LCOV - code coverage report
Current view: top level - src/backend/catalog - toasting.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 113 118 95.8 %
Date: 2024-04-25 19:11:21 Functions: 7 7 100.0 %
Legend: Lines: hit not hit

          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-2024, 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/rel.h"
      33             : #include "utils/syscache.h"
      34             : 
      35             : static void CheckAndCreateToastTable(Oid relOid, Datum reloptions,
      36             :                                      LOCKMODE lockmode, bool check,
      37             :                                      Oid OIDOldToast);
      38             : static bool create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid,
      39             :                                Datum reloptions, LOCKMODE lockmode, bool check,
      40             :                                Oid OIDOldToast);
      41             : static bool needs_toast_table(Relation rel);
      42             : 
      43             : 
      44             : /*
      45             :  * CreateToastTable variants
      46             :  *      If the table needs a toast table, and doesn't already have one,
      47             :  *      then create a toast table for it.
      48             :  *
      49             :  * reloptions for the toast table can be passed, too.  Pass (Datum) 0
      50             :  * for default reloptions.
      51             :  *
      52             :  * We expect the caller to have verified that the relation is a table and have
      53             :  * already done any necessary permission checks.  Callers expect this function
      54             :  * to end with CommandCounterIncrement if it makes any changes.
      55             :  */
      56             : void
      57       31792 : AlterTableCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
      58             : {
      59       31792 :     CheckAndCreateToastTable(relOid, reloptions, lockmode, true, InvalidOid);
      60       31792 : }
      61             : 
      62             : void
      63         664 : NewHeapCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode,
      64             :                         Oid OIDOldToast)
      65             : {
      66         664 :     CheckAndCreateToastTable(relOid, reloptions, lockmode, false, OIDOldToast);
      67         664 : }
      68             : 
      69             : void
      70       36024 : NewRelationCreateToastTable(Oid relOid, Datum reloptions)
      71             : {
      72       36024 :     CheckAndCreateToastTable(relOid, reloptions, AccessExclusiveLock, false,
      73             :                              InvalidOid);
      74       36024 : }
      75             : 
      76             : static void
      77       68480 : CheckAndCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode,
      78             :                          bool check, Oid OIDOldToast)
      79             : {
      80             :     Relation    rel;
      81             : 
      82       68480 :     rel = table_open(relOid, lockmode);
      83             : 
      84             :     /* create_toast_table does all the work */
      85       68480 :     (void) create_toast_table(rel, InvalidOid, InvalidOid, reloptions, lockmode,
      86             :                               check, OIDOldToast);
      87             : 
      88       68480 :     table_close(rel, NoLock);
      89       68480 : }
      90             : 
      91             : /*
      92             :  * Create a toast table during bootstrap
      93             :  *
      94             :  * Here we need to prespecify the OIDs of the toast table and its index
      95             :  */
      96             : void
      97        2880 : BootstrapToastTable(char *relName, Oid toastOid, Oid toastIndexOid)
      98             : {
      99             :     Relation    rel;
     100             : 
     101        2880 :     rel = table_openrv(makeRangeVar(NULL, relName, -1), AccessExclusiveLock);
     102             : 
     103        2880 :     if (rel->rd_rel->relkind != RELKIND_RELATION &&
     104           0 :         rel->rd_rel->relkind != RELKIND_MATVIEW)
     105           0 :         elog(ERROR, "\"%s\" is not a table or materialized view",
     106             :              relName);
     107             : 
     108             :     /* create_toast_table does all the work */
     109        2880 :     if (!create_toast_table(rel, toastOid, toastIndexOid, (Datum) 0,
     110             :                             AccessExclusiveLock, false, InvalidOid))
     111           0 :         elog(ERROR, "\"%s\" does not require a toast table",
     112             :              relName);
     113             : 
     114        2880 :     table_close(rel, NoLock);
     115        2880 : }
     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       71360 : create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid,
     127             :                    Datum reloptions, LOCKMODE lockmode, bool check,
     128             :                    Oid OIDOldToast)
     129             : {
     130       71360 :     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       71360 :     if (rel->rd_rel->reltoastrelid != InvalidOid)
     152       12032 :         return false;
     153             : 
     154             :     /*
     155             :      * Check to see whether the table actually needs a TOAST table.
     156             :      */
     157       59328 :     if (!IsBinaryUpgrade)
     158             :     {
     159             :         /* Normal mode, normal check */
     160       56178 :         if (!needs_toast_table(rel))
     161       40760 :             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             :          */
     183        3150 :         if (!OidIsValid(binary_upgrade_next_toast_pg_class_oid))
     184        2626 :             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       15942 :     if (check && lockmode != AccessExclusiveLock)
     192           0 :         elog(ERROR, "AccessExclusiveLock required to add toast table.");
     193             : 
     194             :     /*
     195             :      * Create the toast table and its index
     196             :      */
     197       15942 :     snprintf(toast_relname, sizeof(toast_relname),
     198             :              "pg_toast_%u", relOid);
     199       15942 :     snprintf(toast_idxname, sizeof(toast_idxname),
     200             :              "pg_toast_%u_index", relOid);
     201             : 
     202             :     /* this is pretty painful...  need a tuple descriptor */
     203       15942 :     tupdesc = CreateTemplateTupleDesc(3);
     204       15942 :     TupleDescInitEntry(tupdesc, (AttrNumber) 1,
     205             :                        "chunk_id",
     206             :                        OIDOID,
     207             :                        -1, 0);
     208       15942 :     TupleDescInitEntry(tupdesc, (AttrNumber) 2,
     209             :                        "chunk_seq",
     210             :                        INT4OID,
     211             :                        -1, 0);
     212       15942 :     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       15942 :     TupleDescAttr(tupdesc, 0)->attstorage = TYPSTORAGE_PLAIN;
     223       15942 :     TupleDescAttr(tupdesc, 1)->attstorage = TYPSTORAGE_PLAIN;
     224       15942 :     TupleDescAttr(tupdesc, 2)->attstorage = TYPSTORAGE_PLAIN;
     225             : 
     226             :     /* Toast field should not be compressed */
     227       15942 :     TupleDescAttr(tupdesc, 0)->attcompression = InvalidCompressionMethod;
     228       15942 :     TupleDescAttr(tupdesc, 1)->attcompression = InvalidCompressionMethod;
     229       15942 :     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       15942 :     if (isTempOrTempToastNamespace(rel->rd_rel->relnamespace))
     236         904 :         namespaceid = GetTempToastNamespace();
     237             :     else
     238       15038 :         namespaceid = PG_TOAST_NAMESPACE;
     239             : 
     240             :     /* Toast table is shared if and only if its parent is. */
     241       15942 :     shared_relation = rel->rd_rel->relisshared;
     242             : 
     243             :     /* It's mapped if and only if its parent is, too */
     244       15942 :     mapped_relation = RelationIsMapped(rel);
     245             : 
     246       31884 :     toast_relid = heap_create_with_catalog(toast_relname,
     247             :                                            namespaceid,
     248       15942 :                                            rel->rd_rel->reltablespace,
     249             :                                            toastOid,
     250             :                                            InvalidOid,
     251             :                                            InvalidOid,
     252       15942 :                                            rel->rd_rel->relowner,
     253             :                                            table_relation_toast_am(rel),
     254             :                                            tupdesc,
     255             :                                            NIL,
     256             :                                            RELKIND_TOASTVALUE,
     257       15942 :                                            rel->rd_rel->relpersistence,
     258             :                                            shared_relation,
     259             :                                            mapped_relation,
     260             :                                            ONCOMMIT_NOOP,
     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 */
     270       15942 :     CommandCounterIncrement();
     271             : 
     272             :     /* ShareLock is not really needed here, but take it anyway */
     273       15942 :     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       15942 :     indexInfo = makeNode(IndexInfo);
     288       15942 :     indexInfo->ii_NumIndexAttrs = 2;
     289       15942 :     indexInfo->ii_NumIndexKeyAttrs = 2;
     290       15942 :     indexInfo->ii_IndexAttrNumbers[0] = 1;
     291       15942 :     indexInfo->ii_IndexAttrNumbers[1] = 2;
     292       15942 :     indexInfo->ii_Expressions = NIL;
     293       15942 :     indexInfo->ii_ExpressionsState = NIL;
     294       15942 :     indexInfo->ii_Predicate = NIL;
     295       15942 :     indexInfo->ii_PredicateState = NULL;
     296       15942 :     indexInfo->ii_ExclusionOps = NULL;
     297       15942 :     indexInfo->ii_ExclusionProcs = NULL;
     298       15942 :     indexInfo->ii_ExclusionStrats = NULL;
     299       15942 :     indexInfo->ii_Unique = true;
     300       15942 :     indexInfo->ii_NullsNotDistinct = false;
     301       15942 :     indexInfo->ii_ReadyForInserts = true;
     302       15942 :     indexInfo->ii_CheckedUnchanged = false;
     303       15942 :     indexInfo->ii_IndexUnchanged = false;
     304       15942 :     indexInfo->ii_Concurrent = false;
     305       15942 :     indexInfo->ii_BrokenHotChain = false;
     306       15942 :     indexInfo->ii_ParallelWorkers = 0;
     307       15942 :     indexInfo->ii_Am = BTREE_AM_OID;
     308       15942 :     indexInfo->ii_AmCache = NULL;
     309       15942 :     indexInfo->ii_Context = CurrentMemoryContext;
     310             : 
     311       15942 :     collationIds[0] = InvalidOid;
     312       15942 :     collationIds[1] = InvalidOid;
     313             : 
     314       15942 :     opclassIds[0] = OID_BTREE_OPS_OID;
     315       15942 :     opclassIds[1] = INT4_BTREE_OPS_OID;
     316             : 
     317       15942 :     coloptions[0] = 0;
     318       15942 :     coloptions[1] = 0;
     319             : 
     320       15942 :     index_create(toast_rel, toast_idxname, toastIndexOid, InvalidOid,
     321             :                  InvalidOid, InvalidOid,
     322             :                  indexInfo,
     323       15942 :                  list_make2("chunk_id", "chunk_seq"),
     324             :                  BTREE_AM_OID,
     325       15942 :                  rel->rd_rel->reltablespace,
     326             :                  collationIds, opclassIds, NULL, coloptions, NULL, (Datum) 0,
     327             :                  INDEX_CREATE_IS_PRIMARY, 0, true, true, NULL);
     328             : 
     329       15942 :     table_close(toast_rel, NoLock);
     330             : 
     331             :     /*
     332             :      * Store the toast table's OID in the parent relation's pg_class row
     333             :      */
     334       15942 :     class_rel = table_open(RelationRelationId, RowExclusiveLock);
     335             : 
     336       15942 :     reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
     337       15942 :     if (!HeapTupleIsValid(reltup))
     338           0 :         elog(ERROR, "cache lookup failed for relation %u", relOid);
     339             : 
     340       15942 :     ((Form_pg_class) GETSTRUCT(reltup))->reltoastrelid = toast_relid;
     341             : 
     342       15942 :     if (!IsBootstrapProcessingMode())
     343             :     {
     344             :         /* normal case, use a transactional update */
     345       13062 :         CatalogTupleUpdate(class_rel, &reltup->t_self, reltup);
     346             :     }
     347             :     else
     348             :     {
     349             :         /* While bootstrapping, we cannot UPDATE, so overwrite in-place */
     350        2880 :         heap_inplace_update(class_rel, reltup);
     351             :     }
     352             : 
     353       15942 :     heap_freetuple(reltup);
     354             : 
     355       15942 :     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             :      */
     361       15942 :     if (!IsBootstrapProcessingMode())
     362             :     {
     363       13062 :         baseobject.classId = RelationRelationId;
     364       13062 :         baseobject.objectId = relOid;
     365       13062 :         baseobject.objectSubId = 0;
     366       13062 :         toastobject.classId = RelationRelationId;
     367       13062 :         toastobject.objectId = toast_relid;
     368       13062 :         toastobject.objectSubId = 0;
     369             : 
     370       13062 :         recordDependencyOn(&toastobject, &baseobject, DEPENDENCY_INTERNAL);
     371             :     }
     372             : 
     373             :     /*
     374             :      * Make changes visible
     375             :      */
     376       15942 :     CommandCounterIncrement();
     377             : 
     378       15942 :     return true;
     379             : }
     380             : 
     381             : /*
     382             :  * Check to see whether the table needs a TOAST table.
     383             :  */
     384             : static bool
     385       56178 : needs_toast_table(Relation rel)
     386             : {
     387             :     /*
     388             :      * No need to create a TOAST table for partitioned tables.
     389             :      */
     390       56178 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
     391        8514 :         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       47664 :     if (rel->rd_rel->relisshared && !IsBootstrapProcessingMode())
     398         228 :         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             :      */
     406       47436 :     if (IsCatalogRelation(rel) && !IsBootstrapProcessingMode())
     407        3496 :         return false;
     408             : 
     409             :     /* Otherwise, let the AM decide. */
     410       43940 :     return table_relation_needs_toast_table(rel);
     411             : }

Generated by: LCOV version 1.14