1<!-- doc/src/sgml/lobj.sgml -->
2
3 <chapter id="largeobjects">
4  <title>Large Objects</title>
5
6  <indexterm zone="largeobjects"><primary>large object</primary></indexterm>
7  <indexterm><primary>BLOB</primary><see>large object</see></indexterm>
8
9   <para>
10    <productname>PostgreSQL</productname> has a <firstterm>large object</firstterm>
11    facility, which provides stream-style access to user data that is stored
12    in a special large-object structure.  Streaming access is useful
13    when working with data values that are too large to manipulate
14    conveniently as a whole.
15   </para>
16
17   <para>
18    This chapter describes the implementation and the programming and
19    query language interfaces to <productname>PostgreSQL</productname>
20    large object data.  We use the <application>libpq</application> C
21    library for the examples in this chapter, but most programming
22    interfaces native to <productname>PostgreSQL</productname> support
23    equivalent functionality.  Other interfaces might use the large
24    object interface internally to provide generic support for large
25    values.  This is not described here.
26   </para>
27
28  <sect1 id="lo-intro">
29   <title>Introduction</title>
30
31   <indexterm>
32    <primary>TOAST</primary>
33    <secondary>versus large objects</secondary>
34   </indexterm>
35
36   <para>
37    All large objects are stored in a single system table named <link
38    linkend="catalog-pg-largeobject"><structname>pg_largeobject</structname></link>.
39    Each large object also has an entry in the system table <link
40    linkend="catalog-pg-largeobject-metadata"><structname>pg_largeobject_metadata</structname></link>.
41    Large objects can be created, modified, and deleted using a read/write API
42    that is similar to standard operations on files.
43   </para>
44
45   <para>
46    <productname>PostgreSQL</productname> also supports a storage system called
47    <link
48    linkend="storage-toast"><quote><acronym>TOAST</acronym></quote></link>,
49    which automatically stores values
50    larger than a single database page into a secondary storage area per table.
51    This makes the large object facility partially obsolete.  One
52    remaining advantage of the large object facility is that it allows values
53    up to 4 TB in size, whereas <acronym>TOAST</acronym>ed fields can be at
54    most 1 GB.  Also, reading and updating portions of a large object can be
55    done efficiently, while most operations on a <acronym>TOAST</acronym>ed
56    field will read or write the whole value as a unit.
57   </para>
58
59  </sect1>
60
61  <sect1 id="lo-implementation">
62   <title>Implementation Features</title>
63
64   <para>
65    The large object implementation breaks large
66    objects up into <quote>chunks</quote> and stores the chunks in
67    rows in the database.  A B-tree index guarantees fast
68    searches for the correct chunk number when doing random
69    access reads and writes.
70   </para>
71
72   <para>
73    The chunks stored for a large object do not have to be contiguous.
74    For example, if an application opens a new large object, seeks to offset
75    1000000, and writes a few bytes there, this does not result in allocation
76    of 1000000 bytes worth of storage; only of chunks covering the range of
77    data bytes actually written.  A read operation will, however, read out
78    zeroes for any unallocated locations preceding the last existing chunk.
79    This corresponds to the common behavior of <quote>sparsely allocated</quote>
80    files in <acronym>Unix</acronym> file systems.
81   </para>
82
83   <para>
84    As of <productname>PostgreSQL</productname> 9.0, large objects have an owner
85    and a set of access permissions, which can be managed using
86    <xref linkend="sql-grant"/> and
87    <xref linkend="sql-revoke"/>.
88    <literal>SELECT</literal> privileges are required to read a large
89    object, and
90    <literal>UPDATE</literal> privileges are required to write or
91    truncate it.
92    Only the large object's owner (or a database superuser) can delete,
93    comment on, or change the owner of a large object.
94    To adjust this behavior for compatibility with prior releases, see the
95    <xref linkend="guc-lo-compat-privileges"/> run-time parameter.
96   </para>
97  </sect1>
98
99  <sect1 id="lo-interfaces">
100   <title>Client Interfaces</title>
101
102   <para>
103    This section describes the facilities that
104    <productname>PostgreSQL</productname>'s <application>libpq</application>
105    client interface library provides for accessing large objects.
106    The <productname>PostgreSQL</productname> large object interface is
107    modeled after the <acronym>Unix</acronym> file-system interface, with
108    analogues of <function>open</function>,  <function>read</function>,
109    <function>write</function>,
110    <function>lseek</function>, etc.
111   </para>
112
113   <para>
114    All large object manipulation using these functions
115    <emphasis>must</emphasis> take place within an SQL transaction block,
116    since large object file descriptors are only valid for the duration of
117    a transaction.
118   </para>
119
120   <para>
121    If an error occurs while executing any one of these functions, the
122    function will return an otherwise-impossible value, typically 0 or -1.
123    A message describing the error is stored in the connection object and
124    can be retrieved with <function>PQerrorMessage</function>.
125   </para>
126
127   <para>
128    Client applications that use these functions should include the header file
129    <filename>libpq/libpq-fs.h</filename> and link with the
130    <application>libpq</application> library.
131   </para>
132
133   <sect2 id="lo-create">
134    <title>Creating a Large Object</title>
135
136    <para>
137     <indexterm><primary>lo_creat</primary></indexterm>
138     The function
139<synopsis>
140Oid lo_creat(PGconn *conn, int mode);
141</synopsis>
142     creates a new large object.
143     The return value is the OID that was assigned to the new large object,
144     or <symbol>InvalidOid</symbol> (zero) on failure.
145
146     <replaceable class="parameter">mode</replaceable> is unused and
147     ignored as of <productname>PostgreSQL</productname> 8.1; however, for
148     backward compatibility with earlier releases it is best to
149     set it to <symbol>INV_READ</symbol>, <symbol>INV_WRITE</symbol>,
150     or <symbol>INV_READ</symbol> <literal>|</literal> <symbol>INV_WRITE</symbol>.
151     (These symbolic constants are defined
152     in the header file <filename>libpq/libpq-fs.h</filename>.)
153    </para>
154
155    <para>
156     An example:
157<programlisting>
158inv_oid = lo_creat(conn, INV_READ|INV_WRITE);
159</programlisting>
160    </para>
161
162    <para>
163     <indexterm><primary>lo_create</primary></indexterm>
164     The function
165<synopsis>
166Oid lo_create(PGconn *conn, Oid lobjId);
167</synopsis>
168     also creates a new large object.  The OID to be assigned can be
169     specified by <replaceable class="parameter">lobjId</replaceable>;
170     if so, failure occurs if that OID is already in use for some large
171     object.  If <replaceable class="parameter">lobjId</replaceable>
172     is <symbol>InvalidOid</symbol> (zero) then <function>lo_create</function> assigns an unused
173     OID (this is the same behavior as <function>lo_creat</function>).
174     The return value is the OID that was assigned to the new large object,
175     or <symbol>InvalidOid</symbol> (zero) on failure.
176    </para>
177
178    <para>
179     <function>lo_create</function> is new as of <productname>PostgreSQL</productname>
180     8.1; if this function is run against an older server version, it will
181     fail and return <symbol>InvalidOid</symbol>.
182    </para>
183
184    <para>
185     An example:
186<programlisting>
187inv_oid = lo_create(conn, desired_oid);
188</programlisting>
189    </para>
190   </sect2>
191
192   <sect2 id="lo-import">
193    <title>Importing a Large Object</title>
194
195    <para>
196     <indexterm><primary>lo_import</primary></indexterm>
197     To import an operating system file as a large object, call
198<synopsis>
199Oid lo_import(PGconn *conn, const char *filename);
200</synopsis>
201     <replaceable class="parameter">filename</replaceable>
202     specifies the operating system name of
203     the file to be imported as a large object.
204     The return value is the OID that was assigned to the new large object,
205     or <symbol>InvalidOid</symbol> (zero) on failure.
206     Note that the file is read by the client interface library, not by
207     the server; so it must exist in the client file system and be readable
208     by the client application.
209    </para>
210
211    <para>
212     <indexterm><primary>lo_import_with_oid</primary></indexterm>
213     The function
214<synopsis>
215Oid lo_import_with_oid(PGconn *conn, const char *filename, Oid lobjId);
216</synopsis>
217     also imports a new large object.  The OID to be assigned can be
218     specified by <replaceable class="parameter">lobjId</replaceable>;
219     if so, failure occurs if that OID is already in use for some large
220     object.  If <replaceable class="parameter">lobjId</replaceable>
221     is <symbol>InvalidOid</symbol> (zero) then <function>lo_import_with_oid</function> assigns an unused
222     OID (this is the same behavior as <function>lo_import</function>).
223     The return value is the OID that was assigned to the new large object,
224     or <symbol>InvalidOid</symbol> (zero) on failure.
225    </para>
226
227    <para>
228     <function>lo_import_with_oid</function> is new as of <productname>PostgreSQL</productname>
229     8.4 and uses <function>lo_create</function> internally which is new in 8.1; if this function is run against 8.0 or before, it will
230     fail and return <symbol>InvalidOid</symbol>.
231    </para>
232   </sect2>
233
234   <sect2 id="lo-export">
235    <title>Exporting a Large Object</title>
236
237    <para>
238     <indexterm><primary>lo_export</primary></indexterm>
239     To export a large object
240     into an operating system file, call
241<synopsis>
242int lo_export(PGconn *conn, Oid lobjId, const char *filename);
243</synopsis>
244     The <parameter>lobjId</parameter> argument specifies the OID of the large
245     object to export and the <parameter>filename</parameter> argument
246     specifies the operating system name of the file.  Note that the file is
247     written by the client interface library, not by the server.  Returns 1
248     on success, -1 on failure.
249    </para>
250   </sect2>
251
252   <sect2 id="lo-open">
253    <title>Opening an Existing Large Object</title>
254
255    <para>
256     <indexterm><primary>lo_open</primary></indexterm>
257     To open an existing large object for reading or writing, call
258<synopsis>
259int lo_open(PGconn *conn, Oid lobjId, int mode);
260</synopsis>
261     The <parameter>lobjId</parameter> argument specifies the OID of the large
262     object to open.   The <parameter>mode</parameter> bits control whether the
263     object is opened for reading (<symbol>INV_READ</symbol>), writing
264     (<symbol>INV_WRITE</symbol>), or both.
265     (These symbolic constants are defined
266     in the header file <filename>libpq/libpq-fs.h</filename>.)
267     <function>lo_open</function> returns a (non-negative) large object
268     descriptor for later use in <function>lo_read</function>,
269     <function>lo_write</function>, <function>lo_lseek</function>,
270     <function>lo_lseek64</function>, <function>lo_tell</function>,
271     <function>lo_tell64</function>, <function>lo_truncate</function>,
272     <function>lo_truncate64</function>, and <function>lo_close</function>.
273     The descriptor is only valid for
274     the duration of the current transaction.
275     On failure, -1 is returned.
276    </para>
277
278    <para>
279     The server currently does not distinguish between modes
280     <symbol>INV_WRITE</symbol> and <symbol>INV_READ</symbol> <literal>|</literal>
281     <symbol>INV_WRITE</symbol>: you are allowed to read from the descriptor
282     in either case.  However there is a significant difference between
283     these modes and <symbol>INV_READ</symbol> alone: with <symbol>INV_READ</symbol>
284     you cannot write on the descriptor, and the data read from it will
285     reflect the contents of the large object at the time of the transaction
286     snapshot that was active when <function>lo_open</function> was executed,
287     regardless of later writes by this or other transactions.  Reading
288     from a descriptor opened with <symbol>INV_WRITE</symbol> returns
289     data that reflects all writes of other committed transactions as well
290     as writes of the current transaction.  This is similar to the behavior
291     of <literal>REPEATABLE READ</literal> versus <literal>READ COMMITTED</literal> transaction
292     modes for ordinary SQL <command>SELECT</command> commands.
293    </para>
294
295    <para>
296     <function>lo_open</function> will fail if <literal>SELECT</literal>
297     privilege is not available for the large object, or
298     if <symbol>INV_WRITE</symbol> is specified and <literal>UPDATE</literal>
299     privilege is not available.
300     (Prior to <productname>PostgreSQL</productname> 11, these privilege
301     checks were instead performed at the first actual read or write call
302     using the descriptor.)
303     These privilege checks can be disabled with the
304     <xref linkend="guc-lo-compat-privileges"/> run-time parameter.
305    </para>
306
307    <para>
308     An example:
309<programlisting>
310inv_fd = lo_open(conn, inv_oid, INV_READ|INV_WRITE);
311</programlisting>
312    </para>
313</sect2>
314
315<sect2 id="lo-write">
316<title>Writing Data to a Large Object</title>
317
318<para>
319     <indexterm><primary>lo_write</primary></indexterm>
320     The function
321<synopsis>
322int lo_write(PGconn *conn, int fd, const char *buf, size_t len);
323</synopsis>
324     writes <parameter>len</parameter> bytes from <parameter>buf</parameter>
325     (which must be of size <parameter>len</parameter>) to large object
326     descriptor <parameter>fd</parameter>.  The <parameter>fd</parameter> argument must
327     have been returned by a previous <function>lo_open</function>.  The
328     number of bytes actually written is returned (in the current
329     implementation, this will always equal <parameter>len</parameter> unless
330     there is an error).  In the event of an error, the return value is -1.
331</para>
332
333<para>
334     Although the <parameter>len</parameter> parameter is declared as
335     <type>size_t</type>, this function will reject length values larger than
336     <literal>INT_MAX</literal>.  In practice, it's best to transfer data in chunks
337     of at most a few megabytes anyway.
338</para>
339</sect2>
340
341<sect2 id="lo-read">
342<title>Reading Data from a Large Object</title>
343
344<para>
345     <indexterm><primary>lo_read</primary></indexterm>
346     The function
347<synopsis>
348int lo_read(PGconn *conn, int fd, char *buf, size_t len);
349</synopsis>
350     reads up to <parameter>len</parameter> bytes from large object descriptor
351     <parameter>fd</parameter> into <parameter>buf</parameter> (which must be
352     of size <parameter>len</parameter>).  The <parameter>fd</parameter>
353     argument must have been returned by a previous
354     <function>lo_open</function>.  The number of bytes actually read is
355     returned; this will be less than <parameter>len</parameter> if the end of
356     the large object is reached first.  In the event of an error, the return
357     value is -1.
358</para>
359
360<para>
361     Although the <parameter>len</parameter> parameter is declared as
362     <type>size_t</type>, this function will reject length values larger than
363     <literal>INT_MAX</literal>.  In practice, it's best to transfer data in chunks
364     of at most a few megabytes anyway.
365</para>
366</sect2>
367
368<sect2 id="lo-seek">
369<title>Seeking in a Large Object</title>
370
371<para>
372     <indexterm><primary>lo_lseek</primary></indexterm>
373     To change the current read or write location associated with a
374     large object descriptor, call
375<synopsis>
376int lo_lseek(PGconn *conn, int fd, int offset, int whence);
377</synopsis>
378     This function moves the
379     current location pointer for the large object descriptor identified by
380     <parameter>fd</parameter> to the new location specified by
381     <parameter>offset</parameter>.  The valid values for <parameter>whence</parameter>
382     are <symbol>SEEK_SET</symbol> (seek from object start),
383     <symbol>SEEK_CUR</symbol> (seek from current position), and
384     <symbol>SEEK_END</symbol> (seek from object end).  The return value is
385     the new location pointer, or -1 on error.
386</para>
387
388<para>
389     <indexterm><primary>lo_lseek64</primary></indexterm>
390     When dealing with large objects that might exceed 2GB in size,
391     instead use
392<synopsis>
393pg_int64 lo_lseek64(PGconn *conn, int fd, pg_int64 offset, int whence);
394</synopsis>
395     This function has the same behavior
396     as <function>lo_lseek</function>, but it can accept an
397     <parameter>offset</parameter> larger than 2GB and/or deliver a result larger
398     than 2GB.
399     Note that <function>lo_lseek</function> will fail if the new location
400     pointer would be greater than 2GB.
401</para>
402
403<para>
404     <function>lo_lseek64</function> is new as of <productname>PostgreSQL</productname>
405     9.3.  If this function is run against an older server version, it will
406     fail and return -1.
407</para>
408
409</sect2>
410
411<sect2 id="lo-tell">
412<title>Obtaining the Seek Position of a Large Object</title>
413
414<para>
415     <indexterm><primary>lo_tell</primary></indexterm>
416     To obtain the current read or write location of a large object descriptor,
417     call
418<synopsis>
419int lo_tell(PGconn *conn, int fd);
420</synopsis>
421     If there is an error, the return value is -1.
422</para>
423
424<para>
425     <indexterm><primary>lo_tell64</primary></indexterm>
426     When dealing with large objects that might exceed 2GB in size,
427     instead use
428<synopsis>
429pg_int64 lo_tell64(PGconn *conn, int fd);
430</synopsis>
431     This function has the same behavior
432     as <function>lo_tell</function>, but it can deliver a result larger
433     than 2GB.
434     Note that <function>lo_tell</function> will fail if the current
435     read/write location is greater than 2GB.
436</para>
437
438<para>
439     <function>lo_tell64</function> is new as of <productname>PostgreSQL</productname>
440     9.3.  If this function is run against an older server version, it will
441     fail and return -1.
442</para>
443</sect2>
444
445<sect2 id="lo-truncate">
446<title>Truncating a Large Object</title>
447
448<para>
449     <indexterm><primary>lo_truncate</primary></indexterm>
450     To truncate a large object to a given length, call
451<synopsis>
452int lo_truncate(PGconn *conn, int fd, size_t len);
453</synopsis>
454     This function truncates the large object
455     descriptor <parameter>fd</parameter> to length <parameter>len</parameter>.  The
456     <parameter>fd</parameter> argument must have been returned by a
457     previous <function>lo_open</function>.  If <parameter>len</parameter> is
458     greater than the large object's current length, the large object
459     is extended to the specified length with null bytes ('\0').
460     On success, <function>lo_truncate</function> returns
461     zero.  On error, the return value is -1.
462</para>
463
464<para>
465     The read/write location associated with the descriptor
466     <parameter>fd</parameter> is not changed.
467</para>
468
469<para>
470     Although the <parameter>len</parameter> parameter is declared as
471     <type>size_t</type>, <function>lo_truncate</function> will reject length
472     values larger than <literal>INT_MAX</literal>.
473</para>
474
475<para>
476     <indexterm><primary>lo_truncate64</primary></indexterm>
477     When dealing with large objects that might exceed 2GB in size,
478     instead use
479<synopsis>
480int lo_truncate64(PGconn *conn, int fd, pg_int64 len);
481</synopsis>
482     This function has the same
483     behavior as <function>lo_truncate</function>, but it can accept a
484     <parameter>len</parameter> value exceeding 2GB.
485</para>
486
487<para>
488     <function>lo_truncate</function> is new as of <productname>PostgreSQL</productname>
489     8.3; if this function is run against an older server version, it will
490     fail and return -1.
491</para>
492
493<para>
494     <function>lo_truncate64</function> is new as of <productname>PostgreSQL</productname>
495     9.3; if this function is run against an older server version, it will
496     fail and return -1.
497</para>
498</sect2>
499
500<sect2 id="lo-close">
501<title>Closing a Large Object Descriptor</title>
502
503<para>
504     <indexterm><primary>lo_close</primary></indexterm>
505     A large object descriptor can be closed by calling
506<synopsis>
507int lo_close(PGconn *conn, int fd);
508</synopsis>
509     where <parameter>fd</parameter> is a
510     large object descriptor returned by <function>lo_open</function>.
511     On success, <function>lo_close</function> returns zero.  On
512     error, the return value is -1.
513</para>
514
515<para>
516     Any large  object  descriptors that remain open at the end of a
517     transaction will be closed automatically.
518</para>
519</sect2>
520
521   <sect2 id="lo-unlink">
522    <title>Removing a Large Object</title>
523
524    <para>
525     <indexterm><primary>lo_unlink</primary></indexterm>
526     To remove a large object from the database, call
527<synopsis>
528int lo_unlink(PGconn *conn, Oid lobjId);
529</synopsis>
530     The <parameter>lobjId</parameter> argument specifies the OID of the
531     large object to remove.  Returns 1 if successful, -1 on failure.
532    </para>
533   </sect2>
534
535</sect1>
536
537<sect1 id="lo-funcs">
538<title>Server-Side Functions</title>
539
540  <para>
541   Server-side functions tailored for manipulating large objects from SQL are
542   listed in <xref linkend="lo-funcs-table"/>.
543  </para>
544
545  <table id="lo-funcs-table">
546   <title>SQL-Oriented Large Object Functions</title>
547   <tgroup cols="5">
548    <thead>
549     <row>
550      <entry>Function</entry>
551      <entry>Return Type</entry>
552      <entry>Description</entry>
553      <entry>Example</entry>
554      <entry>Result</entry>
555     </row>
556    </thead>
557
558    <tbody>
559     <row>
560      <entry>
561       <indexterm>
562        <primary>lo_from_bytea</primary>
563       </indexterm>
564       <literal><function>lo_from_bytea(<parameter>loid</parameter> <type>oid</type>, <parameter>string</parameter> <type>bytea</type>)</function></literal>
565      </entry>
566      <entry><type>oid</type></entry>
567      <entry>
568       Create a large object and store data there, returning its OID.
569       Pass <literal>0</literal> to have the system choose an OID.
570      </entry>
571      <entry><literal>lo_from_bytea(0, '\xffffff00')</literal></entry>
572      <entry><literal>24528</literal></entry>
573     </row>
574
575     <row>
576      <entry>
577       <indexterm>
578        <primary>lo_put</primary>
579       </indexterm>
580       <literal><function>lo_put(<parameter>loid</parameter> <type>oid</type>, <parameter>offset</parameter> <type>bigint</type>, <parameter>str</parameter> <type>bytea</type>)</function></literal>
581      </entry>
582      <entry><type>void</type></entry>
583      <entry>
584       Write data at the given offset.
585      </entry>
586      <entry><literal>lo_put(24528, 1, '\xaa')</literal></entry>
587      <entry></entry>
588     </row>
589
590     <row>
591      <entry>
592       <indexterm>
593        <primary>lo_get</primary>
594       </indexterm>
595       <literal><function>lo_get(<parameter>loid</parameter> <type>oid</type> <optional>, <parameter>from</parameter> <type>bigint</type>, <parameter>for</parameter> <type>int</type></optional>)</function></literal>
596      </entry>
597      <entry><type>bytea</type></entry>
598      <entry>
599       Extract contents or a substring thereof.
600      </entry>
601      <entry><literal>lo_get(24528, 0, 3)</literal></entry>
602      <entry><literal>\xffaaff</literal></entry>
603     </row>
604
605    </tbody>
606   </tgroup>
607  </table>
608
609  <para>
610   There are additional server-side functions corresponding to each of the
611   client-side functions described earlier; indeed, for the most part the
612   client-side functions are simply interfaces to the equivalent server-side
613   functions.  The ones just as convenient to call via SQL commands are
614   <function>lo_creat</function><indexterm><primary>lo_creat</primary></indexterm>,
615   <function>lo_create</function>,
616   <function>lo_unlink</function><indexterm><primary>lo_unlink</primary></indexterm>,
617   <function>lo_import</function><indexterm><primary>lo_import</primary></indexterm>, and
618   <function>lo_export</function><indexterm><primary>lo_export</primary></indexterm>.
619   Here are examples of their use:
620
621<programlisting>
622CREATE TABLE image (
623    name            text,
624    raster          oid
625);
626
627SELECT lo_creat(-1);       -- returns OID of new, empty large object
628
629SELECT lo_create(43213);   -- attempts to create large object with OID 43213
630
631SELECT lo_unlink(173454);  -- deletes large object with OID 173454
632
633INSERT INTO image (name, raster)
634    VALUES ('beautiful image', lo_import('/etc/motd'));
635
636INSERT INTO image (name, raster)  -- same as above, but specify OID to use
637    VALUES ('beautiful image', lo_import('/etc/motd', 68583));
638
639SELECT lo_export(image.raster, '/tmp/motd') FROM image
640    WHERE name = 'beautiful image';
641</programlisting>
642  </para>
643
644  <para>
645    The server-side <function>lo_import</function> and
646    <function>lo_export</function> functions behave considerably differently
647    from their client-side analogs.  These two functions read and write files
648    in the server's file system, using the permissions of the database's
649    owning user.  Therefore, by default their use is restricted to superusers.
650    In contrast, the client-side import and export functions read and write
651    files in the client's file system, using the permissions of the client
652    program.  The client-side functions do not require any database
653    privileges, except the privilege to read or write the large object in
654    question.
655  </para>
656
657  <caution>
658   <para>
659    It is possible to <xref linkend="sql-grant"/> use of the
660    server-side <function>lo_import</function>
661    and <function>lo_export</function> functions to non-superusers, but
662    careful consideration of the security implications is required.  A
663    malicious user of such privileges could easily parlay them into becoming
664    superuser (for example by rewriting server configuration files), or could
665    attack the rest of the server's file system without bothering to obtain
666    database superuser privileges as such.  <emphasis>Access to roles having
667    such privilege must therefore be guarded just as carefully as access to
668    superuser roles.</emphasis>  Nonetheless, if use of
669    server-side <function>lo_import</function>
670    or <function>lo_export</function> is needed for some routine task, it's
671    safer to use a role with such privileges than one with full superuser
672    privileges, as that helps to reduce the risk of damage from accidental
673    errors.
674   </para>
675  </caution>
676
677  <para>
678    The functionality of <function>lo_read</function> and
679    <function>lo_write</function> is also available via server-side calls,
680    but the names of the server-side functions differ from the client side
681    interfaces in that they do not contain underscores.  You must call
682    these functions as <function>loread</function> and <function>lowrite</function>.
683  </para>
684
685</sect1>
686
687<sect1 id="lo-examplesect">
688<title>Example Program</title>
689
690<para>
691     <xref linkend="lo-example"/> is a sample program which shows how the large object
692     interface
693     in <application>libpq</application> can be used.  Parts of the program are
694     commented out but are left in the source for  the  reader's
695     benefit.  This program can also be found in
696     <filename>src/test/examples/testlo.c</filename> in the source distribution.
697</para>
698
699  <example id="lo-example">
700   <title>Large Objects with <application>libpq</application> Example Program</title>
701<programlisting><![CDATA[
702/*-------------------------------------------------------------------------
703 *
704 * testlo.c
705 *    test using large objects with libpq
706 *
707 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
708 * Portions Copyright (c) 1994, Regents of the University of California
709 *
710 *
711 * IDENTIFICATION
712 *    src/test/examples/testlo.c
713 *
714 *-------------------------------------------------------------------------
715 */
716#include <stdio.h>
717#include <stdlib.h>
718
719#include <sys/types.h>
720#include <sys/stat.h>
721#include <fcntl.h>
722#include <unistd.h>
723
724#include "libpq-fe.h"
725#include "libpq/libpq-fs.h"
726
727#define BUFSIZE         1024
728
729/*
730 * importFile -
731 *    import file "in_filename" into database as large object "lobjOid"
732 *
733 */
734static Oid
735importFile(PGconn *conn, char *filename)
736{
737    Oid         lobjId;
738    int         lobj_fd;
739    char        buf[BUFSIZE];
740    int         nbytes,
741                tmp;
742    int         fd;
743
744    /*
745     * open the file to be read in
746     */
747    fd = open(filename, O_RDONLY, 0666);
748    if (fd < 0)
749    {                           /* error */
750        fprintf(stderr, "cannot open unix file\"%s\"\n", filename);
751    }
752
753    /*
754     * create the large object
755     */
756    lobjId = lo_creat(conn, INV_READ | INV_WRITE);
757    if (lobjId == 0)
758        fprintf(stderr, "cannot create large object");
759
760    lobj_fd = lo_open(conn, lobjId, INV_WRITE);
761
762    /*
763     * read in from the Unix file and write to the inversion file
764     */
765    while ((nbytes = read(fd, buf, BUFSIZE)) > 0)
766    {
767        tmp = lo_write(conn, lobj_fd, buf, nbytes);
768        if (tmp < nbytes)
769            fprintf(stderr, "error while reading \"%s\"", filename);
770    }
771
772    close(fd);
773    lo_close(conn, lobj_fd);
774
775    return lobjId;
776}
777
778static void
779pickout(PGconn *conn, Oid lobjId, int start, int len)
780{
781    int         lobj_fd;
782    char       *buf;
783    int         nbytes;
784    int         nread;
785
786    lobj_fd = lo_open(conn, lobjId, INV_READ);
787    if (lobj_fd < 0)
788        fprintf(stderr, "cannot open large object %u", lobjId);
789
790    lo_lseek(conn, lobj_fd, start, SEEK_SET);
791    buf = malloc(len + 1);
792
793    nread = 0;
794    while (len - nread > 0)
795    {
796        nbytes = lo_read(conn, lobj_fd, buf, len - nread);
797        buf[nbytes] = '\0';
798        fprintf(stderr, ">>> %s", buf);
799        nread += nbytes;
800        if (nbytes <= 0)
801            break;              /* no more data? */
802    }
803    free(buf);
804    fprintf(stderr, "\n");
805    lo_close(conn, lobj_fd);
806}
807
808static void
809overwrite(PGconn *conn, Oid lobjId, int start, int len)
810{
811    int         lobj_fd;
812    char       *buf;
813    int         nbytes;
814    int         nwritten;
815    int         i;
816
817    lobj_fd = lo_open(conn, lobjId, INV_WRITE);
818    if (lobj_fd < 0)
819        fprintf(stderr, "cannot open large object %u", lobjId);
820
821    lo_lseek(conn, lobj_fd, start, SEEK_SET);
822    buf = malloc(len + 1);
823
824    for (i = 0; i < len; i++)
825        buf[i] = 'X';
826    buf[i] = '\0';
827
828    nwritten = 0;
829    while (len - nwritten > 0)
830    {
831        nbytes = lo_write(conn, lobj_fd, buf + nwritten, len - nwritten);
832        nwritten += nbytes;
833        if (nbytes <= 0)
834        {
835            fprintf(stderr, "\nWRITE FAILED!\n");
836            break;
837        }
838    }
839    free(buf);
840    fprintf(stderr, "\n");
841    lo_close(conn, lobj_fd);
842}
843
844
845/*
846 * exportFile -
847 *    export large object "lobjOid" to file "out_filename"
848 *
849 */
850static void
851exportFile(PGconn *conn, Oid lobjId, char *filename)
852{
853    int         lobj_fd;
854    char        buf[BUFSIZE];
855    int         nbytes,
856                tmp;
857    int         fd;
858
859    /*
860     * open the large object
861     */
862    lobj_fd = lo_open(conn, lobjId, INV_READ);
863    if (lobj_fd < 0)
864        fprintf(stderr, "cannot open large object %u", lobjId);
865
866    /*
867     * open the file to be written to
868     */
869    fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0666);
870    if (fd < 0)
871    {                           /* error */
872        fprintf(stderr, "cannot open unix file\"%s\"",
873                filename);
874    }
875
876    /*
877     * read in from the inversion file and write to the Unix file
878     */
879    while ((nbytes = lo_read(conn, lobj_fd, buf, BUFSIZE)) > 0)
880    {
881        tmp = write(fd, buf, nbytes);
882        if (tmp < nbytes)
883        {
884            fprintf(stderr, "error while writing \"%s\"",
885                    filename);
886        }
887    }
888
889    lo_close(conn, lobj_fd);
890    close(fd);
891
892    return;
893}
894
895static void
896exit_nicely(PGconn *conn)
897{
898    PQfinish(conn);
899    exit(1);
900}
901
902int
903main(int argc, char **argv)
904{
905    char       *in_filename,
906               *out_filename;
907    char       *database;
908    Oid         lobjOid;
909    PGconn     *conn;
910    PGresult   *res;
911
912    if (argc != 4)
913    {
914        fprintf(stderr, "Usage: %s database_name in_filename out_filename\n",
915                argv[0]);
916        exit(1);
917    }
918
919    database = argv[1];
920    in_filename = argv[2];
921    out_filename = argv[3];
922
923    /*
924     * set up the connection
925     */
926    conn = PQsetdb(NULL, NULL, NULL, NULL, database);
927
928    /* check to see that the backend connection was successfully made */
929    if (PQstatus(conn) != CONNECTION_OK)
930    {
931        fprintf(stderr, "Connection to database failed: %s",
932                PQerrorMessage(conn));
933        exit_nicely(conn);
934    }
935
936    /* Set always-secure search path, so malicious users can't take control. */
937    res = PQexec(conn,
938                 "SELECT pg_catalog.set_config('search_path', '', false)");
939    if (PQresultStatus(res) != PGRES_TUPLES_OK)
940    {
941        fprintf(stderr, "SET failed: %s", PQerrorMessage(conn));
942        PQclear(res);
943        exit_nicely(conn);
944    }
945    PQclear(res);
946
947    res = PQexec(conn, "begin");
948    PQclear(res);
949    printf("importing file \"%s\" ...\n", in_filename);
950/*  lobjOid = importFile(conn, in_filename); */
951    lobjOid = lo_import(conn, in_filename);
952    if (lobjOid == 0)
953        fprintf(stderr, "%s\n", PQerrorMessage(conn));
954    else
955    {
956        printf("\tas large object %u.\n", lobjOid);
957
958        printf("picking out bytes 1000-2000 of the large object\n");
959        pickout(conn, lobjOid, 1000, 1000);
960
961        printf("overwriting bytes 1000-2000 of the large object with X's\n");
962        overwrite(conn, lobjOid, 1000, 1000);
963
964        printf("exporting large object to file \"%s\" ...\n", out_filename);
965/*      exportFile(conn, lobjOid, out_filename); */
966        if (lo_export(conn, lobjOid, out_filename) < 0)
967            fprintf(stderr, "%s\n", PQerrorMessage(conn));
968    }
969
970    res = PQexec(conn, "end");
971    PQclear(res);
972    PQfinish(conn);
973    return 0;
974}
975]]>
976</programlisting>
977</example>
978
979</sect1>
980</chapter>
981