PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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-2026, 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/genam.h"
18#include "access/heapam.h"
20#include "access/xact.h"
22#include "catalog/catalog.h"
23#include "catalog/dependency.h"
24#include "catalog/heap.h"
25#include "catalog/index.h"
26#include "catalog/namespace.h"
27#include "catalog/pg_am.h"
29#include "catalog/pg_opclass.h"
30#include "catalog/toasting.h"
31#include "miscadmin.h"
32#include "nodes/makefuncs.h"
33#include "utils/fmgroids.h"
34#include "utils/rel.h"
35#include "utils/syscache.h"
36
37static void CheckAndCreateToastTable(Oid relOid, Datum reloptions,
38 LOCKMODE lockmode, bool check,
41 Datum reloptions, LOCKMODE lockmode, bool check,
43static 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 */
58void
59AlterTableCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
60{
61 CheckAndCreateToastTable(relOid, reloptions, lockmode, true, InvalidOid);
62}
63
64void
65NewHeapCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode,
67{
68 CheckAndCreateToastTable(relOid, reloptions, lockmode, false, OIDOldToast);
69}
70
71void
73{
74 CheckAndCreateToastTable(relOid, reloptions, AccessExclusiveLock, false,
76}
77
78static void
79CheckAndCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode,
80 bool check, Oid OIDOldToast)
81{
82 Relation rel;
83
84 rel = table_open(relOid, lockmode);
85
86 /* create_toast_table does all the work */
87 (void) create_toast_table(rel, InvalidOid, InvalidOid, reloptions, lockmode,
88 check, OIDOldToast);
89
90 table_close(rel, NoLock);
91}
92
93/*
94 * Create a toast table during bootstrap
95 *
96 * Here we need to prespecify the OIDs of the toast table and its index
97 */
98void
100{
101 Relation rel;
102
104
105 if (rel->rd_rel->relkind != RELKIND_RELATION &&
106 rel->rd_rel->relkind != RELKIND_MATVIEW)
107 elog(ERROR, "\"%s\" is not a table or materialized view",
108 relName);
109
110 /* create_toast_table does all the work */
113 elog(ERROR, "\"%s\" does not require a toast table",
114 relName);
115
116 table_close(rel, NoLock);
117}
118
119
120/*
121 * create_toast_table --- internal workhorse
122 *
123 * rel is already opened and locked
124 * toastOid and toastIndexOid are normally InvalidOid, but during
125 * bootstrap they can be nonzero to specify hand-assigned OIDs
126 */
127static bool
129 Datum reloptions, LOCKMODE lockmode, bool check,
131{
132 Oid relOid = RelationGetRelid(rel);
134 TupleDesc tupdesc;
135 bool shared_relation;
136 bool mapped_relation;
137 Relation toast_rel;
143 IndexInfo *indexInfo;
144 Oid collationIds[2];
145 Oid opclassIds[2];
146 int16 coloptions[2];
149
150 /*
151 * Is it already toasted?
152 */
153 if (rel->rd_rel->reltoastrelid != InvalidOid)
154 return false;
155
156 /*
157 * Check to see whether the table actually needs a TOAST table.
158 */
159 if (!IsBinaryUpgrade)
160 {
161 /* Normal mode, normal check */
162 if (!needs_toast_table(rel))
163 return false;
164 }
165 else
166 {
167 /*
168 * In binary-upgrade mode, create a TOAST table if and only if
169 * pg_upgrade told us to (ie, a TOAST table OID has been provided).
170 *
171 * This indicates that the old cluster had a TOAST table for the
172 * current table. We must create a TOAST table to receive the old
173 * TOAST file, even if the table seems not to need one.
174 *
175 * Contrariwise, if the old cluster did not have a TOAST table, we
176 * should be able to get along without one even if the new version's
177 * needs_toast_table rules suggest we should have one. There is a lot
178 * of daylight between where we will create a TOAST table and where
179 * one is really necessary to avoid failures, so small cross-version
180 * differences in the when-to-create heuristic shouldn't be a problem.
181 * If we tried to create a TOAST table anyway, we would have the
182 * problem that it might take up an OID that will conflict with some
183 * old-cluster table we haven't seen yet.
184 */
186 return false;
187 }
188
189 /*
190 * If requested check lockmode is sufficient. This is a cross check in
191 * case of errors or conflicting decisions in earlier code.
192 */
193 if (check && lockmode != AccessExclusiveLock)
194 elog(ERROR, "AccessExclusiveLock required to add toast table.");
195
196 /*
197 * Create the toast table and its index
198 */
200 "pg_toast_%u", relOid);
202 "pg_toast_%u_index", relOid);
203
204 /* this is pretty painful... need a tuple descriptor */
205 tupdesc = CreateTemplateTupleDesc(3);
206 TupleDescInitEntry(tupdesc, (AttrNumber) 1,
207 "chunk_id",
208 OIDOID,
209 -1, 0);
210 TupleDescInitEntry(tupdesc, (AttrNumber) 2,
211 "chunk_seq",
212 INT4OID,
213 -1, 0);
214 TupleDescInitEntry(tupdesc, (AttrNumber) 3,
215 "chunk_data",
216 BYTEAOID,
217 -1, 0);
218
219 /*
220 * Ensure that the toast table doesn't itself get toasted, or we'll be
221 * toast :-(. This is essential for chunk_data because type bytea is
222 * toastable; hit the other two just to be sure.
223 */
224 TupleDescAttr(tupdesc, 0)->attstorage = TYPSTORAGE_PLAIN;
225 TupleDescAttr(tupdesc, 1)->attstorage = TYPSTORAGE_PLAIN;
226 TupleDescAttr(tupdesc, 2)->attstorage = TYPSTORAGE_PLAIN;
227
228 /* Toast field should not be compressed */
229 TupleDescAttr(tupdesc, 0)->attcompression = InvalidCompressionMethod;
230 TupleDescAttr(tupdesc, 1)->attcompression = InvalidCompressionMethod;
231 TupleDescAttr(tupdesc, 2)->attcompression = InvalidCompressionMethod;
232
233 populate_compact_attribute(tupdesc, 0);
234 populate_compact_attribute(tupdesc, 1);
235 populate_compact_attribute(tupdesc, 2);
236
237 TupleDescFinalize(tupdesc);
238
239 /*
240 * Toast tables for regular relations go in pg_toast; those for temp
241 * relations go into the per-backend temp-toast-table namespace.
242 */
243 if (isTempOrTempToastNamespace(rel->rd_rel->relnamespace))
245 else
247
248 /* Toast table is shared if and only if its parent is. */
249 shared_relation = rel->rd_rel->relisshared;
250
251 /* It's mapped if and only if its parent is, too */
253
256 rel->rd_rel->reltablespace,
257 toastOid,
260 rel->rd_rel->relowner,
262 tupdesc,
263 NIL,
265 rel->rd_rel->relpersistence,
269 reloptions,
270 false,
271 true,
272 true,
274 NULL);
276
277 /* make the toast relation visible, else table_open will fail */
279
280 /* ShareLock is not really needed here, but take it anyway */
281 toast_rel = table_open(toast_relid, ShareLock);
282
283 /*
284 * Create unique index on chunk_id, chunk_seq.
285 *
286 * NOTE: the normal TOAST access routines could actually function with a
287 * single-column index on chunk_id only. However, the slice access
288 * routines use both columns for faster access to an individual chunk. In
289 * addition, we want it to be unique as a check against the possibility of
290 * duplicate TOAST chunk OIDs. The index might also be a little more
291 * efficient this way, since btree isn't all that happy with large numbers
292 * of equal keys.
293 */
294
295 indexInfo = makeNode(IndexInfo);
296 indexInfo->ii_NumIndexAttrs = 2;
297 indexInfo->ii_NumIndexKeyAttrs = 2;
298 indexInfo->ii_IndexAttrNumbers[0] = 1;
299 indexInfo->ii_IndexAttrNumbers[1] = 2;
300 indexInfo->ii_Expressions = NIL;
301 indexInfo->ii_ExpressionsState = NIL;
302 indexInfo->ii_Predicate = NIL;
303 indexInfo->ii_PredicateState = NULL;
304 indexInfo->ii_ExclusionOps = NULL;
305 indexInfo->ii_ExclusionProcs = NULL;
306 indexInfo->ii_ExclusionStrats = NULL;
307 indexInfo->ii_Unique = true;
308 indexInfo->ii_NullsNotDistinct = false;
309 indexInfo->ii_ReadyForInserts = true;
310 indexInfo->ii_CheckedUnchanged = false;
311 indexInfo->ii_IndexUnchanged = false;
312 indexInfo->ii_Concurrent = false;
313 indexInfo->ii_BrokenHotChain = false;
314 indexInfo->ii_ParallelWorkers = 0;
315 indexInfo->ii_Am = BTREE_AM_OID;
316 indexInfo->ii_AmCache = NULL;
317 indexInfo->ii_Context = CurrentMemoryContext;
318
321
324
325 coloptions[0] = 0;
326 coloptions[1] = 0;
327
330 indexInfo,
331 list_make2("chunk_id", "chunk_seq"),
333 rel->rd_rel->reltablespace,
335 INDEX_CREATE_IS_PRIMARY, 0, true, true, NULL);
336
337 table_close(toast_rel, NoLock);
338
339 /*
340 * Store the toast table's OID in the parent relation's pg_class row
341 */
343
345 {
346 /* normal case, use a transactional update */
349 elog(ERROR, "cache lookup failed for relation %u", relOid);
350
352
354 }
355 else
356 {
357 /* While bootstrapping, we cannot UPDATE, so overwrite in-place */
358
359 ScanKeyData key[1];
360 void *state;
361
362 ScanKeyInit(&key[0],
365 ObjectIdGetDatum(relOid));
367 NULL, 1, key, &reltup, &state);
369 elog(ERROR, "cache lookup failed for relation %u", relOid);
370
372
374 }
375
377
379
380 /*
381 * Register dependency from the toast table to the main, so that the toast
382 * table will be deleted if the main is. Skip this in bootstrap mode.
383 */
385 {
387 baseobject.objectId = relOid;
388 baseobject.objectSubId = 0;
390 toastobject.objectId = toast_relid;
391 toastobject.objectSubId = 0;
392
394 }
395
396 /*
397 * Make changes visible
398 */
400
401 return true;
402}
403
404/*
405 * Check to see whether the table needs a TOAST table.
406 */
407static bool
409{
410 /*
411 * No need to create a TOAST table for partitioned tables.
412 */
413 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
414 return false;
415
416 /*
417 * We cannot allow toasting a shared relation after initdb (because
418 * there's no way to mark it toasted in other databases' pg_class).
419 */
420 if (rel->rd_rel->relisshared && !IsBootstrapProcessingMode())
421 return false;
422
423 /*
424 * Ignore attempts to create toast tables on catalog tables after initdb.
425 * Which catalogs get toast tables is explicitly chosen in catalog/pg_*.h.
426 * (We could get here via some ALTER TABLE command if the catalog doesn't
427 * have a toast table.)
428 */
430 return false;
431
432 /* Otherwise, let the AM decide. */
434}
int16 AttrNumber
Definition attnum.h:21
#define Assert(condition)
Definition c.h:943
int16_t int16
Definition c.h:619
#define OidIsValid(objectId)
Definition c.h:858
bool IsCatalogRelation(Relation relation)
Definition catalog.c:104
@ DEPENDENCY_INTERNAL
Definition dependency.h:35
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
void systable_inplace_update_begin(Relation relation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, const ScanKeyData *key, HeapTuple *oldtupcopy, void **state)
Definition genam.c:818
void systable_inplace_update_finish(void *state, HeapTuple tuple)
Definition genam.c:894
bool IsBinaryUpgrade
Definition globals.c:123
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:1122
Oid binary_upgrade_next_toast_pg_class_oid
Definition heap.c:82
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
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, const NullableDatum *stattargets, Datum reloptions, uint16 flags, uint16 constr_flags, bool allow_system_table_mods, bool is_internal, Oid *constraintId)
Definition index.c:730
#define INDEX_CREATE_IS_PRIMARY
Definition index.h:67
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
int LOCKMODE
Definition lockdefs.h:26
#define NoLock
Definition lockdefs.h:34
#define AccessExclusiveLock
Definition lockdefs.h:43
#define ShareLock
Definition lockdefs.h:40
#define RowExclusiveLock
Definition lockdefs.h:38
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition makefuncs.c:473
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
#define IsBootstrapProcessingMode()
Definition miscadmin.h:495
bool isTempOrTempToastNamespace(Oid namespaceId)
Definition namespace.c:3745
Oid GetTempToastNamespace(void)
Definition namespace.c:3863
#define makeNode(_type_)
Definition nodes.h:161
FormData_pg_class * Form_pg_class
Definition pg_class.h:160
#define NAMEDATALEN
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition pg_depend.c:47
#define NIL
Definition pg_list.h:68
#define list_make2(x1, x2)
Definition pg_list.h:246
#define snprintf
Definition port.h:260
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
#define InvalidOid
unsigned int Oid
static int fb(int x)
@ ONCOMMIT_NOOP
Definition primnodes.h:59
#define RelationGetRelid(relation)
Definition rel.h:516
#define RelationIsMapped(relation)
Definition rel.h:565
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
#define BTEqualStrategyNumber
Definition stratnum.h:31
bool ii_Unique
Definition execnodes.h:214
uint16 * ii_ExclusionStrats
Definition execnodes.h:206
bool ii_BrokenHotChain
Definition execnodes.h:226
int ii_NumIndexAttrs
Definition execnodes.h:181
void * ii_AmCache
Definition execnodes.h:237
bool ii_CheckedUnchanged
Definition execnodes.h:220
ExprState * ii_PredicateState
Definition execnodes.h:199
Oid * ii_ExclusionOps
Definition execnodes.h:202
bool ii_NullsNotDistinct
Definition execnodes.h:216
int ii_ParallelWorkers
Definition execnodes.h:232
bool ii_Concurrent
Definition execnodes.h:224
int ii_NumIndexKeyAttrs
Definition execnodes.h:183
List * ii_ExpressionsState
Definition execnodes.h:194
List * ii_Expressions
Definition execnodes.h:192
bool ii_IndexUnchanged
Definition execnodes.h:222
Oid * ii_ExclusionProcs
Definition execnodes.h:204
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition execnodes.h:189
MemoryContext ii_Context
Definition execnodes.h:240
bool ii_ReadyForInserts
Definition execnodes.h:218
List * ii_Predicate
Definition execnodes.h:197
Form_pg_class rd_rel
Definition rel.h:111
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition table.c:83
static bool table_relation_needs_toast_table(Relation rel)
Definition tableam.h:1949
static Oid table_relation_toast_am(Relation rel)
Definition tableam.h:1959
#define InvalidCompressionMethod
void BootstrapToastTable(char *relName, Oid toastOid, Oid toastIndexOid)
Definition toasting.c:99
static void CheckAndCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode, bool check, Oid OIDOldToast)
Definition toasting.c:79
void NewHeapCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode, Oid OIDOldToast)
Definition toasting.c:65
void NewRelationCreateToastTable(Oid relOid, Datum reloptions)
Definition toasting.c:72
void AlterTableCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
Definition toasting.c:59
static bool create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid, Datum reloptions, LOCKMODE lockmode, bool check, Oid OIDOldToast)
Definition toasting.c:128
static bool needs_toast_table(Relation rel)
Definition toasting.c:408
TupleDesc CreateTemplateTupleDesc(int natts)
Definition tupdesc.c:165
void TupleDescFinalize(TupleDesc tupdesc)
Definition tupdesc.c:511
void populate_compact_attribute(TupleDesc tupdesc, int attnum)
Definition tupdesc.c:100
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition tupdesc.c:900
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178
void CommandCounterIncrement(void)
Definition xact.c:1130