]> granicus.if.org Git - postgresql/blob - doc/src/sgml/lobj.sgml
4cdac668f0d01b95fef5a944456a048ad76836ad
[postgresql] / doc / src / sgml / lobj.sgml
1 <!--
2 $Header: /cvsroot/pgsql/doc/src/sgml/lobj.sgml,v 1.31 2003/11/01 01:56:29 petere Exp $
3 -->
4
5  <chapter id="largeObjects">
6   <title id="largeObjects-title">Large Objects</title>
7
8   <indexterm zone="largeobjects"><primary>large object</></>
9   <indexterm><primary>BLOB</><see>large object</></>
10
11    <para>
12     In <productname>PostgreSQL</productname> releases prior to 7.1,
13     the size of any row in the database could not exceed the size of a
14     data page.  Since the size of a data page is 8192 bytes (the
15     default, which can be raised up to 32768), the upper limit on the
16     size of a data value was relatively low. To support the storage of
17     larger atomic values, <productname>PostgreSQL</productname>
18     provided and continues to provide a large object interface.  This
19     interface provides file-oriented access to user data that is stored in
20     a special large-object structure.
21    </para>
22
23    <para>
24     This chapter describes the implementation and the programming and
25     query language interfaces to <productname>PostgreSQL</productname>
26     large object data.  We use the <application>libpq</application> C
27     library for the examples in this chapter, but most programming
28     interfaces native to <productname>PostgreSQL</productname> support
29     equivalent functionality.  Other interfaces may use the large
30     object interface internally to provide generic support for large
31     values.  This is not described here.
32    </para>
33
34   <sect1 id="lo-history">
35    <title>History</title>
36
37    <para>
38     <productname>POSTGRES 4.2</productname>, the indirect predecessor
39     of <productname>PostgreSQL</productname>, supported three standard
40     implementations of large objects: as files external to the
41     <productname>POSTGRES</productname> server, as external files
42     managed by the <productname>POSTGRES</productname> server, and as
43     data stored within the <productname>POSTGRES</productname>
44     database. This caused considerable confusion among users. As a
45     result, only support for large objects as data stored within the
46     database is retained in <productname>PostgreSQL</productname>.
47     Even though this is slower to access, it provides stricter data
48     integrity.  For historical reasons, this storage scheme is
49     referred to as <firstterm>Inversion large
50     objects</firstterm>. (You will see the term Inversion used
51     occasionally to mean the same thing as large object.)  Since
52     <productname>PostgreSQL 7.1</productname>, all large objects are
53     placed in one system table called
54     <classname>pg_largeobject</classname>.
55    </para>
56
57    <para>
58     <indexterm><primary>TOAST</></>
59     <indexterm><primary>sliced bread</><see>TOAST</></indexterm>
60     <productname>PostgreSQL 7.1</productname> introduced a mechanism
61     (nicknamed <quote><acronym>TOAST</acronym></quote>) that allows
62     data rows to be much larger than individual data pages.  This
63     makes the large object interface partially obsolete.  One
64     remaining advantage of the large object interface is that it allows values up
65     to 2 GB in size, whereas <acronym>TOAST</acronym> can only handle 1 GB.
66    </para>
67
68   </sect1>
69
70   <sect1 id="lo-implementation">
71    <title>Implementation Features</title>
72
73    <para>
74     The large object implementation breaks  large
75     objects  up  into  <quote>chunks</quote>  and  stores  the chunks in
76     rows in the database.  A B-tree index guarantees fast
77     searches for the correct chunk number when doing random
78     access reads and writes.
79    </para>
80   </sect1>
81
82   <sect1 id="lo-interfaces">
83    <title>Client Interfaces</title>
84
85    <para>
86     This section describes the facilities that
87     <productname>PostgreSQL</productname> client interface libraries
88     provide for accessing large objects.  All large object
89     manipulation using these functions <emphasis>must</emphasis> take
90     place within an SQL transaction block.  (This requirement is
91     strictly enforced as of <productname>PostgreSQL 6.5</>, though it
92     has been an implicit requirement in previous versions, resulting
93     in misbehavior if ignored.)
94     The  <productname>PostgreSQL</productname>  large  object interface is modeled after
95     the <acronym>Unix</acronym>  file-system  interface,  with  analogues  of
96     <function>open</function>,  <function>read</function>,
97     <function>write</function>,
98     <function>lseek</function>, etc.
99    </para>
100
101    <para>
102     Client applications which use the large object interface in
103     <application>libpq</application> should include the header file
104     <filename>libpq/libpq-fs.h</filename> and link with the
105     <application>libpq</application> library.
106    </para>
107
108    <sect2>
109     <title>Creating a Large Object</title>
110
111     <para>
112      The function
113 <synopsis>
114 Oid lo_creat(PGconn *conn, int mode);
115 </synopsis>
116      <indexterm><primary>lo_creat</></>
117      creates a new large  object.  
118      <replaceable class="parameter">mode</replaceable>  is  a  bit mask
119      describing  several  different  attributes  of  the new
120      object.  The symbolic constants listed here are defined
121      in the header file <filename>libpq/libpq-fs.h</filename>.
122      The access type (read, write, or both) is controlled by
123      or'ing together the bits <symbol>INV_READ</symbol>  and
124      <symbol>INV_WRITE</symbol>.  The low-order sixteen bits of the mask have
125      historically been used at Berkeley to designate the storage  manager  number on which the large object
126      should reside.  These
127      bits should always be zero now.
128      The return value is the OID that was assigned to the new large object.
129     </para>
130
131     <para>
132      An example:
133 <programlisting>
134 inv_oid = lo_creat(INV_READ|INV_WRITE);
135 </programlisting>
136     </para>
137    </sect2>
138
139    <sect2>
140     <title>Importing a Large Object</title>
141
142     <para>
143      To import an operating system file as a large object, call
144 <synopsis>
145 Oid lo_import(PGconn *conn, const char *filename);
146 </synopsis>
147      <indexterm><primary>lo_import</></>
148      <replaceable class="parameter">filename</replaceable> 
149      specifies the operating system name of
150      the file to be imported as a large object.
151      The return value is the OID that was assigned to the new large object.
152     </para>
153    </sect2>
154
155    <sect2>
156     <title>Exporting a Large Object</title>
157
158     <para>
159      To export a large object
160      into an operating system file, call
161 <synopsis>
162 int lo_export(PGconn *conn, Oid lobjId, const char *filename);
163 </synopsis>
164      <indexterm><primary>lo_export</></>
165      The <parameter>lobjId</parameter> argument specifies  the  OID  of  the  large
166      object  to  export  and the <parameter>filename</parameter> argument specifies
167      the operating system name name of the file.
168     </para>
169    </sect2>
170
171    <sect2>
172     <title>Opening an Existing Large Object</title>
173
174     <para>
175      To open an existing large object, call
176 <synopsis>
177 int lo_open(PGconn *conn, Oid lobjId, int mode);
178 </synopsis>
179      <indexterm><primary>lo_open</></>
180      The <parameter>lobjId</parameter> argument specifies  the  OID  of  the  large
181      object  to  open.   The  <parameter>mode</parameter>  bits control whether the
182      object is opened  for  reading  (<symbol>INV_READ</>),  writing (<symbol>INV_WRITE</symbol>),  or
183      both.
184      A  large  object cannot be opened before it is created.
185      <function>lo_open</function> returns a large object descriptor
186      for later use in <function>lo_read</function>, <function>lo_write</function>,
187      <function>lo_lseek</function>, <function>lo_tell</function>, and
188      <function>lo_close</function>.  The descriptor is only valid for
189      the duration of the current transaction.
190 </para>
191 </sect2>
192
193 <sect2>
194 <title>Writing Data to a Large Object</title>
195
196 <para>
197      The function
198 <synopsis>
199 int lo_write(PGconn *conn, int fd, const char *buf, size_t len);
200 </synopsis>
201      <indexterm><primary>lo_write</></> writes
202      <parameter>len</parameter> bytes from <parameter>buf</parameter>
203      to large object <parameter>fd</>.  The <parameter>fd</parameter>
204      argument must have been returned by a previous
205      <function>lo_open</function>.  The number of bytes actually
206      written is returned.  In the event of an error, the return value
207      is negative.
208 </para>
209 </sect2>
210
211 <sect2>
212 <title>Reading Data from a Large Object</title>
213
214 <para>
215      The function
216 <synopsis>
217 int lo_read(PGconn *conn, int fd, char *buf, size_t len);
218 </synopsis>
219      <indexterm><primary>lo_read</></> reads
220      <parameter>len</parameter> bytes from large object
221      <parameter>fd</parameter> into <parameter>buf</parameter>. The
222      <parameter>fd</parameter> argument must have been returned by a
223      previous <function>lo_open</function>.  The number of bytes
224      actually read is returned. In the event of an error, the return
225      value is negative.
226 </para>
227 </sect2>
228
229 <sect2>
230 <title>Seeking on a Large Object</title>
231
232 <para>
233      To change the current read or write location on a large
234      object, call
235 <synopsis>
236 int lo_lseek(PGconn *conn, int fd, int offset, int whence);
237 </synopsis>
238      <indexterm><primary>lo_lseek</></> This function moves the
239      current location pointer for the large object described by
240      <parameter>fd</> to the new location specified by
241      <parameter>offset</>.  The valid values for <parameter>whence</>
242      are <symbol>SEEK_SET</> (seek from object start),
243      <symbol>SEEK_CUR</> (seek from current position), and
244      <symbol>SEEK_END</> (seek from object end).  The return value is
245      the new location pointer.
246 </para>
247 </sect2>
248
249 <sect2>
250 <title>Obtaining the Seek Position of a Large Object</title>
251
252 <para>
253      To obtain the current read or write location of a large object,
254      call
255 <synopsis>
256 int lo_tell(PGconn *conn, int fd);
257 </synopsis>
258      <indexterm><primary>lo_tell</></> If there is an error, the
259      return value is negative.
260 </para>
261 </sect2>
262
263 <sect2>
264 <title>Closing a Large Object Descriptor</title>
265
266 <para>
267      A large object may be closed by calling
268 <synopsis>
269 int lo_close(PGconn *conn, int fd);
270 </synopsis>
271      <indexterm><primary>lo_close</></> where <parameter>fd</> is a
272      large object descriptor returned by <function>lo_open</function>.
273      On success, <function>lo_close</function> returns zero.  On
274      error, the return value is negative.
275 </para>
276
277 <para>
278      Any large  object  descriptors that remain open at the end of a
279      transaction will be closed automatically.
280 </para>
281 </sect2>
282
283    <sect2>
284     <title>Removing a Large Object</title>
285
286     <para>
287      To remove a large object from the database, call
288 <synopsis>
289 int lo_unlink(PGconn *conn, Oid lobjId);
290 </synopsis>
291      <indexterm><primary>lo_unlink</></> The
292      <parameter>lobjId</parameter> argument specifies the OID of the
293      large object to remove.  In the event of an error, the return
294      value is negative.
295     </para>
296    </sect2>
297
298
299 </sect1>
300
301 <sect1 id="lo-funcs">
302 <title>Server-side Functions</title>
303
304 <para>
305      There are two built-in server-side functions,
306      <function>lo_import</function><indexterm><primary>lo_import</></>
307      and
308      <function>lo_export</function>,<indexterm><primary>lo_export</></>
309      for large object access, which are available for use in
310      <acronym>SQL</acronym> commands.  Here is an example of their
311      use:
312 <programlisting>
313 CREATE TABLE image (
314     name            text,
315     raster          oid
316 );
317
318 INSERT INTO image (name, raster)
319     VALUES ('beautiful image', lo_import('/etc/motd'));
320
321 SELECT lo_export(image.raster, '/tmp/motd') FROM image
322     WHERE name = 'beautiful image';
323 </programlisting>
324 </para>
325
326 <para>
327 These functions read and write files in the server's file system, using the
328 permissions of the database's owning user.  Therefore, their use is restricted
329 to superusers.  (In contrast, the client-side import and export functions
330 read and write files in the client's file system, using the permissions of
331 the client program.  Their use is not restricted.)
332 </para>
333 </sect1>
334
335 <sect1 id="lo-examplesect">
336 <title>Example Program</title>
337
338 <para>
339      <xref linkend="lo-example"> is a sample program which shows how the large object  
340      interface
341      in  <application>libpq</>  can  be used.  Parts of the program are 
342      commented out but are left in the source for  the  reader's
343      benefit.  This program can also be found in
344      <filename>src/test/examples/testlo.c</filename> in the source distribution.
345 </para>
346
347   <example id="lo-example">
348    <title>Large Objects with <application>libpq</application> Example Program</title>
349 <programlisting>
350 /*--------------------------------------------------------------
351  *
352  * testlo.c--
353  *    test using large objects with libpq
354  *
355  * Copyright (c) 1994, Regents of the University of California
356  *
357  *--------------------------------------------------------------
358  */
359 #include &lt;stdio.h&gt;
360 #include &quot;libpq-fe.h&quot;
361 #include &quot;libpq/libpq-fs.h&quot;
362
363 #define BUFSIZE          1024
364
365 /*
366  * importFile
367  *    import file &quot;in_filename&quot; into database as large object &quot;lobjOid&quot;
368  *
369  */
370 Oid
371 importFile(PGconn *conn, char *filename)
372 {
373     Oid         lobjId;
374     int         lobj_fd;
375     char        buf[BUFSIZE];
376     int         nbytes,
377                 tmp;
378     int         fd;
379
380     /*
381      * open the file to be read in
382      */
383     fd = open(filename, O_RDONLY, 0666);
384     if (fd &lt; 0)
385     {                           /* error */
386         fprintf(stderr, &quot;can't open unix file %s\n&quot;, filename);
387     }
388
389     /*
390      * create the large object
391      */
392     lobjId = lo_creat(conn, INV_READ | INV_WRITE);
393     if (lobjId == 0)
394         fprintf(stderr, &quot;can't create large object\n&quot;);
395
396     lobj_fd = lo_open(conn, lobjId, INV_WRITE);
397
398     /*
399      * read in from the Unix file and write to the inversion file
400      */
401     while ((nbytes = read(fd, buf, BUFSIZE)) &gt; 0)
402     {
403         tmp = lo_write(conn, lobj_fd, buf, nbytes);
404         if (tmp &lt; nbytes)
405             fprintf(stderr, &quot;error while reading large object\n&quot;);
406     }
407
408     (void) close(fd);
409     (void) lo_close(conn, lobj_fd);
410
411     return lobjId;
412 }
413
414 void
415 pickout(PGconn *conn, Oid lobjId, int start, int len)
416 {
417     int         lobj_fd;
418     char       *buf;
419     int         nbytes;
420     int         nread;
421
422     lobj_fd = lo_open(conn, lobjId, INV_READ);
423     if (lobj_fd &lt; 0)
424     {
425         fprintf(stderr, &quot;can't open large object %d\n&quot;,
426                 lobjId);
427     }
428
429     lo_lseek(conn, lobj_fd, start, SEEK_SET);
430     buf = malloc(len + 1);
431
432     nread = 0;
433     while (len - nread &gt; 0)
434     {
435         nbytes = lo_read(conn, lobj_fd, buf, len - nread);
436         buf[nbytes] = ' ';
437         fprintf(stderr, &quot;&gt;&gt;&gt; %s&quot;, buf);
438         nread += nbytes;
439     }
440     free(buf);
441     fprintf(stderr, &quot;\n&quot;);
442     lo_close(conn, lobj_fd);
443 }
444
445 void
446 overwrite(PGconn *conn, Oid lobjId, int start, int len)
447 {
448     int         lobj_fd;
449     char       *buf;
450     int         nbytes;
451     int         nwritten;
452     int         i;
453
454     lobj_fd = lo_open(conn, lobjId, INV_READ);
455     if (lobj_fd &lt; 0)
456     {
457         fprintf(stderr, &quot;can't open large object %d\n&quot;,
458                 lobjId);
459     }
460
461     lo_lseek(conn, lobj_fd, start, SEEK_SET);
462     buf = malloc(len + 1);
463
464     for (i = 0; i &lt; len; i++)
465         buf[i] = 'X';
466     buf[i] = ' ';
467
468     nwritten = 0;
469     while (len - nwritten &gt; 0)
470     {
471         nbytes = lo_write(conn, lobj_fd, buf + nwritten, len - nwritten);
472         nwritten += nbytes;
473     }
474     free(buf);
475     fprintf(stderr, &quot;\n&quot;);
476     lo_close(conn, lobj_fd);
477 }
478
479 /*
480  * exportFile *    export large object &quot;lobjOid&quot; to file &quot;out_filename&quot;
481  *
482  */
483 void
484 exportFile(PGconn *conn, Oid lobjId, char *filename)
485 {
486     int         lobj_fd;
487     char        buf[BUFSIZE];
488     int         nbytes,
489                 tmp;
490     int         fd;
491
492     /*
493      * create an inversion &quot;object&quot;
494      */
495     lobj_fd = lo_open(conn, lobjId, INV_READ);
496     if (lobj_fd &lt; 0)
497     {
498         fprintf(stderr, &quot;can't open large object %d\n&quot;,
499                 lobjId);
500     }
501
502     /*
503      * open the file to be written to
504      */
505     fd = open(filename, O_CREAT | O_WRONLY, 0666);
506     if (fd &lt; 0)
507     {                           /* error */
508         fprintf(stderr, &quot;can't open unix file %s\n&quot;,
509                 filename);
510     }
511
512     /*
513      * read in from the Unix file and write to the inversion file
514      */
515     while ((nbytes = lo_read(conn, lobj_fd, buf, BUFSIZE)) &gt; 0)
516     {
517         tmp = write(fd, buf, nbytes);
518         if (tmp &lt; nbytes)
519         {
520             fprintf(stderr, &quot;error while writing %s\n&quot;,
521                     filename);
522         }
523     }
524
525     (void) lo_close(conn, lobj_fd);
526     (void) close(fd);
527
528     return;
529 }
530
531 void
532 exit_nicely(PGconn *conn)
533 {
534     PQfinish(conn);
535     exit(1);
536 }
537
538 int
539 main(int argc, char **argv)
540 {
541     char       *in_filename,
542                *out_filename;
543     char       *database;
544     Oid         lobjOid;
545     PGconn     *conn;
546     PGresult   *res;
547
548     if (argc != 4)
549     {
550         fprintf(stderr, &quot;Usage: %s database_name in_filename out_filename\n&quot;,
551                 argv[0]);
552         exit(1);
553     }
554
555     database = argv[1];
556     in_filename = argv[2];
557     out_filename = argv[3];
558
559     /*
560      * set up the connection
561      */
562     conn = PQsetdb(NULL, NULL, NULL, NULL, database);
563
564     /* check to see that the backend connection was successfully made */
565     if (PQstatus(conn) == CONNECTION_BAD)
566     {
567         fprintf(stderr, &quot;Connection to database '%s' failed.\n&quot;, database);
568         fprintf(stderr, &quot;%s&quot;, PQerrorMessage(conn));
569         exit_nicely(conn);
570     }
571
572     res = PQexec(conn, &quot;begin&quot;);
573     PQclear(res);
574
575     printf(&quot;importing file %s\n&quot;, in_filename);
576 /*  lobjOid = importFile(conn, in_filename); */
577     lobjOid = lo_import(conn, in_filename);
578 /*
579     printf(&quot;as large object %d.\n&quot;, lobjOid);
580
581     printf(&quot;picking out bytes 1000-2000 of the large object\n&quot;);
582     pickout(conn, lobjOid, 1000, 1000);
583
584     printf(&quot;overwriting bytes 1000-2000 of the large object with X's\n&quot;);
585     overwrite(conn, lobjOid, 1000, 1000);
586 */
587
588     printf(&quot;exporting large object to file %s\n&quot;, out_filename);
589 /*    exportFile(conn, lobjOid, out_filename); */
590     lo_export(conn, lobjOid, out_filename);
591
592     res = PQexec(conn, &quot;end&quot;);
593     PQclear(res);
594     PQfinish(conn);
595     exit(0);
596 }
597 </programlisting>
598 </example>
599
600 </sect1>
601 </chapter>
602
603 <!-- Keep this comment at the end of the file
604 Local variables:
605 mode:sgml
606 sgml-omittag:nil
607 sgml-shorttag:t
608 sgml-minimize-attributes:nil
609 sgml-always-quote-attributes:t
610 sgml-indent-step:1
611 sgml-indent-data:t
612 sgml-parent-document:nil
613 sgml-default-dtd-file:"./reference.ced"
614 sgml-exposed-tags:nil
615 sgml-local-catalogs:("/usr/lib/sgml/catalog")
616 sgml-local-ecat-files:nil
617 End:
618 -->