lobj.sgml 18.5 KB
Newer Older
1
<!--
2
$Header: /cvsroot/pgsql/doc/src/sgml/lobj.sgml,v 1.27 2002/04/18 14:28:14 momjian Exp $
3 4
-->

T
Thomas G. Lockhart 已提交
5 6 7
 <chapter id="largeObjects">
  <title id="largeObjects-title">Large Objects</title>

P
Peter Eisentraut 已提交
8 9 10
  <indexterm zone="largeobjects"><primary>large object</></>
  <indexterm><primary>BLOB</><see>large object</></>

11 12
  <sect1 id="lo-intro">
   <title>Introduction</title>
13 14

   <para>
15 16 17 18 19 20 21 22 23
    In <productname>PostgreSQL</productname> releases prior to 7.1,
    the size of any row in the database could not exceed the size of a
    data page.  Since the size of a data page is 8192 bytes (the
    default, which can be raised up to 32768), the upper limit on the
    size of a data value was relatively low. To support the storage of
    larger atomic values, <productname>PostgreSQL</productname>
    provided and continues to provide a large object interface.  This
    interface provides file-oriented access to user data that has been
    declared to be a large object.
24
   </para>
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

   <para>
    <productname>POSTGRES 4.2</productname>, the indirect predecessor
    of <productname>PostgreSQL</productname>, supported three standard
    implementations of large objects: as files external to the
    <productname>POSTGRES</productname> server, as external files
    managed by the <productname>POSTGRES</productname> server, and as
    data stored within the <productname>POSTGRES</productname>
    database. This caused considerable confusion among users. As a
    result, only support for large objects as data stored within the
    database is retained in <productname>PostgreSQL</productname>.
    Even though this is slower to access, it provides stricter data
    integrity.  For historical reasons, this storage scheme is
    referred to as <firstterm>Inversion large
    objects</firstterm>. (You will see the term Inversion used
    occasionally to mean the same thing as large object.)  Since
    <productname>PostgreSQL 7.1</productname>, all large objects are
    placed in one system table called
    <classname>pg_largeobject</classname>.
   </para>

   <para>
P
Peter Eisentraut 已提交
47 48
    <indexterm><primary>TOAST</></>
    <indexterm><primary>sliced bread</><see>TOAST</></indexterm>
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
    <productname>PostgreSQL 7.1</productname> introduced a mechanism
    (nicknamed <quote><acronym>TOAST</acronym></quote>) that allows
    data rows to be much larger than individual data pages.  This
    makes the large object interface partially obsolete.  One
    remaining advantage of the large object interface is that it
    allows random access to the data, i.e., the ability to read or
    write small chunks of a large value.  It is planned to equip
    <acronym>TOAST</acronym> with such functionality in the future.
   </para>

   <para>
    This section describes the implementation and the programming and
    query language interfaces to <productname>PostgreSQL</productname>
    large object data.  We use the <application>libpq</application> C
    library for the examples in this section, but most programming
    interfaces native to <productname>PostgreSQL</productname> support
    equivalent functionality.  Other interfaces may use the large
    object interface internally to provide generic support for large
    values.  This is not described here.
   </para>

70 71
  </sect1>

72
  <sect1 id="lo-implementation">
73 74 75
   <title>Implementation Features</title>

   <para>
76
    The large object implementation breaks  large
77
    objects  up  into  <quote>chunks</quote>  and  stores  the chunks in
78 79 80 81 82 83
    tuples in the database.  A B-tree index guarantees fast
    searches for the correct chunk number when doing random
    access reads and writes.
   </para>
  </sect1>

84
  <sect1 id="lo-interfaces">
85 86 87
   <title>Interfaces</title>

   <para>
88
    The  facilities  <productname>PostgreSQL</productname> provides  to
89 90 91
    access large objects,  both  in  the backend as part of user-defined
    functions or the front end as part  of  an  application
    using  the   interface, are described below. For users
92
    familiar with <productname>POSTGRES 4.2</productname>,
