Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * toasting.c
4 : : * This file contains routines to support creation of toast tables
5 : : *
6 : : *
7 : : * Portions Copyright (c) 1996-2025, 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"
18 : : #include "access/toast_compression.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/toasting.h"
30 : : #include "miscadmin.h"
31 : : #include "nodes/makefuncs.h"
32 : : #include "utils/fmgroids.h"
33 : : #include "utils/rel.h"
34 : : #include "utils/syscache.h"
35 : :
36 : : static void CheckAndCreateToastTable(Oid relOid, Datum reloptions,
37 : : LOCKMODE lockmode, bool check,
38 : : Oid OIDOldToast);
39 : : static bool create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid,
40 : : Datum reloptions, LOCKMODE lockmode, bool check,
41 : : Oid OIDOldToast);
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
4171 simon@2ndQuadrant.co 58 :CBC 14640 : AlterTableCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
59 : : {
1473 akapila@postgresql.o 60 : 14640 : CheckAndCreateToastTable(relOid, reloptions, lockmode, true, InvalidOid);
4171 simon@2ndQuadrant.co 61 : 14640 : }
62 : :
63 : : void
1473 akapila@postgresql.o 64 : 432 : NewHeapCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode,
65 : : Oid OIDOldToast)
66 : : {
67 : 432 : CheckAndCreateToastTable(relOid, reloptions, lockmode, false, OIDOldToast);
4171 simon@2ndQuadrant.co 68 : 432 : }
69 : :
70 : : void
71 : 18821 : NewRelationCreateToastTable(Oid relOid, Datum reloptions)
72 : : {
1473 akapila@postgresql.o 73 : 18821 : CheckAndCreateToastTable(relOid, reloptions, AccessExclusiveLock, false,
74 : : InvalidOid);
4171 simon@2ndQuadrant.co 75 : 18821 : }
76 : :
77 : : static void
1473 akapila@postgresql.o 78 : 33893 : CheckAndCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode,
79 : : bool check, Oid OIDOldToast)
80 : : {
81 : : Relation rel;
82 : :
2420 andres@anarazel.de 83 : 33893 : rel = table_open(relOid, lockmode);
84 : :
85 : : /* create_toast_table does all the work */
1473 akapila@postgresql.o 86 : 33893 : (void) create_toast_table(rel, InvalidOid, InvalidOid, reloptions, lockmode,
87 : : check, OIDOldToast);
88 : :
2420 andres@anarazel.de 89 : 33893 : table_close(rel, NoLock);
6977 tgl@sss.pgh.pa.us 90 : 33893 : }
91 : :
92 : : /*
93 : : * Create a toast table during bootstrap
94 : : *
95 : : * Here we need to prespecify the OIDs of the toast table and its index
96 : : */
97 : : void
98 : 1750 : BootstrapToastTable(char *relName, Oid toastOid, Oid toastIndexOid)
99 : : {
100 : : Relation rel;
101 : :
2420 andres@anarazel.de 102 : 1750 : rel = table_openrv(makeRangeVar(NULL, relName, -1), AccessExclusiveLock);
103 : :
4570 kgrittn@postgresql.o 104 [ - + ]: 1750 : if (rel->rd_rel->relkind != RELKIND_RELATION &&
4570 kgrittn@postgresql.o 105 [ # # ]:UBC 0 : rel->rd_rel->relkind != RELKIND_MATVIEW)
1521 peter@eisentraut.org 106 [ # # ]: 0 : elog(ERROR, "\"%s\" is not a table or materialized view",
107 : : relName);
108 : :
109 : : /* create_toast_table does all the work */
4171 simon@2ndQuadrant.co 110 [ - + ]:CBC 1750 : if (!create_toast_table(rel, toastOid, toastIndexOid, (Datum) 0,
111 : : AccessExclusiveLock, false, InvalidOid))
6977 tgl@sss.pgh.pa.us 112 [ # # ]:UBC 0 : elog(ERROR, "\"%s\" does not require a toast table",
113 : : relName);
114 : :
2420 andres@anarazel.de 115 :CBC 1750 : table_close(rel, NoLock);
6977 tgl@sss.pgh.pa.us 116 : 1750 : }
117 : :
118 : :
119 : : /*
120 : : * create_toast_table --- internal workhorse
121 : : *
122 : : * rel is already opened and locked
123 : : * toastOid and toastIndexOid are normally InvalidOid, but during
124 : : * bootstrap they can be nonzero to specify hand-assigned OIDs
125 : : */
126 : : static bool
4171 simon@2ndQuadrant.co 127 : 35643 : create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid,
128 : : Datum reloptions, LOCKMODE lockmode, bool check,
129 : : Oid OIDOldToast)
130 : : {
6977 tgl@sss.pgh.pa.us 131 : 35643 : Oid relOid = RelationGetRelid(rel);
132 : : HeapTuple reltup;
133 : : TupleDesc tupdesc;
134 : : bool shared_relation;
135 : : bool mapped_relation;
136 : : Relation toast_rel;
137 : : Relation class_rel;
138 : : Oid toast_relid;
139 : : Oid namespaceid;
140 : : char toast_relname[NAMEDATALEN];
141 : : char toast_idxname[NAMEDATALEN];
142 : : IndexInfo *indexInfo;
143 : : Oid collationIds[2];
144 : : Oid opclassIds[2];
145 : : int16 coloptions[2];
146 : : ObjectAddress baseobject,
147 : : toastobject;
148 : :
149 : : /*
150 : : * Is it already toasted?
151 : : */
152 [ + + ]: 35643 : if (rel->rd_rel->reltoastrelid != InvalidOid)
153 : 5283 : return false;
154 : :
155 : : /*
156 : : * Check to see whether the table actually needs a TOAST table.
157 : : */
4048 bruce@momjian.us 158 [ + + ]: 30360 : if (!IsBinaryUpgrade)
159 : : {
160 : : /* Normal mode, normal check */
161 [ + + ]: 28638 : if (!needs_toast_table(rel))
162 : 20206 : return false;
163 : : }
164 : : else
165 : : {
166 : : /*
167 : : * In binary-upgrade mode, create a TOAST table if and only if
168 : : * pg_upgrade told us to (ie, a TOAST table OID has been provided).
169 : : *
170 : : * This indicates that the old cluster had a TOAST table for the
171 : : * current table. We must create a TOAST table to receive the old
172 : : * TOAST file, even if the table seems not to need one.
173 : : *
174 : : * Contrariwise, if the old cluster did not have a TOAST table, we
175 : : * should be able to get along without one even if the new version's
176 : : * needs_toast_table rules suggest we should have one. There is a lot
177 : : * of daylight between where we will create a TOAST table and where
178 : : * one is really necessary to avoid failures, so small cross-version
179 : : * differences in the when-to-create heuristic shouldn't be a problem.
180 : : * If we tried to create a TOAST table anyway, we would have the
181 : : * problem that it might take up an OID that will conflict with some
182 : : * old-cluster table we haven't seen yet.
183 : : */
1887 tgl@sss.pgh.pa.us 184 [ + + ]: 1722 : if (!OidIsValid(binary_upgrade_next_toast_pg_class_oid))
4048 bruce@momjian.us 185 : 1452 : return false;
186 : : }
187 : :
188 : : /*
189 : : * If requested check lockmode is sufficient. This is a cross check in
190 : : * case of errors or conflicting decisions in earlier code.
191 : : */
4171 simon@2ndQuadrant.co 192 [ + + - + ]: 8702 : if (check && lockmode != AccessExclusiveLock)
4171 simon@2ndQuadrant.co 193 [ # # ]:UBC 0 : elog(ERROR, "AccessExclusiveLock required to add toast table.");
194 : :
195 : : /*
196 : : * Create the toast table and its index
197 : : */
6977 tgl@sss.pgh.pa.us 198 :CBC 8702 : snprintf(toast_relname, sizeof(toast_relname),
199 : : "pg_toast_%u", relOid);
200 : 8702 : snprintf(toast_idxname, sizeof(toast_idxname),
201 : : "pg_toast_%u_index", relOid);
202 : :
203 : : /* this is pretty painful... need a tuple descriptor */
2482 andres@anarazel.de 204 : 8702 : tupdesc = CreateTemplateTupleDesc(3);
6977 tgl@sss.pgh.pa.us 205 : 8702 : TupleDescInitEntry(tupdesc, (AttrNumber) 1,
206 : : "chunk_id",
207 : : OIDOID,
208 : : -1, 0);
209 : 8702 : TupleDescInitEntry(tupdesc, (AttrNumber) 2,
210 : : "chunk_seq",
211 : : INT4OID,
212 : : -1, 0);
213 : 8702 : TupleDescInitEntry(tupdesc, (AttrNumber) 3,
214 : : "chunk_data",
215 : : BYTEAOID,
216 : : -1, 0);
217 : :
218 : : /*
219 : : * Ensure that the toast table doesn't itself get toasted, or we'll be
220 : : * toast :-(. This is essential for chunk_data because type bytea is
221 : : * toastable; hit the other two just to be sure.
222 : : */
2012 223 : 8702 : TupleDescAttr(tupdesc, 0)->attstorage = TYPSTORAGE_PLAIN;
224 : 8702 : TupleDescAttr(tupdesc, 1)->attstorage = TYPSTORAGE_PLAIN;
225 : 8702 : TupleDescAttr(tupdesc, 2)->attstorage = TYPSTORAGE_PLAIN;
226 : :
227 : : /* Toast field should not be compressed */
1632 rhaas@postgresql.org 228 : 8702 : TupleDescAttr(tupdesc, 0)->attcompression = InvalidCompressionMethod;
229 : 8702 : TupleDescAttr(tupdesc, 1)->attcompression = InvalidCompressionMethod;
230 : 8702 : TupleDescAttr(tupdesc, 2)->attcompression = InvalidCompressionMethod;
231 : :
232 : : /*
233 : : * Toast tables for regular relations go in pg_toast; those for temp
234 : : * relations go into the per-backend temp-toast-table namespace.
235 : : */
4030 bruce@momjian.us 236 [ + + ]: 8702 : if (isTempOrTempToastNamespace(rel->rd_rel->relnamespace))
6618 tgl@sss.pgh.pa.us 237 : 472 : namespaceid = GetTempToastNamespace();
238 : : else
239 : 8230 : namespaceid = PG_TOAST_NAMESPACE;
240 : :
241 : : /* Toast table is shared if and only if its parent is. */
2363 peter@eisentraut.org 242 : 8702 : shared_relation = rel->rd_rel->relisshared;
243 : :
244 : : /* It's mapped if and only if its parent is, too */
245 [ + + + - : 8702 : mapped_relation = RelationIsMapped(rel);
+ - + - +
- + + ]
246 : :
6977 tgl@sss.pgh.pa.us 247 : 17404 : toast_relid = heap_create_with_catalog(toast_relname,
248 : : namespaceid,
249 : 8702 : rel->rd_rel->reltablespace,
250 : : toastOid,
251 : : InvalidOid,
252 : : InvalidOid,
253 : 8702 : rel->rd_rel->relowner,
254 : : table_relation_toast_am(rel),
255 : : tupdesc,
256 : : NIL,
257 : : RELKIND_TOASTVALUE,
5381 rhaas@postgresql.org 258 : 8702 : rel->rd_rel->relpersistence,
259 : : shared_relation,
260 : : mapped_relation,
261 : : ONCOMMIT_NOOP,
262 : : reloptions,
263 : : false,
264 : : true,
265 : : true,
266 : : OIDOldToast,
267 : : NULL);
5522 268 [ - + ]: 8702 : Assert(toast_relid != InvalidOid);
269 : :
270 : : /* make the toast relation visible, else table_open will fail */
6977 tgl@sss.pgh.pa.us 271 : 8702 : CommandCounterIncrement();
272 : :
273 : : /* ShareLock is not really needed here, but take it anyway */
2420 andres@anarazel.de 274 : 8702 : toast_rel = table_open(toast_relid, ShareLock);
275 : :
276 : : /*
277 : : * Create unique index on chunk_id, chunk_seq.
278 : : *
279 : : * NOTE: the normal TOAST access routines could actually function with a
280 : : * single-column index on chunk_id only. However, the slice access
281 : : * routines use both columns for faster access to an individual chunk. In
282 : : * addition, we want it to be unique as a check against the possibility of
283 : : * duplicate TOAST chunk OIDs. The index might also be a little more
284 : : * efficient this way, since btree isn't all that happy with large numbers
285 : : * of equal keys.
286 : : */
287 : :
6977 tgl@sss.pgh.pa.us 288 : 8702 : indexInfo = makeNode(IndexInfo);
289 : 8702 : indexInfo->ii_NumIndexAttrs = 2;
2709 teodor@sigaev.ru 290 : 8702 : indexInfo->ii_NumIndexKeyAttrs = 2;
2704 291 : 8702 : indexInfo->ii_IndexAttrNumbers[0] = 1;
292 : 8702 : indexInfo->ii_IndexAttrNumbers[1] = 2;
6977 tgl@sss.pgh.pa.us 293 : 8702 : indexInfo->ii_Expressions = NIL;
294 : 8702 : indexInfo->ii_ExpressionsState = NIL;
295 : 8702 : indexInfo->ii_Predicate = NIL;
3098 andres@anarazel.de 296 : 8702 : indexInfo->ii_PredicateState = NULL;
5752 tgl@sss.pgh.pa.us 297 : 8702 : indexInfo->ii_ExclusionOps = NULL;
298 : 8702 : indexInfo->ii_ExclusionProcs = NULL;
299 : 8702 : indexInfo->ii_ExclusionStrats = NULL;
6977 300 : 8702 : indexInfo->ii_Unique = true;
1311 peter@eisentraut.org 301 : 8702 : indexInfo->ii_NullsNotDistinct = false;
6561 tgl@sss.pgh.pa.us 302 : 8702 : indexInfo->ii_ReadyForInserts = true;
1333 pg@bowt.ie 303 : 8702 : indexInfo->ii_CheckedUnchanged = false;
304 : 8702 : indexInfo->ii_IndexUnchanged = false;
6952 tgl@sss.pgh.pa.us 305 : 8702 : indexInfo->ii_Concurrent = false;
6561 306 : 8702 : indexInfo->ii_BrokenHotChain = false;
2773 rhaas@postgresql.org 307 : 8702 : indexInfo->ii_ParallelWorkers = 0;
2787 alvherre@alvh.no-ip. 308 : 8702 : indexInfo->ii_Am = BTREE_AM_OID;
3131 tgl@sss.pgh.pa.us 309 : 8702 : indexInfo->ii_AmCache = NULL;
310 : 8702 : indexInfo->ii_Context = CurrentMemoryContext;
311 : :
745 peter@eisentraut.org 312 : 8702 : collationIds[0] = InvalidOid;
313 : 8702 : collationIds[1] = InvalidOid;
314 : :
315 : 8702 : opclassIds[0] = OID_BTREE_OPS_OID;
316 : 8702 : opclassIds[1] = INT4_BTREE_OPS_OID;
317 : :
6815 tgl@sss.pgh.pa.us 318 : 8702 : coloptions[0] = 0;
319 : 8702 : coloptions[1] = 0;
320 : :
5164 rhaas@postgresql.org 321 : 8702 : index_create(toast_rel, toast_idxname, toastIndexOid, InvalidOid,
322 : : InvalidOid, InvalidOid,
323 : : indexInfo,
5203 bruce@momjian.us 324 : 8702 : list_make2("chunk_id", "chunk_seq"),
325 : : BTREE_AM_OID,
326 : 8702 : rel->rd_rel->reltablespace,
327 : : collationIds, opclassIds, NULL, coloptions, NULL, (Datum) 0,
328 : : INDEX_CREATE_IS_PRIMARY, 0, true, true, NULL);
329 : :
2420 andres@anarazel.de 330 : 8702 : table_close(toast_rel, NoLock);
331 : :
332 : : /*
333 : : * Store the toast table's OID in the parent relation's pg_class row
334 : : */
335 : 8702 : class_rel = table_open(RelationRelationId, RowExclusiveLock);
336 : :
6977 tgl@sss.pgh.pa.us 337 [ + + ]: 8702 : if (!IsBootstrapProcessingMode())
338 : : {
339 : : /* normal case, use a transactional update */
347 noah@leadboat.com 340 : 6952 : reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
341 [ - + ]: 6952 : if (!HeapTupleIsValid(reltup))
347 noah@leadboat.com 342 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for relation %u", relOid);
343 : :
347 noah@leadboat.com 344 :CBC 6952 : ((Form_pg_class) GETSTRUCT(reltup))->reltoastrelid = toast_relid;
345 : :
3140 alvherre@alvh.no-ip. 346 : 6952 : CatalogTupleUpdate(class_rel, &reltup->t_self, reltup);
347 : : }
348 : : else
349 : : {
350 : : /* While bootstrapping, we cannot UPDATE, so overwrite in-place */
351 : :
352 : : ScanKeyData key[1];
353 : : void *state;
354 : :
347 noah@leadboat.com 355 : 1750 : ScanKeyInit(&key[0],
356 : : Anum_pg_class_oid,
357 : : BTEqualStrategyNumber, F_OIDEQ,
358 : : ObjectIdGetDatum(relOid));
359 : 1750 : systable_inplace_update_begin(class_rel, ClassOidIndexId, true,
360 : : NULL, 1, key, &reltup, &state);
361 [ - + ]: 1750 : if (!HeapTupleIsValid(reltup))
347 noah@leadboat.com 362 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for relation %u", relOid);
363 : :
347 noah@leadboat.com 364 :CBC 1750 : ((Form_pg_class) GETSTRUCT(reltup))->reltoastrelid = toast_relid;
365 : :
366 : 1750 : systable_inplace_update_finish(state, reltup);
367 : : }
368 : :
6977 tgl@sss.pgh.pa.us 369 : 8702 : heap_freetuple(reltup);
370 : :
2420 andres@anarazel.de 371 : 8702 : table_close(class_rel, RowExclusiveLock);
372 : :
373 : : /*
374 : : * Register dependency from the toast table to the main, so that the toast
375 : : * table will be deleted if the main is. Skip this in bootstrap mode.
376 : : */
6977 tgl@sss.pgh.pa.us 377 [ + + ]: 8702 : if (!IsBootstrapProcessingMode())
378 : : {
379 : 6952 : baseobject.classId = RelationRelationId;
380 : 6952 : baseobject.objectId = relOid;
381 : 6952 : baseobject.objectSubId = 0;
382 : 6952 : toastobject.classId = RelationRelationId;
383 : 6952 : toastobject.objectId = toast_relid;
384 : 6952 : toastobject.objectSubId = 0;
385 : :
386 : 6952 : recordDependencyOn(&toastobject, &baseobject, DEPENDENCY_INTERNAL);
387 : : }
388 : :
389 : : /*
390 : : * Make changes visible
391 : : */
392 : 8702 : CommandCounterIncrement();
393 : :
394 : 8702 : return true;
395 : : }
396 : :
397 : : /*
398 : : * Check to see whether the table needs a TOAST table.
399 : : */
400 : : static bool
401 : 28638 : needs_toast_table(Relation rel)
402 : : {
403 : : /*
404 : : * No need to create a TOAST table for partitioned tables.
405 : : */
2725 rhaas@postgresql.org 406 [ + + ]: 28638 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
407 : 4096 : return false;
408 : :
409 : : /*
410 : : * We cannot allow toasting a shared relation after initdb (because
411 : : * there's no way to mark it toasted in other databases' pg_class).
412 : : */
2363 peter@eisentraut.org 413 [ + + + + ]: 24542 : if (rel->rd_rel->relisshared && !IsBootstrapProcessingMode())
414 : 336 : return false;
415 : :
416 : : /*
417 : : * Ignore attempts to create toast tables on catalog tables after initdb.
418 : : * Which catalogs get toast tables is explicitly chosen in catalog/pg_*.h.
419 : : * (We could get here via some ALTER TABLE command if the catalog doesn't
420 : : * have a toast table.)
421 : : */
422 [ + + + + ]: 24206 : if (IsCatalogRelation(rel) && !IsBootstrapProcessingMode())
423 : 2160 : return false;
424 : :
425 : : /* Otherwise, let the AM decide. */
2300 rhaas@postgresql.org 426 : 22046 : return table_relation_needs_toast_table(rel);
427 : : }
|