lobj.sgml 18.3 KB
Newer Older
1
<!--
P
Peter Eisentraut 已提交
2
$Header: /cvsroot/pgsql/doc/src/sgml/lobj.sgml,v 1.24 2001/11/12 19:19:39 petere 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
109 110 111 112 113 114
    the <acronym>Unix</acronym>  file  system  interface,  with  analogues  of
    <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  
116
    photographs  of  faces, then a function called beard could
117
    be declared on <type>mugshot</type> data.  Beard could look  at  the
118 119 120 121 122 123
    lower third of a photograph, and determine the color of
    the beard that appeared  there,  if  any.   The  entire
    large  object value need not be buffered, or even 
    examined, by the beard function.
    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
143 144 145 146 147 148 149
     OR'ing together the bits <symbol>INV_READ</symbol>  and
     <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>
159 160 161 162
     To import a <acronym>UNIX</acronym> file as a large object, call
<synopsis>
Oid lo_import(PGconn *<replaceable class="parameter">conn</replaceable>, const char *<replaceable class="parameter">filename</replaceable>)
</synopsis>
163
    <replaceable class="parameter">filename</replaceable> 
164
     specifies the  <acronym>Unix</acronym>  path 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
174 175 176 177
     into <acronym>UNIX</acronym> file, call
<synopsis>
int lo_export(PGconn *<replaceable class="parameter">conn</replaceable>, Oid <replaceable class="parameter">lobjId</replaceable>, const char *<replaceable class="parameter">filename</replaceable>)
</synopsis>
178 179 180
     The <parameter>lobjId</parameter> argument specifies  the  Oid  of  the  large
     object  to  export  and the <parameter>filename</parameter> argument specifies
     the <acronym>UNIX</acronym> path 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>
192 193 194
     The <parameter>lobjId</parameter> argument specifies  the  Oid  of  the  large
     object  to  open.   The  <parameter>mode</parameter>  bits control whether the
     object is opened  for  reading  (<symbol>INV_READ</>),  writing  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 244
     This routine moves the current location pointer for the
     large object described by fd to the new location specified 
245 246
     by offset.  The valid values for whence are
     SEEK_SET, SEEK_CUR, and 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>
258
     where  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 270 271

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

    <para>
     To remove a large object from the database, call
<synopsis>
Oid lo_unlink(PGconn *<replaceable class="parameter">conn</replaceable>, Oid lobjId)
</synopsis>
272
     The <parameter>lobjId</parameter> argument specifies  the  Oid  of  the  large
273 274 275 276 277
     object  to  remove.
    </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 284 285 286
<para>
     There  are two built-in registered functions, <acronym>lo_import</acronym>
     and <acronym>lo_export</acronym> which  are  convenient  for  use
    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'));

B
Bruce Momjian 已提交
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>
308 309
     Below is a sample program which shows how the large object  
     interface
310
     in  <application>libpq</>  can  be used.  Parts of the program are 
311 312
     commented out but are left in the source for  the  readers
     benefit.  This program can be found in
T
Thomas G. Lockhart 已提交
313
<filename>
314
../src/test/examples
T
Thomas G. Lockhart 已提交
315
</filename>
316
     Frontend applications which use the large object interface  
317 318
     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 已提交
319 320
</para>
</sect1>
321

P
Peter Eisentraut 已提交
322 323
<sect1 id="lo-example">
<title>Example Program</title>
324

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

#define BUFSIZE          1024

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

    /*
     * open the file to be read in
     */
    fd = open(filename, O_RDONLY, 0666);
362 363 364
    if (fd &lt; 0)
    {                           /* error */
        fprintf(stderr, &quot;can't open unix file %s\n&quot;, filename);
365 366 367 368 369
    }

    /*
     * create the large object
     */
370 371 372
    lobjId = lo_creat(conn, INV_READ | INV_WRITE);
    if (lobjId == 0)
        fprintf(stderr, &quot;can't create large object\n&quot;);
373 374

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

376 377 378
    /*
     * read in from the Unix file and write to the inversion file
     */
379 380 381 382 383
    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;);
384 385 386 387 388 389 390 391
    }

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

    return lobjId;
}

392 393
void
pickout(PGconn *conn, Oid lobjId, int start, int len)
394
{
395 396 397 398
    int         lobj_fd;
    char       *buf;
    int         nbytes;
    int         nread;
399 400

    lobj_fd = lo_open(conn, lobjId, INV_READ);
401 402 403 404
    if (lobj_fd &lt; 0)
    {
        fprintf(stderr, &quot;can't open large object %d\n&quot;,
                lobjId);
405 406 407
    }

    lo_lseek(conn, lobj_fd, start, SEEK_SET);
408
    buf = malloc(len + 1);
409 410

    nread = 0;
411 412 413 414 415 416
    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;
417
    }