T
Thomas G. Lockhart 已提交
93
    <productname>PostgreSQL</productname> has a new set of
94 95 96 97 98 99
    functions  providing  a  more  coherent  interface.

    <note>
     <para>
      All large object manipulation <emphasis>must</emphasis> take
      place within an SQL transaction. This requirement is strictly
100
      enforced as of <productname>PostgreSQL 6.5</>, though it has been an
101 102 103 104 105 106 107
      implicit requirement in previous versions, resulting in
      misbehavior if ignored.
     </para>
    </note>
   </para>

   <para>
108
    The  <productname>PostgreSQL</productname>  large  object interface is modeled after
P
Peter Eisentraut 已提交
109
    the <acronym>Unix</acronym>  file-system  interface,  with  analogues  of
110 111 112 113 114
    <function>open(2)</function>,  <function>read(2)</function>,
    <function>write(2)</function>,
    <function>lseek(2)</function>, etc.  User 
    functions call these routines to retrieve only the data  of
    interest  from a large object.  For example, if a large
115
    object type called <type>mugshot</type>  existed  that  stored  
P
Peter Eisentraut 已提交
116 117
    photographs  of  faces, then a function called <function>beard</function> could
    be declared on <type>mugshot</type> data.  <function>beard</> could look  at  the
118 119
    lower third of a photograph, and determine the color of
    the beard that appeared  there,  if  any.   The  entire
P
Peter Eisentraut 已提交
120 121
    large-object value need not be buffered, or even 
    examined, by the <function>beard</function> function.
122 123
    Large objects may be accessed from dynamically-loaded <acronym>C</acronym>
    functions  or  database  client  programs that link the
124
    library.  <productname>PostgreSQL</productname> provides a set of routines that 
125 126 127 128 129 130 131 132
    support opening, reading, writing, closing, and seeking on
    large objects.
   </para>

   <sect2>
    <title>Creating a Large Object</title>

    <para>
133
     The routine
134
<synopsis>
135
Oid lo_creat(PGconn *<replaceable class="parameter">conn</replaceable>, int <replaceable class="parameter">mode</replaceable>)
136
</synopsis>
137
     creates a new large  object.  
138
     <replaceable class="parameter">mode</replaceable>  is  a  bit mask
139 140
     describing  several  different  attributes  of  the new
     object.  The symbolic constants listed here are defined
141
     in the header file <filename>libpq/libpq-fs.h</filename>.
142
     The access type (read, write, or both) is controlled by
P
Peter Eisentraut 已提交
143
     or'ing together the bits <symbol>INV_READ</symbol>  and
144 145 146 147 148 149
     <symbol>INV_WRITE</symbol>.  The low-order sixteen bits of the mask have
     historically been used at Berkeley to designate the storage  manager  number on which the large object
     should reside.  These
     bits should always be zero now.
     The commands below create a large object:
<programlisting>
B
Bruce Momjian 已提交
150
inv_oid = lo_creat(INV_READ|INV_WRITE);
151
</programlisting>
152 153 154 155 156 157 158
    </para>
   </sect2>

   <sect2>
    <title>Importing a Large Object</title>

    <para>
P
Peter Eisentraut 已提交
159
     To import an operating system file as a large object, call
160 161 162
<synopsis>
Oid lo_import(PGconn *<replaceable class="parameter">conn</replaceable>, const char *<replaceable class="parameter">filename</replaceable>)
</synopsis>
163
    <replaceable class="parameter">filename</replaceable> 
P
Peter Eisentraut 已提交
164
     specifies the operating system name of
165
     the file to be imported as a large object.
166 167 168 169 170 171 172 173
    </para>
   </sect2>

   <sect2>
    <title>Exporting a Large Object</title>

    <para>
     To export a large object
P
Peter Eisentraut 已提交
174
     into an operating system file, call
175 176 177
<synopsis>
int lo_export(PGconn *<replaceable class="parameter">conn</replaceable>, Oid <replaceable class="parameter">lobjId</replaceable>, const char *<replaceable class="parameter">filename</replaceable>)
</synopsis>
P
Peter Eisentraut 已提交
178
     The <parameter>lobjId</parameter> argument specifies  the  OID  of  the  large
