]> granicus.if.org Git - postgresql/blob - doc/src/sgml/ref/copy.sgml
e5f45f4a8af2e335a98c4de34b85cd43e829809a
[postgresql] / doc / src / sgml / ref / copy.sgml
1 <!--
2 doc/src/sgml/ref/copy.sgml
3 PostgreSQL documentation
4 -->
5
6
7 <refentry id="SQL-COPY">
8  <refmeta>
9   <refentrytitle>COPY</refentrytitle>
10   <manvolnum>7</manvolnum>
11   <refmiscinfo>SQL - Language Statements</refmiscinfo>
12  </refmeta>
13
14  <refnamediv>
15   <refname>COPY</refname>
16   <refpurpose>copy data between a file and a table</refpurpose>
17  </refnamediv>
18
19  <indexterm zone="sql-copy">
20   <primary>COPY</primary>
21  </indexterm>
22
23  <refsynopsisdiv>
24 <synopsis>
25 COPY <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ]
26     FROM { '<replaceable class="parameter">filename</replaceable>' | STDIN }
27     [ [ WITH ] ( <replaceable class="parameter">option</replaceable> [, ...] ) ]
28
29 COPY { <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] | ( <replaceable class="parameter">query</replaceable> ) }
30     TO { '<replaceable class="parameter">filename</replaceable>' | STDOUT }
31     [ [ WITH ] ( <replaceable class="parameter">option</replaceable> [, ...] ) ]
32
33 <phrase>where <replaceable class="parameter">option</replaceable> can be one of:</phrase>
34
35     FORMAT <replaceable class="parameter">format_name</replaceable>
36     OIDS [ <replaceable class="parameter">boolean</replaceable> ]
37     DELIMITER '<replaceable class="parameter">delimiter_character</replaceable>'
38     NULL '<replaceable class="parameter">null_string</replaceable>'
39     HEADER [ <replaceable class="parameter">boolean</replaceable> ]
40     QUOTE '<replaceable class="parameter">quote_character</replaceable>'
41     ESCAPE '<replaceable class="parameter">escape_character</replaceable>'
42     FORCE_QUOTE { ( <replaceable class="parameter">column_name</replaceable> [, ...] ) | * }
43     FORCE_NOT_NULL ( <replaceable class="parameter">column_name</replaceable> [, ...] ) |
44     ENCODING '<replaceable class="parameter">encoding_name</replaceable>'
45 </synopsis>
46  </refsynopsisdiv>
47
48  <refsect1>
49   <title>Description</title>
50
51   <para>
52    <command>COPY</command> moves data between
53    <productname>PostgreSQL</productname> tables and standard file-system
54    files. <command>COPY TO</command> copies the contents of a table
55    <emphasis>to</> a file, while <command>COPY FROM</command> copies
56    data <emphasis>from</> a file to a table (appending the data to
57    whatever is in the table already).  <command>COPY TO</command>
58    can also copy the results of a <command>SELECT</> query.
59   </para>
60
61   <para>
62    If a list of columns is specified, <command>COPY</command> will
63    only copy the data in the specified columns to or from the file.
64    If there are any columns in the table that are not in the column list,
65    <command>COPY FROM</command> will insert the default values for
66    those columns.
67   </para>
68
69   <para>
70    <command>COPY</command> with a file name instructs the
71    <productname>PostgreSQL</productname> server to directly read from
72    or write to a file. The file must be accessible to the server and
73    the name must be specified from the viewpoint of the server. When
74    <literal>STDIN</literal> or <literal>STDOUT</literal> is
75    specified, data is transmitted via the connection between the
76    client and the server.
77   </para>
78  </refsect1>
79
80  <refsect1>
81   <title>Parameters</title>
82
83   <variablelist>
84    <varlistentry>
85     <term><replaceable class="parameter">table_name</replaceable></term>
86     <listitem>
87      <para>
88       The name (optionally schema-qualified) of an existing table.
89      </para>
90     </listitem>
91    </varlistentry>
92
93    <varlistentry>
94     <term><replaceable class="parameter">column_name</replaceable></term>
95      <listitem>
96      <para>
97       An optional list of columns to be copied.  If no column list is
98       specified, all columns of the table will be copied.
99      </para>
100     </listitem>
101    </varlistentry>
102
103    <varlistentry>
104     <term><replaceable class="parameter">query</replaceable></term>
105     <listitem>
106      <para>
107       A <xref linkend="sql-select"> or
108       <xref linkend="sql-values"> command
109       whose results are to be copied.
110       Note that parentheses are required around the query.
111      </para>
112     </listitem>
113    </varlistentry>
114
115    <varlistentry>
116     <term><replaceable class="parameter">filename</replaceable></term>
117     <listitem>
118      <para>
119       The absolute path name of the input or output file.  Windows users
120       might need to use an <literal>E''</> string and double any backslashes
121       used in the path name.
122      </para>
123     </listitem>
124    </varlistentry>
125
126    <varlistentry>
127     <term><literal>STDIN</literal></term>
128     <listitem>
129      <para>
130       Specifies that input comes from the client application.
131      </para>
132     </listitem>
133    </varlistentry>
134
135    <varlistentry>
136     <term><literal>STDOUT</literal></term>
137     <listitem>
138      <para>
139       Specifies that output goes to the client application.
140      </para>
141     </listitem>
142    </varlistentry>
143
144    <varlistentry>
145     <term><replaceable class="parameter">boolean</replaceable></term>
146     <listitem>
147      <para>
148       Specifies whether the selected option should be turned on or off.
149       You can write <literal>TRUE</literal>, <literal>ON</>, or
150       <literal>1</literal> to enable the option, and <literal>FALSE</literal>,
151       <literal>OFF</>, or <literal>0</literal> to disable it.  The
152       <replaceable class="parameter">boolean</replaceable> value can also
153       be omitted, in which case <literal>TRUE</literal> is assumed.
154      </para>
155     </listitem>
156    </varlistentry>
157
158    <varlistentry>
159     <term><literal>FORMAT</literal></term>
160     <listitem>
161      <para>
162       Selects the data format to be read or written:
163       <literal>text</>,
164       <literal>csv</> (Comma Separated Values),
165       or <literal>binary</>.
166       The default is <literal>text</>.
167      </para>
168     </listitem>
169    </varlistentry>
170
171    <varlistentry>
172     <term><literal>OIDS</literal></term>
173     <listitem>
174      <para>
175       Specifies copying the OID for each row.  (An error is raised if
176       <literal>OIDS</literal> is specified for a table that does not
177       have OIDs, or in the case of copying a <replaceable
178       class="parameter">query</replaceable>.)
179      </para>
180     </listitem>
181    </varlistentry>
182
183    <varlistentry>
184     <term><literal>DELIMITER</literal></term>
185     <listitem>
186      <para>
187       Specifies the character that separates columns within each row
188       (line) of the file.  The default is a tab character in text format,
189       a comma in <literal>CSV</> format.
190       This must be a single one-byte character.
191       This option is not allowed when using <literal>binary</> format.
192      </para>
193     </listitem>
194    </varlistentry>
195
196    <varlistentry>
197     <term><literal>NULL</literal></term>
198     <listitem>
199      <para>
200       Specifies the string that represents a null value. The default is
201       <literal>\N</literal> (backslash-N) in text format, and an unquoted empty
202       string in <literal>CSV</> format. You might prefer an
203       empty string even in text format for cases where you don't want to
204       distinguish nulls from empty strings.
205       This option is not allowed when using <literal>binary</> format.
206      </para>
207
208      <note>
209       <para>
210        When using <command>COPY FROM</command>, any data item that matches
211        this string will be stored as a null value, so you should make
212        sure that you use the same string as you used with
213        <command>COPY TO</command>.
214       </para>
215      </note>
216
217     </listitem>
218    </varlistentry>
219
220    <varlistentry>
221     <term><literal>HEADER</literal></term>
222     <listitem>
223      <para>
224       Specifies that the file contains a header line with the names of each
225       column in the file.  On output, the first line contains the column
226       names from the table, and on input, the first line is ignored.
227       This option is allowed only when using <literal>CSV</> format.
228      </para>
229     </listitem>
230    </varlistentry>
231
232    <varlistentry>
233     <term><literal>QUOTE</literal></term>
234     <listitem>
235      <para>
236       Specifies the quoting character to be used when a data value is quoted.
237       The default is double-quote.
238       This must be a single one-byte character.
239       This option is allowed only when using <literal>CSV</> format.
240      </para>
241     </listitem>
242    </varlistentry>
243
244    <varlistentry>
245     <term><literal>ESCAPE</literal></term>
246     <listitem>
247      <para>
248       Specifies the character that should appear before a
249       data character that matches the <literal>QUOTE</> value.
250       The default is the same as the <literal>QUOTE</> value (so that
251       the quoting character is doubled if it appears in the data).
252       This must be a single one-byte character.
253       This option is allowed only when using <literal>CSV</> format.
254      </para>
255     </listitem>
256    </varlistentry>
257
258    <varlistentry>
259     <term><literal>FORCE_QUOTE</></term>
260     <listitem>
261      <para>
262       Forces quoting to be
263       used for all non-<literal>NULL</> values in each specified column.
264       <literal>NULL</> output is never quoted. If <literal>*</> is specified,
265       non-<literal>NULL</> values will be quoted in all columns.
266       This option is allowed only in <command>COPY TO</>, and only when
267       using <literal>CSV</> format.
268      </para>
269     </listitem>
270    </varlistentry>
271
272    <varlistentry>
273     <term><literal>FORCE_NOT_NULL</></term>
274     <listitem>
275      <para>
276       Do not match the specified columns' values against the null string.
277       In the default case where the null string is empty, this means that
278       empty values will be read as zero-length strings rather than nulls,
279       even when they are not quoted.
280       This option is allowed only in <command>COPY FROM</>, and only when
281       using <literal>CSV</> format.
282      </para>
283     </listitem>
284    </varlistentry>
285
286    <varlistentry>
287     <term><literal>ENCODING</></term>
288     <listitem>
289      <para>
290       Specifies that the file is encoded in the <replaceable
291       class="parameter">encoding_name</replaceable>.  If this option is
292       omitted, the current client encoding is used. See the Notes below
293       for more details.
294      </para>
295     </listitem>
296    </varlistentry>
297
298   </variablelist>
299  </refsect1>
300
301  <refsect1>
302   <title>Outputs</title>
303
304   <para>
305    On successful completion, a <command>COPY</> command returns a command
306    tag of the form
307 <screen>
308 COPY <replaceable class="parameter">count</replaceable>
309 </screen>
310    The <replaceable class="parameter">count</replaceable> is the number
311    of rows copied.
312   </para>
313  </refsect1>
314
315  <refsect1>
316   <title>Notes</title>
317
318    <para>
319     <command>COPY</command> can only be used with plain tables, not
320     with views.  However, you can write <literal>COPY (SELECT * FROM
321     <replaceable class="parameter">viewname</replaceable>) TO ...</literal>.
322    </para>
323
324    <para>
325     <command>COPY</command> only deals with the specific table named;
326     it does not copy data to or from child tables.  Thus for example
327     <literal>COPY <replaceable class="parameter">table</> TO</literal>
328     shows the same data as <literal>SELECT * FROM ONLY <replaceable
329     class="parameter">table</></literal>.  But <literal>COPY
330     (SELECT * FROM <replaceable class="parameter">table</>) TO ...</literal>
331     can be used to dump all of the data in an inheritance hierarchy.
332    </para>
333
334    <para>
335     You must have select privilege on the table
336     whose values are read by <command>COPY TO</command>, and
337     insert privilege on the table into which values
338     are inserted by <command>COPY FROM</command>.  It is sufficient
339     to have column privileges on the column(s) listed in the command.
340    </para>
341
342    <para>
343     Files named in a <command>COPY</command> command are read or written
344     directly by the server, not by the client application. Therefore,
345     they must reside on or be accessible to the database server machine,
346     not the client. They must be accessible to and readable or writable
347     by the <productname>PostgreSQL</productname> user (the user ID the
348     server runs as), not the client. <command>COPY</command> naming a
349     file is only allowed to database superusers, since it allows reading
350     or writing any file that the server has privileges to access.
351    </para>
352
353    <para>
354     Do not confuse <command>COPY</command> with the
355     <application>psql</application> instruction
356     <command><link linkend="APP-PSQL-meta-commands-copy">\copy</link></command>. <command>\copy</command> invokes
357     <command>COPY FROM STDIN</command> or <command>COPY TO
358     STDOUT</command>, and then fetches/stores the data in a file
359     accessible to the <application>psql</application> client. Thus,
360     file accessibility and access rights depend on the client rather
361     than the server when <command>\copy</command> is used.
362    </para>
363
364    <para>
365     It is recommended that the file name used in <command>COPY</command>
366     always be specified as an absolute path. This is enforced by the
367     server in the case of <command>COPY TO</command>, but for
368     <command>COPY FROM</command> you do have the option of reading from
369     a file specified by a relative path. The path will be interpreted
370     relative to the working directory of the server process (normally
371     the cluster's data directory), not the client's working directory.
372    </para>
373
374    <para>
375     <command>COPY FROM</command> will invoke any triggers and check
376     constraints on the destination table. However, it will not invoke rules.
377    </para>
378
379    <para>
380     <command>COPY</command> input and output is affected by
381     <varname>DateStyle</varname>. To ensure portability to other
382     <productname>PostgreSQL</productname> installations that might use
383     non-default <varname>DateStyle</varname> settings,
384     <varname>DateStyle</varname> should be set to <literal>ISO</> before
385     using <command>COPY TO</>.  It is also a good idea to avoid dumping
386     data with <varname>IntervalStyle</varname> set to
387     <literal>sql_standard</>, because negative interval values might be
388     misinterpreted by a server that has a different setting for
389     <varname>IntervalStyle</varname>.
390    </para>
391
392    <para>
393     Input data is interpreted according to <literal>ENCODING</literal>
394     option or the current client encoding, and output data is encoded
395     in <literal>ENCODING</literal> or the current client encoding, even
396     if the data does not pass through the client but is read from or
397     written to a file directly by the server.
398    </para>
399
400    <para>
401     <command>COPY</command> stops operation at the first error. This
402     should not lead to problems in the event of a <command>COPY
403     TO</command>, but the target table will already have received
404     earlier rows in a <command>COPY FROM</command>. These rows will not
405     be visible or accessible, but they still occupy disk space. This might
406     amount to a considerable amount of wasted disk space if the failure
407     happened well into a large copy operation. You might wish to invoke
408     <command>VACUUM</command> to recover the wasted space.
409    </para>
410
411  </refsect1>
412
413  <refsect1>
414   <title>File Formats</title>
415
416   <refsect2>
417    <title>Text Format</title>
418
419    <para>
420     When the <literal>text</> format is used,
421     the data read or written is a text file with one line per table row.
422     Columns in a row are separated by the delimiter character.
423     The column values themselves are strings generated by the
424     output function, or acceptable to the input function, of each
425     attribute's data type.  The specified null string is used in
426     place of columns that are null.
427     <command>COPY FROM</command> will raise an error if any line of the
428     input file contains more or fewer columns than are expected.
429     If <literal>OIDS</literal> is specified, the OID is read or written as the first column,
430     preceding the user data columns.
431    </para>
432
433    <para>
434     End of data can be represented by a single line containing just
435     backslash-period (<literal>\.</>).  An end-of-data marker is
436     not necessary when reading from a file, since the end of file
437     serves perfectly well; it is needed only when copying data to or from
438     client applications using pre-3.0 client protocol.
439    </para>
440
441    <para>
442     Backslash characters (<literal>\</>) can be used in the
443     <command>COPY</command> data to quote data characters that might
444     otherwise be taken as row or column delimiters. In particular, the
445     following characters <emphasis>must</> be preceded by a backslash if
446     they appear as part of a column value: backslash itself,
447     newline, carriage return, and the current delimiter character.
448    </para>
449
450    <para>
451     The specified null string is sent by <command>COPY TO</command> without
452     adding any backslashes; conversely, <command>COPY FROM</command> matches
453     the input against the null string before removing backslashes.  Therefore,
454     a null string such as <literal>\N</literal> cannot be confused with
455     the actual data value <literal>\N</literal> (which would be represented
456     as <literal>\\N</literal>).
457    </para>
458
459    <para>
460     The following special backslash sequences are recognized by
461     <command>COPY FROM</command>:
462
463    <informaltable>
464     <tgroup cols="2">
465      <thead>
466       <row>
467        <entry>Sequence</entry>
468        <entry>Represents</entry>
469       </row>
470      </thead>
471
472      <tbody>
473       <row>
474        <entry><literal>\b</></entry>
475        <entry>Backspace (ASCII 8)</entry>
476       </row>
477       <row>
478        <entry><literal>\f</></entry>
479        <entry>Form feed (ASCII 12)</entry>
480       </row>
481       <row>
482        <entry><literal>\n</></entry>
483        <entry>Newline (ASCII 10)</entry>
484       </row>
485       <row>
486        <entry><literal>\r</></entry>
487        <entry>Carriage return (ASCII 13)</entry>
488       </row>
489       <row>
490        <entry><literal>\t</></entry>
491        <entry>Tab (ASCII 9)</entry>
492       </row>
493       <row>
494        <entry><literal>\v</></entry>
495        <entry>Vertical tab (ASCII 11)</entry>
496       </row>
497       <row>
498        <entry><literal>\</><replaceable>digits</></entry>
499        <entry>Backslash followed by one to three octal digits specifies
500        the character with that numeric code</entry>
501       </row>
502       <row>
503        <entry><literal>\x</><replaceable>digits</></entry>
504        <entry>Backslash <literal>x</> followed by one or two hex digits specifies
505        the character with that numeric code</entry>
506       </row>
507      </tbody>
508     </tgroup>
509    </informaltable>
510
511     Presently, <command>COPY TO</command> will never emit an octal or
512     hex-digits backslash sequence, but it does use the other sequences
513     listed above for those control characters.
514    </para>
515
516    <para>
517     Any other backslashed character that is not mentioned in the above table
518     will be taken to represent itself.  However, beware of adding backslashes
519     unnecessarily, since that might accidentally produce a string matching the
520     end-of-data marker (<literal>\.</>) or the null string (<literal>\N</> by
521     default).  These strings will be recognized before any other backslash
522     processing is done.
523    </para>
524
525    <para>
526     It is strongly recommended that applications generating <command>COPY</command> data convert
527     data newlines and carriage returns to the <literal>\n</> and
528     <literal>\r</> sequences respectively.  At present it is
529     possible to represent a data carriage return by a backslash and carriage
530     return, and to represent a data newline by a backslash and newline.
531     However, these representations might not be accepted in future releases.
532     They are also highly vulnerable to corruption if the <command>COPY</command> file is
533     transferred across different machines (for example, from Unix to Windows
534     or vice versa).
535    </para>
536
537    <para>
538     <command>COPY TO</command> will terminate each row with a Unix-style
539     newline (<quote><literal>\n</></>).  Servers running on Microsoft Windows instead
540     output carriage return/newline (<quote><literal>\r\n</></>), but only for
541     <command>COPY</> to a server file; for consistency across platforms,
542     <command>COPY TO STDOUT</> always sends <quote><literal>\n</></>
543     regardless of server platform.
544     <command>COPY FROM</command> can handle lines ending with newlines,
545     carriage returns, or carriage return/newlines.  To reduce the risk of
546     error due to un-backslashed newlines or carriage returns that were
547     meant as data, <command>COPY FROM</command> will complain if the line
548     endings in the input are not all alike.
549    </para>
550   </refsect2>
551
552   <refsect2>
553    <title>CSV Format</title>
554
555    <para>
556     This format option is used for importing and exporting the Comma
557     Separated Value (<literal>CSV</>) file format used by many other
558     programs, such as spreadsheets. Instead of the escaping rules used by
559     <productname>PostgreSQL</productname>'s standard text format, it
560     produces and recognizes the common CSV escaping mechanism.
561    </para>
562
563    <para>
564     The values in each record are separated by the <literal>DELIMITER</>
565     character. If the value contains the delimiter character, the
566     <literal>QUOTE</> character, the <literal>NULL</> string, a carriage
567     return, or line feed character, then the whole value is prefixed and
568     suffixed by the <literal>QUOTE</> character, and any occurrence
569     within the value of a <literal>QUOTE</> character or the
570     <literal>ESCAPE</> character is preceded by the escape character.
571     You can also use <literal>FORCE_QUOTE</> to force quotes when outputting
572     non-<literal>NULL</> values in specific columns.
573    </para>
574
575    <para>
576     The <literal>CSV</> format has no standard way to distinguish a
577     <literal>NULL</> value from an empty string.
578     <productname>PostgreSQL</>'s <command>COPY</> handles this by quoting.
579     A <literal>NULL</> is output as the <literal>NULL</> parameter string
580     and is not quoted, while a non-<literal>NULL</> value matching the
581     <literal>NULL</> parameter string is quoted.  For example, with the
582     default settings, a <literal>NULL</> is written as an unquoted empty
583     string, while an empty string data value is written with double quotes
584     (<literal>""</>). Reading values follows similar rules. You can
585     use <literal>FORCE_NOT_NULL</> to prevent <literal>NULL</> input
586     comparisons for specific columns.
587    </para>
588
589    <para>
590     Because backslash is not a special character in the <literal>CSV</>
591     format, <literal>\.</>, the end-of-data marker, could also appear
592     as a data value.  To avoid any misinterpretation, a <literal>\.</>
593     data value appearing as a lone entry on a line is automatically
594     quoted on output, and on input, if quoted, is not interpreted as the
595     end-of-data marker.  If you are loading a file created by another
596     application that has a single unquoted column and might have a
597     value of <literal>\.</>, you might need to quote that value in the
598     input file.
599    </para>
600
601    <note>
602     <para>
603      In <literal>CSV</> format, all characters are significant. A quoted value
604      surrounded by white space, or any characters other than
605      <literal>DELIMITER</>, will include those characters. This can cause
606      errors if you import data from a system that pads <literal>CSV</>
607      lines with white space out to some fixed width. If such a situation
608      arises you might need to preprocess the <literal>CSV</> file to remove
609      the trailing white space, before importing the data into
610      <productname>PostgreSQL</>.
611     </para>
612    </note>
613
614    <note>
615     <para>
616      CSV format will both recognize and produce CSV files with quoted
617      values containing embedded carriage returns and line feeds. Thus
618      the files are not strictly one line per table row like text-format
619      files.
620     </para>
621    </note>
622
623    <note>
624     <para>
625      Many programs produce strange and occasionally perverse CSV files,
626      so the file format is more a convention than a standard. Thus you
627      might encounter some files that cannot be imported using this
628      mechanism, and <command>COPY</> might produce files that other
629      programs cannot process.
630     </para>
631    </note>
632
633   </refsect2>
634
635   <refsect2>
636    <title>Binary Format</title>
637
638    <para>
639     The <literal>binary</literal> format option causes all data to be
640     stored/read as binary format rather than as text.  It is
641     somewhat faster than the text and <literal>CSV</> formats,
642     but a binary-format file is less portable across machine architectures and
643     <productname>PostgreSQL</productname> versions.
644     Also, the binary format is very data type specific; for example
645     it will not work to output binary data from a <type>smallint</> column
646     and read it into an <type>integer</> column, even though that would work
647     fine in text format.
648    </para>
649
650    <para>
651     The <literal>binary</> file format consists
652     of a file header, zero or more tuples containing the row data, and
653     a file trailer.  Headers and data are in network byte order.
654    </para>
655
656    <note>
657     <para>
658      <productname>PostgreSQL</productname> releases before 7.4 used a
659      different binary file format.
660     </para>
661    </note>
662
663    <refsect3>
664     <title>File Header</title>
665
666     <para>
667      The file header consists of 15 bytes of fixed fields, followed
668      by a variable-length header extension area.  The fixed fields are:
669
670     <variablelist>
671      <varlistentry>
672       <term>Signature</term>
673       <listitem>
674        <para>
675 11-byte sequence <literal>PGCOPY\n\377\r\n\0</> &mdash; note that the zero byte
676 is a required part of the signature.  (The signature is designed to allow
677 easy identification of files that have been munged by a non-8-bit-clean
678 transfer.  This signature will be changed by end-of-line-translation
679 filters, dropped zero bytes, dropped high bits, or parity changes.)
680        </para>
681       </listitem>
682      </varlistentry>
683
684      <varlistentry>
685       <term>Flags field</term>
686       <listitem>
687        <para>
688 32-bit integer bit mask to denote important aspects of the file format. Bits
689 are numbered from 0 (<acronym>LSB</>) to 31 (<acronym>MSB</>).  Note that
690 this field is stored in network byte order (most significant byte first),
691 as are all the integer fields used in the file format.  Bits
692 16-31 are reserved to denote critical file format issues; a reader
693 should abort if it finds an unexpected bit set in this range. Bits 0-15
694 are reserved to signal backwards-compatible format issues; a reader
695 should simply ignore any unexpected bits set in this range. Currently
696 only one flag bit is defined, and the rest must be zero:
697         <variablelist>
698          <varlistentry>
699           <term>Bit 16</term>
700           <listitem>
701            <para>
702             if 1, OIDs are included in the data; if 0, not
703            </para>
704           </listitem>
705          </varlistentry>
706         </variablelist></para>
707       </listitem>
708      </varlistentry>
709
710      <varlistentry>
711       <term>Header extension area length</term>
712       <listitem>
713        <para>
714 32-bit integer, length in bytes of remainder of header, not including self.
715 Currently, this is zero, and the first tuple follows
716 immediately.  Future changes to the format might allow additional data
717 to be present in the header.  A reader should silently skip over any header
718 extension data it does not know what to do with.
719        </para>
720       </listitem>
721      </varlistentry>
722     </variablelist>
723     </para>
724
725     <para>
726 The header extension area is envisioned to contain a sequence of
727 self-identifying chunks.  The flags field is not intended to tell readers
728 what is in the extension area.  Specific design of header extension contents
729 is left for a later release.
730     </para>
731
732     <para>
733      This design allows for both backwards-compatible header additions (add
734      header extension chunks, or set low-order flag bits) and
735      non-backwards-compatible changes (set high-order flag bits to signal such
736      changes, and add supporting data to the extension area if needed).
737     </para>
738    </refsect3>
739
740    <refsect3>
741     <title>Tuples</title>
742     <para>
743 Each tuple begins with a 16-bit integer count of the number of fields in the
744 tuple.  (Presently, all tuples in a table will have the same count, but that
745 might not always be true.)  Then, repeated for each field in the tuple, there
746 is a 32-bit length word followed by that many bytes of field data.  (The
747 length word does not include itself, and can be zero.)  As a special case,
748 -1 indicates a NULL field value.  No value bytes follow in the NULL case.
749     </para>
750
751     <para>
752 There is no alignment padding or any other extra data between fields.
753     </para>
754
755     <para>
756 Presently, all data values in a binary-format file are
757 assumed to be in binary format (format code one).  It is anticipated that a
758 future extension might add a header field that allows per-column format codes
759 to be specified.
760     </para>
761
762     <para>
763 To determine the appropriate binary format for the actual tuple data you
764 should consult the <productname>PostgreSQL</productname> source, in
765 particular the <function>*send</> and <function>*recv</> functions for
766 each column's data type (typically these functions are found in the
767 <filename>src/backend/utils/adt/</filename> directory of the source
768 distribution).
769     </para>
770
771     <para>
772 If OIDs are included in the file, the OID field immediately follows the
773 field-count word.  It is a normal field except that it's not included
774 in the field-count.  In particular it has a length word &mdash; this will allow
775 handling of 4-byte vs. 8-byte OIDs without too much pain, and will allow
776 OIDs to be shown as null if that ever proves desirable.
777     </para>
778    </refsect3>
779
780    <refsect3>
781     <title>File Trailer</title>
782
783     <para>
784      The file trailer consists of a 16-bit integer word containing -1.  This
785      is easily distinguished from a tuple's field-count word.
786     </para>
787
788     <para>
789      A reader should report an error if a field-count word is neither -1
790      nor the expected number of columns.  This provides an extra
791      check against somehow getting out of sync with the data.
792     </para>
793    </refsect3>
794   </refsect2>
795  </refsect1>
796
797  <refsect1>
798   <title>Examples</title>
799
800   <para>
801    The following example copies a table to the client
802    using the vertical bar (<literal>|</literal>) as the field delimiter:
803 <programlisting>
804 COPY country TO STDOUT (DELIMITER '|');
805 </programlisting>
806   </para>
807
808   <para>
809    To copy data from a file into the <literal>country</> table:
810 <programlisting>
811 COPY country FROM '/usr1/proj/bray/sql/country_data';
812 </programlisting>
813   </para>
814
815   <para>
816    To copy into a file just the countries whose names start with 'A':
817 <programlisting>
818 COPY (SELECT * FROM country WHERE country_name LIKE 'A%') TO '/usr1/proj/bray/sql/a_list_countries.copy';
819 </programlisting>
820   </para>
821
822   <para>
823    Here is a sample of data suitable for copying into a table from
824    <literal>STDIN</literal>:
825 <programlisting>
826 AF      AFGHANISTAN
827 AL      ALBANIA
828 DZ      ALGERIA
829 ZM      ZAMBIA
830 ZW      ZIMBABWE
831 </programlisting>
832    Note that the white space on each line is actually a tab character.
833   </para>
834
835   <para>
836    The following is the same data, output in binary format.
837    The data is shown after filtering through the
838    Unix utility <command>od -c</command>. The table has three columns;
839    the first has type <type>char(2)</type>, the second has type <type>text</type>,
840    and the third has type <type>integer</type>. All the rows have a null value
841    in the third column.
842 <programlisting>
843 0000000   P   G   C   O   P   Y  \n 377  \r  \n  \0  \0  \0  \0  \0  \0
844 0000020  \0  \0  \0  \0 003  \0  \0  \0 002   A   F  \0  \0  \0 013   A
845 0000040   F   G   H   A   N   I   S   T   A   N 377 377 377 377  \0 003
846 0000060  \0  \0  \0 002   A   L  \0  \0  \0 007   A   L   B   A   N   I
847 0000100   A 377 377 377 377  \0 003  \0  \0  \0 002   D   Z  \0  \0  \0
848 0000120 007   A   L   G   E   R   I   A 377 377 377 377  \0 003  \0  \0
849 0000140  \0 002   Z   M  \0  \0  \0 006   Z   A   M   B   I   A 377 377
850 0000160 377 377  \0 003  \0  \0  \0 002   Z   W  \0  \0  \0  \b   Z   I
851 0000200   M   B   A   B   W   E 377 377 377 377 377 377
852 </programlisting></para>
853  </refsect1>
854
855  <refsect1>
856   <title>Compatibility</title>
857
858   <para>
859    There is no <command>COPY</command> statement in the SQL standard.
860   </para>
861
862   <para>
863    The following syntax was used before <productname>PostgreSQL</>
864    version 9.0 and is still supported:
865
866 <synopsis>
867 COPY <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ]
868     FROM { '<replaceable class="parameter">filename</replaceable>' | STDIN }
869     [ [ WITH ]
870           [ BINARY ]
871           [ OIDS ]
872           [ DELIMITER [ AS ] '<replaceable class="parameter">delimiter</replaceable>' ]
873           [ NULL [ AS ] '<replaceable class="parameter">null string</replaceable>' ]
874           [ CSV [ HEADER ]
875                 [ QUOTE [ AS ] '<replaceable class="parameter">quote</replaceable>' ]
876                 [ ESCAPE [ AS ] '<replaceable class="parameter">escape</replaceable>' ]
877                 [ FORCE NOT NULL <replaceable class="parameter">column_name</replaceable> [, ...] ] ] ]
878
879 COPY { <replaceable class="parameter">table_name</replaceable> [ ( <replaceable class="parameter">column_name</replaceable> [, ...] ) ] | ( <replaceable class="parameter">query</replaceable> ) }
880     TO { '<replaceable class="parameter">filename</replaceable>' | STDOUT }
881     [ [ WITH ]
882           [ BINARY ]
883           [ OIDS ]
884           [ DELIMITER [ AS ] '<replaceable class="parameter">delimiter</replaceable>' ]
885           [ NULL [ AS ] '<replaceable class="parameter">null string</replaceable>' ]
886           [ CSV [ HEADER ]
887                 [ QUOTE [ AS ] '<replaceable class="parameter">quote</replaceable>' ]
888                 [ ESCAPE [ AS ] '<replaceable class="parameter">escape</replaceable>' ]
889                 [ FORCE QUOTE { <replaceable class="parameter">column_name</replaceable> [, ...] | * } ] ] ]
890 </synopsis>
891
892    Note that in this syntax, <literal>BINARY</> and <literal>CSV</> are
893    treated as independent keywords, not as arguments of a <literal>FORMAT</>
894    option.
895   </para>
896
897   <para>
898    The following syntax was used before <productname>PostgreSQL</>
899    version 7.3 and is still supported:
900
901 <synopsis>
902 COPY [ BINARY ] <replaceable class="parameter">table_name</replaceable> [ WITH OIDS ]
903     FROM { '<replaceable class="parameter">filename</replaceable>' | STDIN }
904     [ [USING] DELIMITERS '<replaceable class="parameter">delimiter</replaceable>' ]
905     [ WITH NULL AS '<replaceable class="parameter">null string</replaceable>' ]
906
907 COPY [ BINARY ] <replaceable class="parameter">table_name</replaceable> [ WITH OIDS ]
908     TO { '<replaceable class="parameter">filename</replaceable>' | STDOUT }
909     [ [USING] DELIMITERS '<replaceable class="parameter">delimiter</replaceable>' ]
910     [ WITH NULL AS '<replaceable class="parameter">null string</replaceable>' ]
911 </synopsis></para>
912  </refsect1>
913 </refentry>