418 419
    free(buf);
    fprintf(stderr, &quot;\n&quot;);
420 421 422
    lo_close(conn, lobj_fd);
}

423 424
void
overwrite(PGconn *conn, Oid lobjId, int start, int len)
425
{
426 427 428 429 430
    int         lobj_fd;
    char       *buf;
    int         nbytes;
    int         nwritten;
    int         i;
431 432

    lobj_fd = lo_open(conn, lobjId, INV_READ);
433 434 435 436
    if (lobj_fd &lt; 0)
    {
        fprintf(stderr, &quot;can't open large object %d\n&quot;,
                lobjId);
437 438 439
    }

    lo_lseek(conn, lobj_fd, start, SEEK_SET);
440
    buf = malloc(len + 1);
441

442 443
    for (i = 0; i &lt; len; i++)
        buf[i] = 'X';
444 445 446
    buf[i] = ' ';

    nwritten = 0;
447 448 449 450
    while (len - nwritten &gt; 0)
    {
        nbytes = lo_write(conn, lobj_fd, buf + nwritten, len - nwritten);
        nwritten += nbytes;
451
    }
452 453
    free(buf);
    fprintf(stderr, &quot;\n&quot;);
454 455 456 457
    lo_close(conn, lobj_fd);
}

/*
458
 * exportFile *    export large object &quot;lobjOid&quot; to file &quot;out_filename&quot;
459 460
 *
 */
461 462
void
exportFile(PGconn *conn, Oid lobjId, char *filename)
463
{
464 465 466 467 468
    int         lobj_fd;
    char        buf[BUFSIZE];
    int         nbytes,
                tmp;
    int         fd;
469 470

    /*
471
     * create an inversion &quot;object&quot;
472 473
     */
    lobj_fd = lo_open(conn, lobjId, INV_READ);
474 475 476 477
    if (lobj_fd &lt; 0)
    {
        fprintf(stderr, &quot;can't open large object %d\n&quot;,
                lobjId);
478 479 480 481 482
    }

    /*
     * open the file to be written to
     */
483 484 485 486 487
    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);
488 489 490 491 492
    }

    /*
     * read in from the Unix file and write to the inversion file
     */
493 494 495 496 497 498 499 500
    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);
        }
501 502 503 504 505 506 507 508 509
    }

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

    return;
}

void
510
exit_nicely(PGconn *conn)
511
{
512 513
    PQfinish(conn);
    exit(1);
514 515 516 517 518
}

int
main(int argc, char **argv)
{
519 520 521 522 523 524 525 526 527 528 529 530
    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);
531 532 533 534 535 536 537 538 539 540 541 542
    }

    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 */
543 544 545 546 547
    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);
548 549
    }

550
    res = PQexec(conn, &quot;begin&quot;);
551 552
    PQclear(res);

553
    printf(&quot;importing file %s\n&quot;, in_filename);
554 555 556
/*  lobjOid = importFile(conn, in_filename); */
    lobjOid = lo_import(conn, in_filename);
/*
557
    printf(&quot;as large object %d.\n&quot;, lobjOid);
558

559
    printf(&quot;picking out bytes 1000-2000 of the large object\n&quot;);
560 561
    pickout(conn, lobjOid, 1000, 1000);

562
    printf(&quot;overwriting bytes 1000-2000 of the large object with X's\n&quot;);
563 564 565
    overwrite(conn, lobjOid, 1000, 1000);
*/

566
    printf(&quot;exporting large object to file %s\n&quot;, out_filename);
567
/*    exportFile(conn, lobjOid, out_filename); */
568
    lo_export(conn, lobjOid, out_filename);
569

570
    res = PQexec(conn, &quot;end&quot;);
571 572 573 574
    PQclear(res);
    PQfinish(conn);
    exit(0);
}
T
Thomas G. Lockhart 已提交
575
</programlisting>
P
Peter Eisentraut 已提交
576
</example>
T
Thomas G. Lockhart 已提交
577 578 579 580 581 582

</sect1>
</chapter>

<!-- Keep this comment at the end of the file
Local variables:
583
mode:sgml
T
Thomas G. Lockhart 已提交
584 585 586 587 588 589 590 591 592
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
593
sgml-local-catalogs:("/usr/lib/sgml/catalog")
T
Thomas G. Lockhart 已提交
594 595 596
sgml-local-ecat-files:nil
End:
-->