179
     object  to  export  and the <parameter>filename</parameter> argument specifies
P
Peter Eisentraut 已提交
180
     the operating system name name of the file.
181 182
    </para>
   </sect2>
183

184 185
   <sect2>
    <title>Opening an Existing Large Object</title>
186

187
    <para>
188
     To open an existing large object, call
189 190 191
<synopsis>
int lo_open(PGconn *conn, Oid lobjId, int mode)
</synopsis>
P
Peter Eisentraut 已提交
192
     The <parameter>lobjId</parameter> argument specifies  the  OID  of  the  large
193
     object  to  open.   The  <parameter>mode</parameter>  bits control whether the
P
Peter Eisentraut 已提交
194
     object is opened  for  reading  (<symbol>INV_READ</>),  writing (<symbol>INV_WRITE</symbol>),  or
195 196
     both.
     A  large  object cannot be opened before it is created.
197 198 199 200
     <function>lo_open</function> returns a large object descriptor
     for later use in <function>lo_read</function>, <function>lo_write</function>,
     <function>lo_lseek</function>, <function>lo_tell</function>, and
     <function>lo_close</function>.
T
Thomas G. Lockhart 已提交
201 202
</para>
</sect2>
203

T
Thomas G. Lockhart 已提交
204 205
<sect2>
<title>Writing Data to a Large Object</title>
206

T
Thomas G. Lockhart 已提交
207
<para>
208
     The routine
T
Thomas G. Lockhart 已提交
209
<programlisting>
210
int lo_write(PGconn *conn, int fd, const char *buf, size_t len)
T
Thomas G. Lockhart 已提交
211
</programlisting>
212
     writes <parameter>len</parameter> bytes from <parameter>buf</parameter> to large object <parameter>fd</>.   The <parameter>fd</parameter>
213
     argument must have been returned by a previous <function>lo_open</function>.
214 215
     The number of bytes actually written is  returned.   In
     the event of an error, the return value is negative.
T
Thomas G. Lockhart 已提交
216 217
</para>
</sect2>
218

219 220 221 222 223 224 225 226
<sect2>
<title>Reading Data from a Large Object</title>

<para>
     The routine
<programlisting>
int lo_read(PGconn *conn, int fd, char *buf, size_t len)
</programlisting>
227
     reads <parameter>len</parameter> bytes from large object <parameter>fd</parameter> into <parameter>buf</parameter>. The  <parameter>fd</parameter>
228 229 230 231 232 233
     argument must have been returned by a previous <function>lo_open</function>.
     The number of bytes actually read is returned. In
     the event of an error, the return value is negative.
</para>
</sect2>

T
Thomas G. Lockhart 已提交
234 235
<sect2>
<title>Seeking on a Large Object</title>
236

T
Thomas G. Lockhart 已提交
237
<para>
238 239
     To change the current read or write location on a large
     object, call
T
Thomas G. Lockhart 已提交
240
<programlisting>
241
int lo_lseek(PGconn *conn, int fd, int offset, int whence)
T
Thomas G. Lockhart 已提交
242
</programlisting>
243
     This routine moves the current location pointer for the
P
Peter Eisentraut 已提交
244 245 246
     large object described by <parameter>fd</> to the new location specified 
     by <parameter>offset</>.  The valid values for <parameter>whence</> are
     <symbol>SEEK_SET</>, <symbol>SEEK_CUR</>, and <symbol>SEEK_END</>.
T
Thomas G. Lockhart 已提交
247 248
</para>
</sect2>
249

T
Thomas G. Lockhart 已提交
250 251
<sect2>
<title>Closing a Large Object Descriptor</title>
252

T
Thomas G. Lockhart 已提交
253
<para>
254
     A large object may be closed by calling
