You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lobj.sgml 33KB

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