]> granicus.if.org Git - postgresql/blob - doc/src/sgml/storage.sgml
doc: Use proper em and en dashes
[postgresql] / doc / src / sgml / storage.sgml
1 <!-- doc/src/sgml/storage.sgml -->
2
3 <chapter id="storage">
4
5 <title>Database Physical Storage</title>
6
7 <para>
8 This chapter provides an overview of the physical storage format used by
9 <productname>PostgreSQL</productname> databases.
10 </para>
11
12 <sect1 id="storage-file-layout">
13
14 <title>Database File Layout</title>
15
16 <para>
17 This section describes the storage format at the level of files and
18 directories.
19 </para>
20
21 <para>
22 Traditionally, the configuration and data files used by a database
23 cluster are stored together within the cluster's data
24 directory, commonly referred to as <varname>PGDATA</varname> (after the name of the
25 environment variable that can be used to define it).  A common location for
26 <varname>PGDATA</varname> is <filename>/var/lib/pgsql/data</filename>.  Multiple clusters,
27 managed by different server instances, can exist on the same machine.
28 </para>
29
30 <para>
31 The <varname>PGDATA</varname> directory contains several subdirectories and control
32 files, as shown in <xref linkend="pgdata-contents-table"/>.  In addition to
33 these required items, the cluster configuration files
34 <filename>postgresql.conf</filename>, <filename>pg_hba.conf</filename>, and
35 <filename>pg_ident.conf</filename> are traditionally stored in
36 <varname>PGDATA</varname>, although it is possible to place them elsewhere.
37 </para>
38
39 <table tocentry="1" id="pgdata-contents-table">
40 <title>Contents of <varname>PGDATA</varname></title>
41 <tgroup cols="2">
42 <thead>
43 <row>
44 <entry>
45 Item
46 </entry>
47 <entry>Description</entry>
48 </row>
49 </thead>
50
51 <tbody>
52
53 <row>
54  <entry><filename>PG_VERSION</filename></entry>
55  <entry>A file containing the major version number of <productname>PostgreSQL</productname></entry>
56 </row>
57
58 <row>
59  <entry><filename>base</filename></entry>
60  <entry>Subdirectory containing per-database subdirectories</entry>
61 </row>
62
63 <row>
64  <entry><filename>current_logfiles</filename></entry>
65  <entry>File recording the log file(s) currently written to by the logging
66   collector</entry>
67 </row>
68
69 <row>
70  <entry><filename>global</filename></entry>
71  <entry>Subdirectory containing cluster-wide tables, such as
72  <structname>pg_database</structname></entry>
73 </row>
74
75 <row>
76  <entry><filename>pg_commit_ts</filename></entry>
77  <entry>Subdirectory containing transaction commit timestamp data</entry>
78 </row>
79
80 <row>
81  <entry><filename>pg_dynshmem</filename></entry>
82  <entry>Subdirectory containing files used by the dynamic shared memory
83   subsystem</entry>
84 </row>
85
86 <row>
87  <entry><filename>pg_logical</filename></entry>
88  <entry>Subdirectory containing status data for logical decoding</entry>
89 </row>
90
91 <row>
92  <entry><filename>pg_multixact</filename></entry>
93  <entry>Subdirectory containing multitransaction status data
94   (used for shared row locks)</entry>
95 </row>
96
97 <row>
98  <entry><filename>pg_notify</filename></entry>
99  <entry>Subdirectory containing LISTEN/NOTIFY status data</entry>
100 </row>
101
102 <row>
103  <entry><filename>pg_replslot</filename></entry>
104  <entry>Subdirectory containing replication slot data</entry>
105 </row>
106
107 <row>
108  <entry><filename>pg_serial</filename></entry>
109  <entry>Subdirectory containing information about committed serializable transactions</entry>
110 </row>
111
112 <row>
113  <entry><filename>pg_snapshots</filename></entry>
114  <entry>Subdirectory containing exported snapshots</entry>
115 </row>
116
117 <row>
118  <entry><filename>pg_stat</filename></entry>
119  <entry>Subdirectory containing permanent files for the statistics
120   subsystem</entry>
121 </row>
122
123 <row>
124  <entry><filename>pg_stat_tmp</filename></entry>
125  <entry>Subdirectory containing temporary files for the statistics
126   subsystem</entry>
127 </row>
128
129 <row>
130  <entry><filename>pg_subtrans</filename></entry>
131  <entry>Subdirectory containing subtransaction status data</entry>
132 </row>
133
134 <row>
135  <entry><filename>pg_tblspc</filename></entry>
136  <entry>Subdirectory containing symbolic links to tablespaces</entry>
137 </row>
138
139 <row>
140  <entry><filename>pg_twophase</filename></entry>
141  <entry>Subdirectory containing state files for prepared transactions</entry>
142 </row>
143
144 <row>
145  <entry><filename>pg_wal</filename></entry>
146  <entry>Subdirectory containing WAL (Write Ahead Log) files</entry>
147 </row>
148
149 <row>
150  <entry><filename>pg_xact</filename></entry>
151  <entry>Subdirectory containing transaction commit status data</entry>
152 </row>
153
154 <row>
155  <entry><filename>postgresql.auto.conf</filename></entry>
156  <entry>A file used for storing configuration parameters that are set by
157 <command>ALTER SYSTEM</command></entry>
158 </row>
159
160 <row>
161  <entry><filename>postmaster.opts</filename></entry>
162  <entry>A file recording the command-line options the server was
163 last started with</entry>
164 </row>
165
166 <row>
167  <entry><filename>postmaster.pid</filename></entry>
168  <entry>A lock file recording the current postmaster process ID (PID),
169   cluster data directory path,
170   postmaster start timestamp,
171   port number,
172   Unix-domain socket directory path (empty on Windows),
173   first valid listen_address (IP address or <literal>*</literal>, or empty if
174   not listening on TCP),
175   and shared memory segment ID
176   (this file is not present after server shutdown)</entry>
177 </row>
178
179 </tbody>
180 </tgroup>
181 </table>
182
183 <para>
184 For each database in the cluster there is a subdirectory within
185 <varname>PGDATA</varname><filename>/base</filename>, named after the database's OID in
186 <structname>pg_database</structname>.  This subdirectory is the default location
187 for the database's files; in particular, its system catalogs are stored
188 there.
189 </para>
190
191 <para>
192  Note that the following sections describe the behavior of the builtin
193  <literal>heap</literal> <link linkend="tableam">table access method</link>,
194  and the builtin <link linkend="indexam">index access methods</link>. Due
195  to the extensible nature of <productname>PostgreSQL</productname>, other
196  access methods might work differently.
197 </para>
198
199 <para>
200 Each table and index is stored in a separate file.  For ordinary relations,
201 these files are named after the table or index's <firstterm>filenode</firstterm> number,
202 which can be found in <structname>pg_class</structname>.<structfield>relfilenode</structfield>. But
203 for temporary relations, the file name is of the form
204 <literal>t<replaceable>BBB</replaceable>_<replaceable>FFF</replaceable></literal>, where <replaceable>BBB</replaceable>
205 is the backend ID of the backend which created the file, and <replaceable>FFF</replaceable>
206 is the filenode number.  In either case, in addition to the main file (a/k/a
207 main fork), each table and index has a <firstterm>free space map</firstterm> (see <xref
208 linkend="storage-fsm"/>), which stores information about free space available in
209 the relation.  The free space map is stored in a file named with the filenode
210 number plus the suffix <literal>_fsm</literal>.  Tables also have a
211 <firstterm>visibility map</firstterm>, stored in a fork with the suffix <literal>_vm</literal>,
212 to track which pages are known to have no dead tuples.  The visibility map is
213 described further in <xref linkend="storage-vm"/>.  Unlogged tables and indexes
214 have a third fork, known as the initialization fork, which is stored in a fork
215 with the suffix <literal>_init</literal> (see <xref linkend="storage-init"/>).
216 </para>
217
218 <caution>
219 <para>
220 Note that while a table's filenode often matches its OID, this is
221 <emphasis>not</emphasis> necessarily the case; some operations, like
222 <command>TRUNCATE</command>, <command>REINDEX</command>, <command>CLUSTER</command> and some forms
223 of <command>ALTER TABLE</command>, can change the filenode while preserving the OID.
224 Avoid assuming that filenode and table OID are the same.
225 Also, for certain system catalogs including <structname>pg_class</structname> itself,
226 <structname>pg_class</structname>.<structfield>relfilenode</structfield> contains zero.  The
227 actual filenode number of these catalogs is stored in a lower-level data
228 structure, and can be obtained using the <function>pg_relation_filenode()</function>
229 function.
230 </para>
231 </caution>
232
233 <para>
234 When a table or index exceeds 1 GB, it is divided into gigabyte-sized
235 <firstterm>segments</firstterm>.  The first segment's file name is the same as the
236 filenode; subsequent segments are named filenode.1, filenode.2, etc.
237 This arrangement avoids problems on platforms that have file size limitations.
238 (Actually, 1 GB is just the default segment size.  The segment size can be
239 adjusted using the configuration option <option>--with-segsize</option>
240 when building <productname>PostgreSQL</productname>.)
241 In principle, free space map and visibility map forks could require multiple
242 segments as well, though this is unlikely to happen in practice.
243 </para>
244
245 <para>
246 A table that has columns with potentially large entries will have an
247 associated <firstterm>TOAST</firstterm> table, which is used for out-of-line storage of
248 field values that are too large to keep in the table rows proper.
249 <structname>pg_class</structname>.<structfield>reltoastrelid</structfield> links from a table to
250 its <acronym>TOAST</acronym> table, if any.
251 See <xref linkend="storage-toast"/> for more information.
252 </para>
253
254 <para>
255 The contents of tables and indexes are discussed further in
256 <xref linkend="storage-page-layout"/>.
257 </para>
258
259 <para>
260 Tablespaces make the scenario more complicated.  Each user-defined tablespace
261 has a symbolic link inside the <varname>PGDATA</varname><filename>/pg_tblspc</filename>
262 directory, which points to the physical tablespace directory (i.e., the
263 location specified in the tablespace's <command>CREATE TABLESPACE</command> command).
264 This symbolic link is named after
265 the tablespace's OID.  Inside the physical tablespace directory there is
266 a subdirectory with a name that depends on the <productname>PostgreSQL</productname>
267 server version, such as <literal>PG_9.0_201008051</literal>.  (The reason for using
268 this subdirectory is so that successive versions of the database can use
269 the same <command>CREATE TABLESPACE</command> location value without conflicts.)
270 Within the version-specific subdirectory, there is
271 a subdirectory for each database that has elements in the tablespace, named
272 after the database's OID.  Tables and indexes are stored within that
273 directory, using the filenode naming scheme.
274 The <literal>pg_default</literal> tablespace is not accessed through
275 <filename>pg_tblspc</filename>, but corresponds to
276 <varname>PGDATA</varname><filename>/base</filename>.  Similarly, the <literal>pg_global</literal>
277 tablespace is not accessed through <filename>pg_tblspc</filename>, but corresponds to
278 <varname>PGDATA</varname><filename>/global</filename>.
279 </para>
280
281 <para>
282 The <function>pg_relation_filepath()</function> function shows the entire path
283 (relative to <varname>PGDATA</varname>) of any relation.  It is often useful
284 as a substitute for remembering many of the above rules.  But keep in
285 mind that this function just gives the name of the first segment of the
286 main fork of the relation &mdash; you may need to append a segment number
287 and/or <literal>_fsm</literal>, <literal>_vm</literal>, or <literal>_init</literal> to find all
288 the files associated with the relation.
289 </para>
290
291 <para>
292 Temporary files (for operations such as sorting more data than can fit in
293 memory) are created within <varname>PGDATA</varname><filename>/base/pgsql_tmp</filename>,
294 or within a <filename>pgsql_tmp</filename> subdirectory of a tablespace directory
295 if a tablespace other than <literal>pg_default</literal> is specified for them.
296 The name of a temporary file has the form
297 <filename>pgsql_tmp<replaceable>PPP</replaceable>.<replaceable>NNN</replaceable></filename>,
298 where <replaceable>PPP</replaceable> is the PID of the owning backend and
299 <replaceable>NNN</replaceable> distinguishes different temporary files of that backend.
300 </para>
301
302 </sect1>
303
304 <sect1 id="storage-toast">
305
306 <title>TOAST</title>
307
308     <indexterm>
309      <primary>TOAST</primary>
310     </indexterm>
311     <indexterm><primary>sliced bread</primary><see>TOAST</see></indexterm>
312
313 <para>
314 This section provides an overview of <acronym>TOAST</acronym> (The
315 Oversized-Attribute Storage Technique).
316 </para>
317
318 <para>
319 <productname>PostgreSQL</productname> uses a fixed page size (commonly
320 8 kB), and does not allow tuples to span multiple pages.  Therefore, it is
321 not possible to store very large field values directly.  To overcome
322 this limitation, large field values are compressed and/or broken up into
323 multiple physical rows.  This happens transparently to the user, with only
324 small impact on most of the backend code.  The technique is affectionately
325 known as <acronym>TOAST</acronym> (or <quote>the best thing since sliced bread</quote>).
326 The <acronym>TOAST</acronym> infrastructure is also used to improve handling of
327 large data values in-memory.
328 </para>
329
330 <para>
331 Only certain data types support <acronym>TOAST</acronym> &mdash; there is no need to
332 impose the overhead on data types that cannot produce large field values.
333 To support <acronym>TOAST</acronym>, a data type must have a variable-length
334 (<firstterm>varlena</firstterm>) representation, in which, ordinarily, the first
335 four-byte word of any stored value contains the total length of the value in
336 bytes (including itself).  <acronym>TOAST</acronym> does not constrain the rest
337 of the data type's representation.  The special representations collectively
338 called <firstterm><acronym>TOAST</acronym>ed values</firstterm> work by modifying or
339 reinterpreting this initial length word.  Therefore, the C-level functions
340 supporting a <acronym>TOAST</acronym>-able data type must be careful about how they
341 handle potentially <acronym>TOAST</acronym>ed input values: an input might not
342 actually consist of a four-byte length word and contents until after it's
343 been <firstterm>detoasted</firstterm>.  (This is normally done by invoking
344 <function>PG_DETOAST_DATUM</function> before doing anything with an input value,
345 but in some cases more efficient approaches are possible.
346 See <xref linkend="xtypes-toast"/> for more detail.)
347 </para>
348
349 <para>
350 <acronym>TOAST</acronym> usurps two bits of the varlena length word (the high-order
351 bits on big-endian machines, the low-order bits on little-endian machines),
352 thereby limiting the logical size of any value of a <acronym>TOAST</acronym>-able
353 data type to 1 GB (2<superscript>30</superscript> - 1 bytes).  When both bits are zero,
354 the value is an ordinary un-<acronym>TOAST</acronym>ed value of the data type, and
355 the remaining bits of the length word give the total datum size (including
356 length word) in bytes.  When the highest-order or lowest-order bit is set,
357 the value has only a single-byte header instead of the normal four-byte
358 header, and the remaining bits of that byte give the total datum size
359 (including length byte) in bytes.  This alternative supports space-efficient
360 storage of values shorter than 127 bytes, while still allowing the data type
361 to grow to 1 GB at need.  Values with single-byte headers aren't aligned on
362 any particular boundary, whereas values with four-byte headers are aligned on
363 at least a four-byte boundary; this omission of alignment padding provides
364 additional space savings that is significant compared to short values.
365 As a special case, if the remaining bits of a single-byte header are all
366 zero (which would be impossible for a self-inclusive length), the value is
367 a pointer to out-of-line data, with several possible alternatives as
368 described below.  The type and size of such a <firstterm>TOAST pointer</firstterm>
369 are determined by a code stored in the second byte of the datum.
370 Lastly, when the highest-order or lowest-order bit is clear but the adjacent
371 bit is set, the content of the datum has been compressed and must be
372 decompressed before use.  In this case the remaining bits of the four-byte
373 length word give the total size of the compressed datum, not the
374 original data.  Note that compression is also possible for out-of-line data
375 but the varlena header does not tell whether it has occurred &mdash;
376 the content of the <acronym>TOAST</acronym> pointer tells that, instead.
377 </para>
378
379 <para>
380 As mentioned, there are multiple types of <acronym>TOAST</acronym> pointer datums.
381 The oldest and most common type is a pointer to out-of-line data stored in
382 a <firstterm><acronym>TOAST</acronym> table</firstterm> that is separate from, but
383 associated with, the table containing the <acronym>TOAST</acronym> pointer datum
384 itself.  These <firstterm>on-disk</firstterm> pointer datums are created by the
385 <acronym>TOAST</acronym> management code (in <filename>access/common/toast_internals.c</filename>)
386 when a tuple to be stored on disk is too large to be stored as-is.
387 Further details appear in <xref linkend="storage-toast-ondisk"/>.
388 Alternatively, a <acronym>TOAST</acronym> pointer datum can contain a pointer to
389 out-of-line data that appears elsewhere in memory.  Such datums are
390 necessarily short-lived, and will never appear on-disk, but they are very
391 useful for avoiding copying and redundant processing of large data values.
392 Further details appear in <xref linkend="storage-toast-inmemory"/>.
393 </para>
394
395 <para>
396 The compression technique used for either in-line or out-of-line compressed
397 data is a fairly simple and very fast member
398 of the LZ family of compression techniques.  See
399 <filename>src/common/pg_lzcompress.c</filename> for the details.
400 </para>
401
402 <sect2 id="storage-toast-ondisk">
403  <title>Out-of-Line, On-Disk TOAST Storage</title>
404
405 <para>
406 If any of the columns of a table are <acronym>TOAST</acronym>-able, the table will
407 have an associated <acronym>TOAST</acronym> table, whose OID is stored in the table's
408 <structname>pg_class</structname>.<structfield>reltoastrelid</structfield> entry.  On-disk
409 <acronym>TOAST</acronym>ed values are kept in the <acronym>TOAST</acronym> table, as
410 described in more detail below.
411 </para>
412
413 <para>
414 Out-of-line values are divided (after compression if used) into chunks of at
415 most <symbol>TOAST_MAX_CHUNK_SIZE</symbol> bytes (by default this value is chosen
416 so that four chunk rows will fit on a page, making it about 2000 bytes).
417 Each chunk is stored as a separate row in the <acronym>TOAST</acronym> table
418 belonging to the owning table.  Every
419 <acronym>TOAST</acronym> table has the columns <structfield>chunk_id</structfield> (an OID
420 identifying the particular <acronym>TOAST</acronym>ed value),
421 <structfield>chunk_seq</structfield> (a sequence number for the chunk within its value),
422 and <structfield>chunk_data</structfield> (the actual data of the chunk).  A unique index
423 on <structfield>chunk_id</structfield> and <structfield>chunk_seq</structfield> provides fast
424 retrieval of the values.  A pointer datum representing an out-of-line on-disk
425 <acronym>TOAST</acronym>ed value therefore needs to store the OID of the
426 <acronym>TOAST</acronym> table in which to look and the OID of the specific value
427 (its <structfield>chunk_id</structfield>).  For convenience, pointer datums also store the
428 logical datum size (original uncompressed data length) and physical stored size
429 (different if compression was applied).  Allowing for the varlena header bytes,
430 the total size of an on-disk <acronym>TOAST</acronym> pointer datum is therefore 18
431 bytes regardless of the actual size of the represented value.
432 </para>
433
434 <para>
435 The <acronym>TOAST</acronym> management code is triggered only
436 when a row value to be stored in a table is wider than
437 <symbol>TOAST_TUPLE_THRESHOLD</symbol> bytes (normally 2 kB).
438 The <acronym>TOAST</acronym> code will compress and/or move
439 field values out-of-line until the row value is shorter than
440 <symbol>TOAST_TUPLE_TARGET</symbol> bytes (also normally 2 kB, adjustable)
441 or no more gains can be had.  During an UPDATE
442 operation, values of unchanged fields are normally preserved as-is; so an
443 UPDATE of a row with out-of-line values incurs no <acronym>TOAST</acronym> costs if
444 none of the out-of-line values change.
445 </para>
446
447 <para>
448 The <acronym>TOAST</acronym> management code recognizes four different strategies
449 for storing <acronym>TOAST</acronym>-able columns on disk:
450
451    <itemizedlist>
452     <listitem>
453      <para>
454       <literal>PLAIN</literal> prevents either compression or
455       out-of-line storage; furthermore it disables use of single-byte headers
456       for varlena types.
457       This is the only possible strategy for
458       columns of non-<acronym>TOAST</acronym>-able data types.
459      </para>
460     </listitem>
461     <listitem>
462      <para>
463       <literal>EXTENDED</literal> allows both compression and out-of-line
464       storage.  This is the default for most <acronym>TOAST</acronym>-able data types.
465       Compression will be attempted first, then out-of-line storage if
466       the row is still too big.
467      </para>
468     </listitem>
469     <listitem>
470      <para>
471       <literal>EXTERNAL</literal> allows out-of-line storage but not
472       compression.  Use of <literal>EXTERNAL</literal> will
473       make substring operations on wide <type>text</type> and
474       <type>bytea</type> columns faster (at the penalty of increased storage
475       space) because these operations are optimized to fetch only the
476       required parts of the out-of-line value when it is not compressed.
477      </para>
478     </listitem>
479     <listitem>
480      <para>
481       <literal>MAIN</literal> allows compression but not out-of-line
482       storage.  (Actually, out-of-line storage will still be performed
483       for such columns, but only as a last resort when there is no other
484       way to make the row small enough to fit on a page.)
485      </para>
486     </listitem>
487    </itemizedlist>
488
489 Each <acronym>TOAST</acronym>-able data type specifies a default strategy for columns
490 of that data type, but the strategy for a given table column can be altered
491 with <link linkend="sql-altertable"><command>ALTER TABLE ... SET STORAGE</command></link>.
492 </para>
493
494 <para>
495 <symbol>TOAST_TUPLE_TARGET</symbol> can be adjusted for each table using
496 <link linkend="sql-altertable"><command>ALTER TABLE ... SET (toast_tuple_target = N)</command></link>
497 </para>
498
499 <para>
500 This scheme has a number of advantages compared to a more straightforward
501 approach such as allowing row values to span pages.  Assuming that queries are
502 usually qualified by comparisons against relatively small key values, most of
503 the work of the executor will be done using the main row entry. The big values
504 of <acronym>TOAST</acronym>ed attributes will only be pulled out (if selected at all)
505 at the time the result set is sent to the client. Thus, the main table is much
506 smaller and more of its rows fit in the shared buffer cache than would be the
507 case without any out-of-line storage. Sort sets shrink also, and sorts will
508 more often be done entirely in memory. A little test showed that a table
509 containing typical HTML pages and their URLs was stored in about half of the
510 raw data size including the <acronym>TOAST</acronym> table, and that the main table
511 contained only about 10% of the entire data (the URLs and some small HTML
512 pages). There was no run time difference compared to an un-<acronym>TOAST</acronym>ed
513 comparison table, in which all the HTML pages were cut down to 7 kB to fit.
514 </para>
515
516 </sect2>
517
518 <sect2 id="storage-toast-inmemory">
519  <title>Out-of-Line, In-Memory TOAST Storage</title>
520
521 <para>
522 <acronym>TOAST</acronym> pointers can point to data that is not on disk, but is
523 elsewhere in the memory of the current server process.  Such pointers
524 obviously cannot be long-lived, but they are nonetheless useful.  There
525 are currently two sub-cases:
526 pointers to <firstterm>indirect</firstterm> data and
527 pointers to <firstterm>expanded</firstterm> data.
528 </para>
529
530 <para>
531 Indirect <acronym>TOAST</acronym> pointers simply point at a non-indirect varlena
532 value stored somewhere in memory.  This case was originally created merely
533 as a proof of concept, but it is currently used during logical decoding to
534 avoid possibly having to create physical tuples exceeding 1 GB (as pulling
535 all out-of-line field values into the tuple might do).  The case is of
536 limited use since the creator of the pointer datum is entirely responsible
537 that the referenced data survives for as long as the pointer could exist,
538 and there is no infrastructure to help with this.
539 </para>
540
541 <para>
542 Expanded <acronym>TOAST</acronym> pointers are useful for complex data types
543 whose on-disk representation is not especially suited for computational
544 purposes.  As an example, the standard varlena representation of a
545 <productname>PostgreSQL</productname> array includes dimensionality information, a
546 nulls bitmap if there are any null elements, then the values of all the
547 elements in order.  When the element type itself is variable-length, the
548 only way to find the <replaceable>N</replaceable>'th element is to scan through all the
549 preceding elements.  This representation is appropriate for on-disk storage
550 because of its compactness, but for computations with the array it's much
551 nicer to have an <quote>expanded</quote> or <quote>deconstructed</quote>
552 representation in which all the element starting locations have been
553 identified.  The <acronym>TOAST</acronym> pointer mechanism supports this need by
554 allowing a pass-by-reference Datum to point to either a standard varlena
555 value (the on-disk representation) or a <acronym>TOAST</acronym> pointer that
556 points to an expanded representation somewhere in memory.  The details of
557 this expanded representation are up to the data type, though it must have
558 a standard header and meet the other API requirements given
559 in <filename>src/include/utils/expandeddatum.h</filename>.  C-level functions
560 working with the data type can choose to handle either representation.
561 Functions that do not know about the expanded representation, but simply
562 apply <function>PG_DETOAST_DATUM</function> to their inputs, will automatically
563 receive the traditional varlena representation; so support for an expanded
564 representation can be introduced incrementally, one function at a time.
565 </para>
566
567 <para>
568 <acronym>TOAST</acronym> pointers to expanded values are further broken down
569 into <firstterm>read-write</firstterm> and <firstterm>read-only</firstterm> pointers.
570 The pointed-to representation is the same either way, but a function that
571 receives a read-write pointer is allowed to modify the referenced value
572 in-place, whereas one that receives a read-only pointer must not; it must
573 first create a copy if it wants to make a modified version of the value.
574 This distinction and some associated conventions make it possible to avoid
575 unnecessary copying of expanded values during query execution.
576 </para>
577
578 <para>
579 For all types of in-memory <acronym>TOAST</acronym> pointer, the <acronym>TOAST</acronym>
580 management code ensures that no such pointer datum can accidentally get
581 stored on disk.  In-memory <acronym>TOAST</acronym> pointers are automatically
582 expanded to normal in-line varlena values before storage &mdash; and then
583 possibly converted to on-disk <acronym>TOAST</acronym> pointers, if the containing
584 tuple would otherwise be too big.
585 </para>
586
587 </sect2>
588
589 </sect1>
590
591 <sect1 id="storage-fsm">
592
593 <title>Free Space Map</title>
594
595 <indexterm>
596  <primary>Free Space Map</primary>
597 </indexterm>
598 <indexterm><primary>FSM</primary><see>Free Space Map</see></indexterm>
599
600 <para>
601 Each heap and index relation, except for hash indexes, has a Free Space Map
602 (FSM) to keep track of available space in the relation. It's stored
603 alongside the main relation data in a separate relation fork, named after the
604 filenode number of the relation, plus a <literal>_fsm</literal> suffix. For example,
605 if the filenode of a relation is 12345, the FSM is stored in a file called
606 <filename>12345_fsm</filename>, in the same directory as the main relation file.
607 </para>
608
609 <para>
610 The Free Space Map is organized as a tree of <acronym>FSM</acronym> pages. The
611 bottom level <acronym>FSM</acronym> pages store the free space available on each
612 heap (or index) page, using one byte to represent each such page. The upper
613 levels aggregate information from the lower levels.
614 </para>
615
616 <para>
617 Within each <acronym>FSM</acronym> page is a binary tree, stored in an array with
618 one byte per node. Each leaf node represents a heap page, or a lower level
619 <acronym>FSM</acronym> page. In each non-leaf node, the higher of its children's
620 values is stored. The maximum value in the leaf nodes is therefore stored
621 at the root.
622 </para>
623
624 <para>
625 See <filename>src/backend/storage/freespace/README</filename> for more details on
626 how the <acronym>FSM</acronym> is structured, and how it's updated and searched.
627 The <xref linkend="pgfreespacemap"/> module
628 can be used to examine the information stored in free space maps.
629 </para>
630
631 </sect1>
632
633 <sect1 id="storage-vm">
634
635 <title>Visibility Map</title>
636
637 <indexterm>
638  <primary>Visibility Map</primary>
639 </indexterm>
640 <indexterm><primary>VM</primary><see>Visibility Map</see></indexterm>
641
642 <para>
643 Each heap relation has a Visibility Map
644 (VM) to keep track of which pages contain only tuples that are known to be
645 visible to all active transactions; it also keeps track of which pages contain
646 only frozen tuples.  It's stored
647 alongside the main relation data in a separate relation fork, named after the
648 filenode number of the relation, plus a <literal>_vm</literal> suffix. For example,
649 if the filenode of a relation is 12345, the VM is stored in a file called
650 <filename>12345_vm</filename>, in the same directory as the main relation file.
651 Note that indexes do not have VMs.
652 </para>
653
654 <para>
655 The visibility map stores two bits per heap page.  The first bit, if set,
656 indicates that the page is all-visible, or in other words that the page does
657 not contain any tuples that need to be vacuumed.
658 This information can also be used
659 by <link linkend="indexes-index-only-scans"><firstterm>index-only
660 scans</firstterm></link> to answer queries using only the index tuple.
661 The second bit, if set, means that all tuples on the page have been frozen.
662 That means that even an anti-wraparound vacuum need not revisit the page.
663 </para>
664
665 <para>
666 The map is conservative in the sense that we make sure that whenever a bit is
667 set, we know the condition is true, but if a bit is not set, it might or
668 might not be true. Visibility map bits are only set by vacuum, but are
669 cleared by any data-modifying operations on a page.
670 </para>
671
672 <para>
673 The <xref linkend="pgvisibility"/> module can be used to examine the
674 information stored in the visibility map.
675 </para>
676
677 </sect1>
678
679 <sect1 id="storage-init">
680
681 <title>The Initialization Fork</title>
682
683 <indexterm>
684  <primary>Initialization Fork</primary>
685 </indexterm>
686
687 <para>
688 Each unlogged table, and each index on an unlogged table, has an initialization
689 fork.  The initialization fork is an empty table or index of the appropriate
690 type.  When an unlogged table must be reset to empty due to a crash, the
691 initialization fork is copied over the main fork, and any other forks are
692 erased (they will be recreated automatically as needed).
693 </para>
694
695 </sect1>
696
697 <sect1 id="storage-page-layout">
698
699 <title>Database Page Layout</title>
700
701 <para>
702 This section provides an overview of the page format used within
703 <productname>PostgreSQL</productname> tables and indexes.<footnote>
704   <para>
705     Actually, use of this page format is not required for either table or
706     index access methods. The <literal>heap</literal> table access method
707     always uses this format.  All the existing index methods also use the
708     basic format, but the data kept on index metapages usually doesn't follow
709     the item layout rules.
710   </para>
711 </footnote>
712 Sequences and <acronym>TOAST</acronym> tables are formatted just like a regular table.
713 </para>
714
715 <para>
716 In the following explanation, a
717 <firstterm>byte</firstterm>
718 is assumed to contain 8 bits.  In addition, the term
719 <firstterm>item</firstterm>
720 refers to an individual data value that is stored on a page.  In a table,
721 an item is a row; in an index, an item is an index entry.
722 </para>
723
724 <para>
725 Every table and index is stored as an array of <firstterm>pages</firstterm> of a
726 fixed size (usually 8 kB, although a different page size can be selected
727 when compiling the server).  In a table, all the pages are logically
728 equivalent, so a particular item (row) can be stored in any page.  In
729 indexes, the first page is generally reserved as a <firstterm>metapage</firstterm>
730 holding control information, and there can be different types of pages
731 within the index, depending on the index access method.
732 </para>
733
734 <para>
735 <xref linkend="page-table"/> shows the overall layout of a page.
736 There are five parts to each page.
737 </para>
738
739 <table tocentry="1" id="page-table">
740 <title>Overall Page Layout</title>
741 <titleabbrev>Page Layout</titleabbrev>
742 <tgroup cols="2">
743 <thead>
744 <row>
745 <entry>
746 Item
747 </entry>
748 <entry>Description</entry>
749 </row>
750 </thead>
751
752 <tbody>
753
754 <row>
755  <entry>PageHeaderData</entry>
756  <entry>24 bytes long. Contains general information about the page, including
757 free space pointers.</entry>
758 </row>
759
760 <row>
761 <entry>ItemIdData</entry>
762 <entry>Array of item identifiers pointing to the actual items. Each
763 entry is an (offset,length) pair. 4 bytes per item.</entry>
764 </row>
765
766 <row>
767 <entry>Free space</entry>
768 <entry>The unallocated space. New item identifiers are allocated from
769 the start of this area, new items from the end.</entry>
770 </row>
771
772 <row>
773 <entry>Items</entry>
774 <entry>The actual items themselves.</entry>
775 </row>
776
777 <row>
778 <entry>Special space</entry>
779 <entry>Index access method specific data. Different methods store different
780 data. Empty in ordinary tables.</entry>
781 </row>
782
783 </tbody>
784 </tgroup>
785 </table>
786
787  <para>
788
789   The first 24 bytes of each page consists of a page header
790   (<structname>PageHeaderData</structname>). Its format is detailed in <xref
791   linkend="pageheaderdata-table"/>. The first field tracks the most
792   recent WAL entry related to this page. The second field contains
793   the page checksum if <xref linkend="app-initdb-data-checksums"/> are
794   enabled.  Next is a 2-byte field containing flag bits. This is followed
795   by three 2-byte integer fields (<structfield>pd_lower</structfield>,
796   <structfield>pd_upper</structfield>, and
797   <structfield>pd_special</structfield>).  These contain byte offsets
798   from the page start to the start of unallocated space, to the end of
799   unallocated space, and to the start of the special space.  The next 2
800   bytes of the page header, <structfield>pd_pagesize_version</structfield>,
801   store both the page size and a version indicator.  Beginning with
802   <productname>PostgreSQL</productname> 8.3 the version number is 4;
803   <productname>PostgreSQL</productname> 8.1 and 8.2 used version number 3;
804   <productname>PostgreSQL</productname> 8.0 used version number 2;
805   <productname>PostgreSQL</productname> 7.3 and 7.4 used version number 1;
806   prior releases used version number 0.
807   (The basic page layout and header format has not changed in most of these
808   versions, but the layout of heap row headers has.)  The page size
809   is basically only present as a cross-check; there is no support for having
810   more than one page size in an installation.
811   The last field is a hint that shows whether pruning the page is likely
812   to be profitable: it tracks the oldest un-pruned XMAX on the page.
813
814  </para>
815
816  <table tocentry="1" id="pageheaderdata-table">
817  <title>PageHeaderData Layout</title>
818  <titleabbrev>PageHeaderData Layout</titleabbrev>
819  <tgroup cols="4">
820  <thead>
821   <row>
822    <entry>Field</entry>
823    <entry>Type</entry>
824    <entry>Length</entry>
825    <entry>Description</entry>
826   </row>
827  </thead>
828  <tbody>
829   <row>
830    <entry>pd_lsn</entry>
831    <entry>PageXLogRecPtr</entry>
832    <entry>8 bytes</entry>
833    <entry>LSN: next byte after last byte of WAL record for last change
834    to this page</entry>
835   </row>
836   <row>
837    <entry>pd_checksum</entry>
838    <entry>uint16</entry>
839    <entry>2 bytes</entry>
840    <entry>Page checksum</entry>
841   </row>
842   <row>
843    <entry>pd_flags</entry>
844    <entry>uint16</entry>
845    <entry>2 bytes</entry>
846    <entry>Flag bits</entry>
847   </row>
848   <row>
849    <entry>pd_lower</entry>
850    <entry>LocationIndex</entry>
851    <entry>2 bytes</entry>
852    <entry>Offset to start of free space</entry>
853   </row>
854   <row>
855    <entry>pd_upper</entry>
856    <entry>LocationIndex</entry>
857    <entry>2 bytes</entry>
858    <entry>Offset to end of free space</entry>
859   </row>
860   <row>
861    <entry>pd_special</entry>
862    <entry>LocationIndex</entry>
863    <entry>2 bytes</entry>
864    <entry>Offset to start of special space</entry>
865   </row>
866   <row>
867    <entry>pd_pagesize_version</entry>
868    <entry>uint16</entry>
869    <entry>2 bytes</entry>
870    <entry>Page size and layout version number information</entry>
871   </row>
872   <row>
873    <entry>pd_prune_xid</entry>
874    <entry>TransactionId</entry>
875    <entry>4 bytes</entry>
876    <entry>Oldest unpruned XMAX on page, or zero if none</entry>
877   </row>
878  </tbody>
879  </tgroup>
880  </table>
881
882  <para>
883   All the details can be found in
884   <filename>src/include/storage/bufpage.h</filename>.
885  </para>
886
887  <para>
888   Following the page header are item identifiers
889   (<type>ItemIdData</type>), each requiring four bytes.
890   An item identifier contains a byte-offset to
891   the start of an item, its length in bytes, and a few attribute bits
892   which affect its interpretation.
893   New item identifiers are allocated
894   as needed from the beginning of the unallocated space.
895   The number of item identifiers present can be determined by looking at
896   <structfield>pd_lower</structfield>, which is increased to allocate a new identifier.
897   Because an item
898   identifier is never moved until it is freed, its index can be used on a
899   long-term basis to reference an item, even when the item itself is moved
900   around on the page to compact free space.  In fact, every pointer to an
901   item (<type>ItemPointer</type>, also known as
902   <type>CTID</type>) created by
903   <productname>PostgreSQL</productname> consists of a page number and the
904   index of an item identifier.
905
906  </para>
907
908  <para>
909
910   The items themselves are stored in space allocated backwards from the end
911   of unallocated space.  The exact structure varies depending on what the
912   table is to contain. Tables and sequences both use a structure named
913   <type>HeapTupleHeaderData</type>, described below.
914
915  </para>
916
917  <para>
918
919   The final section is the <quote>special section</quote> which can
920   contain anything the access method wishes to store.  For example,
921   b-tree indexes store links to the page's left and right siblings,
922   as well as some other data relevant to the index structure.
923   Ordinary tables do not use a special section at all (indicated by setting
924   <structfield>pd_special</structfield> to equal the page size).
925
926  </para>
927
928  <para>
929   <xref linkend="storage-page-layout-figure"/> illustrates how these parts are
930   laid out in a page.
931  </para>
932
933  <figure id="storage-page-layout-figure">
934   <title>Page Layout</title>
935   <mediaobject>
936    <imageobject>
937     <imagedata fileref="images/pagelayout.svg" format="SVG" width="100%"/>
938    </imageobject>
939   </mediaobject>
940  </figure>
941
942  <sect2 id="storage-tuple-layout">
943
944  <title>Table Row Layout</title>
945
946  <para>
947
948   All table rows are structured in the same way. There is a fixed-size
949   header (occupying 23 bytes on most machines), followed by an optional null
950   bitmap, an optional object ID field, and the user data. The header is
951   detailed
952   in <xref linkend="heaptupleheaderdata-table"/>.  The actual user data
953   (columns of the row) begins at the offset indicated by
954   <structfield>t_hoff</structfield>, which must always be a multiple of the MAXALIGN
955   distance for the platform.
956   The null bitmap is
957   only present if the <firstterm>HEAP_HASNULL</firstterm> bit is set in
958   <structfield>t_infomask</structfield>. If it is present it begins just after
959   the fixed header and occupies enough bytes to have one bit per data column
960   (that is, the number of bits that equals the attribute count in
961   <structfield>t_infomask2</structfield>). In this list of bits, a
962   1 bit indicates not-null, a 0 bit is a null.  When the bitmap is not
963   present, all columns are assumed not-null.
964   The object ID is only present if the <firstterm>HEAP_HASOID_OLD</firstterm> bit
965   is set in <structfield>t_infomask</structfield>.  If present, it appears just
966   before the <structfield>t_hoff</structfield> boundary.  Any padding needed to make
967   <structfield>t_hoff</structfield> a MAXALIGN multiple will appear between the null
968   bitmap and the object ID.  (This in turn ensures that the object ID is
969   suitably aligned.)
970
971  </para>
972
973  <table tocentry="1" id="heaptupleheaderdata-table">
974  <title>HeapTupleHeaderData Layout</title>
975  <titleabbrev>HeapTupleHeaderData Layout</titleabbrev>
976  <tgroup cols="4">
977  <thead>
978   <row>
979    <entry>Field</entry>
980    <entry>Type</entry>
981    <entry>Length</entry>
982    <entry>Description</entry>
983   </row>
984  </thead>
985  <tbody>
986   <row>
987    <entry>t_xmin</entry>
988    <entry>TransactionId</entry>
989    <entry>4 bytes</entry>
990    <entry>insert XID stamp</entry>
991   </row>
992   <row>
993    <entry>t_xmax</entry>
994    <entry>TransactionId</entry>
995    <entry>4 bytes</entry>
996    <entry>delete XID stamp</entry>
997   </row>
998   <row>
999    <entry>t_cid</entry>
1000    <entry>CommandId</entry>
1001    <entry>4 bytes</entry>
1002    <entry>insert and/or delete CID stamp (overlays with t_xvac)</entry>
1003   </row>
1004   <row>
1005    <entry>t_xvac</entry>
1006    <entry>TransactionId</entry>
1007    <entry>4 bytes</entry>
1008    <entry>XID for VACUUM operation moving a row version</entry>
1009   </row>
1010   <row>
1011    <entry>t_ctid</entry>
1012    <entry>ItemPointerData</entry>
1013    <entry>6 bytes</entry>
1014    <entry>current TID of this or newer row version</entry>
1015   </row>
1016   <row>
1017    <entry>t_infomask2</entry>
1018    <entry>uint16</entry>
1019    <entry>2 bytes</entry>
1020    <entry>number of attributes, plus various flag bits</entry>
1021   </row>
1022   <row>
1023    <entry>t_infomask</entry>
1024    <entry>uint16</entry>
1025    <entry>2 bytes</entry>
1026    <entry>various flag bits</entry>
1027   </row>
1028   <row>
1029    <entry>t_hoff</entry>
1030    <entry>uint8</entry>
1031    <entry>1 byte</entry>
1032    <entry>offset to user data</entry>
1033   </row>
1034  </tbody>
1035  </tgroup>
1036  </table>
1037
1038  <para>
1039    All the details can be found in
1040    <filename>src/include/access/htup_details.h</filename>.
1041  </para>
1042
1043  <para>
1044
1045   Interpreting the actual data can only be done with information obtained
1046   from other tables, mostly <structname>pg_attribute</structname>. The
1047   key values needed to identify field locations are
1048   <structfield>attlen</structfield> and <structfield>attalign</structfield>.
1049   There is no way to directly get a
1050   particular attribute, except when there are only fixed width fields and no
1051   null values. All this trickery is wrapped up in the functions
1052   <firstterm>heap_getattr</firstterm>, <firstterm>fastgetattr</firstterm>
1053   and <firstterm>heap_getsysattr</firstterm>.
1054
1055  </para>
1056  <para>
1057
1058   To read the data you need to examine each attribute in turn. First check
1059   whether the field is NULL according to the null bitmap. If it is, go to
1060   the next. Then make sure you have the right alignment.  If the field is a
1061   fixed width field, then all the bytes are simply placed. If it's a
1062   variable length field (attlen = -1) then it's a bit more complicated.
1063   All variable-length data types share the common header structure
1064   <type>struct varlena</type>, which includes the total length of the stored
1065   value and some flag bits.  Depending on the flags, the data can be either
1066   inline or in a <acronym>TOAST</acronym> table;
1067   it might be compressed, too (see <xref linkend="storage-toast"/>).
1068
1069  </para>
1070  </sect2>
1071 </sect1>
1072
1073 </chapter>