T
Thomas G. Lockhart 已提交
255
<programlisting>
256
int lo_close(PGconn *conn, int fd)
T
Thomas G. Lockhart 已提交
257
</programlisting>
P
Peter Eisentraut 已提交
258
     where  <parameter>fd</>  is  a  large  object  descriptor returned by
259 260
     <function>lo_open</function>.  On success, <function>lo_close</function>
      returns zero.  On error, the return value is negative.
T
Thomas G. Lockhart 已提交
261
</para>
262
</sect2>
263 264 265 266 267 268 269

   <sect2>
    <title>Removing a Large Object</title>

    <para>
     To remove a large object from the database, call
<synopsis>
270
int lo_unlink(PGconn *<replaceable class="parameter">conn</replaceable>, Oid lobjId)
271
</synopsis>
P
Peter Eisentraut 已提交
272
     The <parameter>lobjId</parameter> argument specifies  the  OID  of  the  large
273
     object  to  remove.  In the event of an error, the return value is negative.
274 275 276 277
    </para>
   </sect2>


T
Thomas G. Lockhart 已提交
278
</sect1>
279

280
<sect1 id="lo-funcs">
P
Peter Eisentraut 已提交
281
<title>Server-side Built-in Functions</title>
282

T
Thomas G. Lockhart 已提交
283
<para>
P
Peter Eisentraut 已提交
284 285
     There  are two built-in registered functions, <function>lo_import</function>
     and <function>lo_export</function> which  are  convenient  for  use
T
Thomas G. Lockhart 已提交
286
    in  <acronym>SQL</acronym>
287 288
     queries.
     Here is an example of their use
T
Thomas G. Lockhart 已提交
289
<programlisting>
290 291 292 293 294 295 296 297
CREATE TABLE image (
    name            text,
    raster          oid
);

INSERT INTO image (name, raster)
    VALUES ('beautiful image', lo_import('/etc/motd'));

P
Peter Eisentraut 已提交
298
SELECT lo_export(image.raster, '/tmp/motd') FROM image
299
    WHERE name = 'beautiful image';
T
Thomas G. Lockhart 已提交
300 301 302
</programlisting>
</para>
</sect1>
303

304
<sect1 id="lo-libpq">
305
<title>Accessing Large Objects from <application>Libpq</application></title>
306

T
Thomas G. Lockhart 已提交
307
<para>
P
Peter Eisentraut 已提交
308
     <xref linkend="lo-example"> is a sample program which shows how the large object  
309
     interface
310
     in  <application>libpq</>  can  be used.  Parts of the program are 
P
Peter Eisentraut 已提交
311
     commented out but are left in the source for  the  reader's
312
     benefit.  This program can be found in
P
Peter Eisentraut 已提交
313
     <filename>src/test/examples/testlo.c</filename> in the source distribution.
314
     Frontend applications which use the large object interface  
315 316
     in  <application>libpq</application>  should   include   the   header   file
     <filename>libpq/libpq-fs.h</filename> and link with the <application>libpq</application> library.
T
Thomas G. Lockhart 已提交
317
</para>
318

P
Peter Eisentraut 已提交
319
  <example id="lo-example">
P
Peter Eisentraut 已提交
320
   <title>Large Objects with <application>Libpq</application> Example Program</title>
T
Thomas G. Lockhart 已提交
321
<programlisting>
322
/*--------------------------------------------------------------
323 324 325 326 327 328 329 330 331
 *
 * testlo.c--
 *    test using large objects with libpq
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *--------------------------------------------------------------
 */
#include &lt;stdio.h&gt;
332 333
#include &quot;libpq-fe.h&quot;
#include &quot;libpq/libpq-fs.h&quot;
334 335 336 337

#define BUFSIZE          1024

/*
P
Peter Eisentraut 已提交
338 339
 * importFile
 *    import file &quot;in_filename&quot; into database as large object &quot;lobjOid&quot;
340 341
 *
 */
342 343
Oid
importFile(PGconn *conn, char *filename)
344
{
345 346 347 348 349 350
    Oid         lobjId;
    int         lobj_fd;
    char        buf[BUFSIZE];
    int         nbytes,
                tmp;
    int         fd;
351 352 353 354 355

    /*
     * open the file to be read in
     */
    fd = open(filename, O_RDONLY, 0666);
356 357 358
    if (fd &lt; 0)
    {                           /* error */
        fprintf(stderr, &quot;can't open unix file %s\n&quot;, filename);
359 360 361 362 363
    }

    /*
     * create the large object
     */
364 365 366
    lobjId = lo_creat(conn, INV_READ | INV_WRITE);
    if (lobjId == 0)
        fprintf(stderr, &quot;can't create large object\n&quot;);
367 368

    lobj_fd = lo_open(conn, lobjId, INV_WRITE);
369

370 371 372
    /*
     * read in from the Unix file and write to the inversion file
     */
373 374 375 376 377
    while ((nbytes = read(fd, buf, BUFSIZE)) &gt; 0)
    {
        tmp = lo_write(conn, lobj_fd, buf, nbytes);
        if (tmp &lt; nbytes)
            fprintf(stderr, &quot;error while reading large object\n&quot;);
378 379 380 381 382 383 384 385
    }

    (void) close(fd);
    (void) lo_close(conn, lobj_fd);

    return lobjId;
}

386 387
void
pickout(PGconn *conn, Oid lobjId, int start, int len)
388
{
389 390 391 392
    int         lobj_fd;
    char       *buf;
    int         nbytes;
    int         nread;
393 394

    lobj_fd = lo_open(conn, lobjId, INV_READ);
395 396 397 398
    if (lobj_fd &lt; 0)
    {
        fprintf(stderr, &quot;can't open large object %d\n&quot;,
                lobjId);
399 400 401
    }

    lo_lseek(conn, lobj_fd, start, SEEK_SET);
402
    buf = malloc(len + 1);
403 404

    nread = 0;
405 406 407 408 409 410
    while (len - nread &gt; 0)
    {
        nbytes = lo_read(conn, lobj_fd, buf, len - nread);
        buf[nbytes] = ' ';
        fprintf(stderr, &quot;&gt;&gt;&gt; %s&quot;, buf);
        nread += nbytes;
411
    }
412 413
    free(buf);
    fprintf(stderr, &quot;\n&quot;);
414 415 416
    lo_close(conn, lobj_fd);
}

417 418
void
overwrite(PGconn *conn, Oid lobjId, int start, int len)
419
{
420 421 422 423 424
    int         lobj_fd;
    char       *buf;
    int         nbytes;
    int         nwritten;
    int         i;
425 426

    lobj_fd = lo_open(conn, lobjId, INV_READ);
427 428 429 430
    if (lobj_fd &lt; 0)
    {
        fprintf(stderr, &quot;can't open large object %d\n&quot;,
                lobjId);
431 432 433
    }

    lo_lseek(conn, lobj_fd, start, SEEK_SET);
434
    buf = malloc(len + 1);
435

436 437
    for (i = 0; i &lt; len; i++)
        buf[i] = 'X';
438 439 440
    buf[i] = ' ';

    nwritten = 0;
441 442 443 444
    while (len - nwritten &gt; 0)
    {
        nbytes = lo_write(conn, lobj_fd, buf + nwritten, len - nwritten);
        nwritten += nbytes;
445
    }
446 447
    free(buf);
    fprintf(stderr, &quot;\n&quot;);
448 449 450 451
    lo_close(conn, lobj_fd);
}

/*
452
 * exportFile *    export large object &quot;lobjOid&quot; to file &quot;out_filename&quot;
453 454
 *
 */
455 456
void
exportFile(PGconn *conn, Oid lobjId, char *filename)
457
{
458 459 460 461 462
    int         lobj_fd;
    char        buf[BUFSIZE];
    int         nbytes,
                tmp;
    int         fd;
463 464

    /*
465
     * create an inversion &quot;object&quot;
466 467
     */
    lobj_fd = lo_open(conn, lobjId, INV_READ);
468 469 470 471
    if (lobj_fd &lt; 0)
    {
        fprintf(stderr, &quot;can't open large object %d\n&quot;,
                lobjId);
472 473 474 475 476
    }

    /*
     * open the file to be written to
     */
477 478 479 480 481
    fd = open(filename, O_CREAT | O_WRONLY, 0666);
    if (fd &lt; 0)
    {                           /* error */
        fprintf(stderr, &quot;can't open unix file %s\n&quot;,
                filename);
482 483 484 485 486
    }

    /*
     * read in from the Unix file and write to the inversion file
     */
487 488 489 490 491 492 493 494
    while ((nbytes = lo_read(conn, lobj_fd, buf, BUFSIZE)) &gt; 0)
    {
        tmp = write(fd, buf, nbytes);
        if (tmp &lt; nbytes)
        {
            fprintf(stderr, &quot;error while writing %s\n&quot;,
                    filename);
        }
495 496 497 498 499 500 501 502 503
    }

    (void) lo_close(conn, lobj_fd);
    (void) close(fd);

    return;
}

void
504
exit_nicely(PGconn *conn)
505
{
506 507
    PQfinish(conn);
    exit(1);
508 509 510 511 512
}

int
main(int argc, char **argv)
{
513 514 515 516 517 518 519 520 521 522 523 524
    char       *in_filename,
               *out_filename;
    char       *database;
    Oid         lobjOid;
    PGconn     *conn;
    PGresult   *res;

    if (argc != 4)
    {
        fprintf(stderr, &quot;Usage: %s database_name in_filename out_filename\n&quot;,
                argv[0]);
        exit(1);
525 526 527 528 529 530 531 532 533 534 535 536
    }

    database = argv[1];
    in_filename = argv[2];
    out_filename = argv[3];

    /*
     * set up the connection
     */
    conn = PQsetdb(NULL, NULL, NULL, NULL, database);

    /* check to see that the backend connection was successfully made */
537 538 539 540 541
    if (PQstatus(conn) == CONNECTION_BAD)
    {
        fprintf(stderr, &quot;Connection to database '%s' failed.\n&quot;, database);
        fprintf(stderr, &quot;%s&quot;, PQerrorMessage(conn));
        exit_nicely(conn);
542 543
    }

544
    res = PQexec(conn, &quot;begin&quot;);
545 546
    PQclear(res);

547
    printf(&quot;importing file %s\n&quot;, in_filename);
548 549 550
/*  lobjOid = importFile(conn, in_filename); */
    lobjOid = lo_import(conn, in_filename);
/*
551
    printf(&quot;as large object %d.\n&quot;, lobjOid);
552

553
    printf(&quot;picking out bytes 1000-2000 of the large object\n&quot;);
554 555
    pickout(conn, lobjOid, 1000, 1000);

556
    printf(&quot;overwriting bytes 1000-2000 of the large object with X's\n&quot;);
557 558 559
    overwrite(conn, lobjOid, 1000, 1000);
*/

560
    printf(&quot;exporting large object to file %s\n&quot;, out_filename);
561
/*    exportFile(conn, lobjOid, out_filename); */
562
    lo_export(conn, lobjOid, out_filename);
563

564
    res = PQexec(conn, &quot;end&quot;);
565 566 567 568
    PQclear(res);
    PQfinish(conn);
    exit(0);
}
T
Thomas G. Lockhart 已提交
569
</programlisting>
P
Peter Eisentraut 已提交
570
</example>
T
Thomas G. Lockhart 已提交
571 572 573 574 575 576

</sect1>
</chapter>

<!-- Keep this comment at the end of the file
Local variables:
577
mode:sgml
T
Thomas G. Lockhart 已提交
578 579 580 581 582 583 584 585 586
sgml-omittag:nil
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"./reference.ced"
sgml-exposed-tags:nil
587
sgml-local-catalogs:("/usr/lib/sgml/catalog")
T
Thomas G. Lockhart 已提交
588 589 590
sgml-local-ecat-files:nil
End:
-->