NAME
COPY - 在表和文件之间拷贝数据
SYNOPSIS
COPY tablename [ ( column [, ...] ) ] FROM { 'filename' | STDIN } [ [ WITH ] [ BINARY ] [ OIDS ] [ DELIMITER [ AS ] 'delimiter' ] [ NULL [ AS ] 'null string' ] ] COPY tablename [ ( column [, ...] ) ] TO { 'filename' | STDOUT } [ [ WITH ] [ BINARY ] [ OIDS ] [ DELIMITER [ AS ] 'delimiter' ] [ NULL [ AS ] 'null string' ] ]
DESCRIPTION 描述
COPY 在 PostgreSQL表和标准文件系统文件之间交换数据。 COPY TO 把一个表的所有内容都拷贝到一个文件, 而 COPY FROM 从一个文件里拷贝数据到一个表里(把数据附加到表中已经存在的内容里)。
如果声明了一个字段列表,COPY 将只在文件和表之间拷贝声明的字段的数据。 如果表中有任何不在字段列表里的字段,那么 COPY FROM 将为那些字段插入缺省值。
带文件名的 COPY 指示 PostgreSQL 服务器直接从文件中读写数据。 如果声明了文件名,那么该文件必须为服务器可见,而且文件名必须从服务器的角度声明。如果声明的是 STDIN 或 STDOUT,数据通过连接在客户前端和服务器之间流动。
PARAMETERS 参数
- tablename
现存表的名字(可以有模式修饰)。- column
可选的待拷贝字段列表。如果没有声明字段列表,那么将使用所有字段。- filename
输入或输出文件的绝对路径名。- STDIN
声明输入是来自客户端应用。- STDOUT
声明输入前往客户端应用。- BINARY
使用二进制格式存储和读取,而不是以文本的方式。 在二进制模式下,不能声明 DELIMITERS和NULL。- OIDS
声明为每行拷贝内部对象标识(OID)。 (如果给那些没有 OID 的表声明了 OIDS 选项,则抛出一个错误。)- delimiter
用于在文件中每行中分隔各个字段的单个字符。 缺省是水平制表符。(tab)- null string
一个代表 NULL 值的字串。缺省是 \N (反斜杠-N)。 当然,你可以自己挑一个空字串。- Note: 注意: 对于COPY FROM,任何匹配这个字串的字串将被存储为 NULL 值, 所以你应该确保你用的字串和COPY TO相同。
NOTES 注意
COPY 只能用于表,不能用于视图。
BINARY 关键字将强制使用二进制对象而不是文本存储/读取所有数据。 这样做在一定程度上比传统的拷贝命令快,但二进制拷贝文件在不同机器体系间的植性不是很好。
你对任何要COPY TO 出来的数据必须有选取数据的权限,对任何要 COPY FROM 入数据的表必须有插入权限。
COPY 命令里面的文件必须是由服务器直接读或写的文件,而不是由客户端应用读写。 因此,它们必须位于数据库服务器上或者可以为数据库服务器所访问,而不是由客户端做这些事情。 它们必须是PostgreSQL用户(服务器运行的用户 ID)可以访问到并且可读或者可写,而不是客户端。 COPY 到一个命名文件是只允许数据库超级用户进行的,因为它允许读写任意服务器有权限访问的文件。
不要混淆 COPY 和 psql 指令 \copy。 \copy 调用 COPY FROM STDIN 或者 COPY TO STDOUT, 然后把数据抓取/存储到一个 psql 客户端可以访问的文件中。 因此,使用 \copy 的时候,文件访问权限是由客户端而不是服务器端决定的。
我们建议在 COPY 里的文件名字总是使用绝对路径。 在 COPY TO 的时候是由服务器强制进行的, 但是对于 COPY FROM,你的确有从一个声明为相对路径的文件里读取的选择。 该路径将解释为相对于服务器的工作目录(在数据目录里的什么地方),而不是客户端的工作目录。
COPY FROM 会激活所有触发器和检查约束。不过,不会激活规则。
COPY 在第一个错误处停下来。这些在 COPY TO中不应该导致问题, 但在 COPY FROM 时目的表会已经接收到早先的行, 这些行将不可见或不可访问,但是仍然会占据磁盘空间。 如果你碰巧是拷贝很大一块数据文件的话, 积累起来,这些东西可能会占据相当大的一部分磁盘空间。你可以调用 VACUUM 来恢复那些磁盘空间。
FILE FORMATS 文件格式
TEXT FORMAT 文本格式
当不带 BINARY 选项使用 COPY 时, 读写的文件是一个文本文件,每行代表表中一个行。 行中的列(字段)用分隔符分开。 字段值本身是由与每个字段类型相关的输出函数生成的字符串, 或者是输入函数可接受的字串。 数据中使用特定的空值字串表示那些为 NULL 的字段。 如果输入文件的任意行包含比预期多或者少的字段,那么 COPY FROM 将抛出一个错误。 如果声明了 OIDS,那么 OID 将作为第一个字段读写, 放在所有用户字段前面。
数据的结束可以用一个只包含反斜扛和句点(\.)的行表示。 如果从文件中读取数据,那么数据结束的标记是不必要的, 因为文件结束起的作用就很好了;但是在 3.0 之前的客户端协议里,如果在客户端应用之间拷贝数据, 那么必须要有结束标记。
反斜扛字符(\)可以用在 COPY 里给那些会有歧义的字符进行逃逸(否则那些字符会被当做行或者字段分隔符处理)。 特别是下面的字符如果是字段值的一部分时,必须前缀一个反斜扛:反斜扛本身,换行符,回车,以及当前分隔符。
声明的空字串被 COPY TO 不加任何反斜杠发送;与之相对,COPY FROM 在删除反斜杠之前拿它的输入与空字串比较。因此,像 \N 这样的空字串不会和实际数据值 \N 之间混淆(因为后者会表现成 \\N)。
COPY FROM 识别下列特殊反斜扛序列:
- \b 退格 (ASCII 8)
\f 进纸 (ASCII 12)
\n 新行 (ASCII 10)
\r 回车 (ASCII 13)
\t 跳格 (ASCII 9)
\v 竖直跳格 (ASCII 11)
\digits (反斜杠,后面是三个八进制数值,代表具有指定值的字符)
目前,COPY TO 将绝不会发出一个八进制反斜扛序列, 但是它的确使用了上面列出的其它字符用于控制字符。
绝对不要把反斜扛放在一个数据字符N或者句点(.)前面。 这样的组合将分别被误认为是空字串(\.) 或者数据结束标记 (\N)。 另外一个没有在上面的表中列出的反斜扛字符就是它自己。
我们强烈建议生成 COPY 数据的应用八换行符和回车分别转换成 \n 和 \r 序列。 目前我们可以用一个反斜杠和一个回车表示一个数据回车,以及用一个反斜扛和一个换行符表示一个数据换行符。 不过,这样的表示在将来的版本中缺省时可能不会被接受。
They are also highly vulnerable to corruption if the COPY file is transferred across different machines (for example, from Unix to Windows or vice versa).
COPY TO 将再每行的结尾是用一个 Unix 风格的换行符("\n"), 或者是在 MS Windows 上运行的服务器上用("\r\n")标记一行终止,但只是用于COPY到服务器文件里; 为了在不同平台之间一致,COPY TO STDOUT 总是发送 "\n",不管服务器平台是什么。 COPY FROM 可以处理那些以回车符,或者换行符,或者回车换行符作为行结束的数据。 为了减少在数据中出现的未逃逸的新行或者回车导致的错误,如果输入的行结尾不像上面这些符号, COPY FROM 会发出警告。
BINARY FORMAT 二进制格式
在PostgreSQL 7.4 中的 COPY BINARY 的文件格式做了变化。新格式由一个文件头,零或多条元组, 以及文件尾组成。文件头和数据现在是网络字节序。
FILE HEADER 文件头
文件头由 15 个字节的固定域组成,后面跟着一个变长的头扩展区。 固定域是:
- Signature 签名
- 11-字节的序列 PGCOPY\n\377\r\n\0 --- 请注意字节零是签名是要求的一部分。 (使用这个签名是为了让我们能够很容易看出文件是否已经被一个非 8 位安全的转换器给糟蹋了。 这个签名会被行结尾转换过滤器,删除字节零,删除高位,或者奇偶的改变而改变。)
- Flags field 标志域
32 位整数掩码表示该文件格式的重要方面。 位是从 0(LSB)到 31 (MSB)编码的 --- 请注意这个域是以网络字节序存储的(高位在前), 后继的整数都是如此。位 16 - 31 是保留用做关键文件格式信息的; 如果读者发现一个不认识的位出现在这个范围内,那么它应该退出。 位 0-15 都保留为标志向后兼容的格式使用;读者可以忽略这个范围内的不认识的位。目前只定义了一个标志位,而其它的必须是零:- Bit 16
如果为 1,那么在数据中包括了 OID;如果为 0,则没有
- 头扩展范围长度
32 位整数,以字节计的头剩余长度,不包括自身。目前,它是零, 后面紧跟第一条元组。对该格式的更多的修改都将允许额外的数据出现在头中。 读者应该忽略任何它不知道该如何处理的头扩展数据。
头扩展数据是一个用来保留一个自定义的数据序列块用的。这个标志域无意告诉读者扩展区的内容是什么。头扩展的具体设计内容留给以后的版本用。
这样设计就允许向下兼容头附加(增加头扩展块,或者设置低位序标志位)以及非向下兼容修改(设置高位标志位以标识这样的修改, 并且根据需要向扩展区域增加支持数据)。
TUPLES 元组
每条元组都以一个 16 位整数计数开头,该计数是元组中字段的数目。(目前,在一个表里的每条元组都有相同的计数,但可能不会永远这样。)然后后面不断出现元组中的各个字段,字段先是一个 32 位的长度字,后面跟着那么长的字段数据。(长度字并不包括自己,并且可以为零。)一个特例是:-1 表示一个 NULL 字段值。在 NULL 情况下,后面不会跟着数值字节。
在数据域之间没有对奇填充或者任何其它额外的数据。
目前,一个 COPY BINARY 文件里的所有数据值都假设是二进制格式的(格式代码为一)。预计将来的扩展可能增加一个头域,允许为每个字段声明格式代码。
为了判断实际元组数据的正确的二进制格式,你应该阅读 PostgreSQL 源代码,特别是该字段数据类型的 *send 和 *recv 函数(典型的函数可以在源代码的 src/backend/utils/adt/ 目录找到)。
如果在文件中包括了 OID,那么该 OID 域立即跟在字段计数字后面。它是一个普通的字段,只不过它没有包括在字段计数。但它包括长度字 --- 这样就允许我们不用花太多的劲就可以处理 4 字节和 8 字节的 OID,并且如果某个家伙允许 OID 是可选的话,那么还可以把 OID 显示成空。
FILE TRAILER 文件尾
文件尾包括保存着 -1 的一个 16 位整数字。这样就很容易与一条元组的域计数字相区分。
如果一个域计数字既不是 -1 也不是预期的字段的数目,那么读者应该报错。 这样就提供了对丢失与数据的同步的额外的检查。
EXAMPLES 例子
下面的例子把一个表拷贝到客户端, 使用竖直条(|)作为域分隔符:
COPY country TO STDOUT WITH DELIMITER '|';
从一个 Unix 文件中拷贝数据到一个country表中:
COPY country FROM '/usr1/proj/bray/sql/country_data';
下面是一个可以从 STDIN 中拷贝数据到表中的例子:
AF AFGHANISTAN AL ALBANIA DZ ALGERIA ZM ZAMBIA ZW ZIMBABWE
请注意在这里每行里的空白实际上是一个水平制表符 tab。
下面的是同样的数据,在一台 Linux/i586 机器上以二进制形式输出。 这些数据是用 Unix 工具 od -c 过滤之后输出的。 该表有三个字段;第一个是 char(2), 第二个是 text, 第三个是integer。所有的行在第三个域都是一个 null 值。
0000000 P G C O P Y \n 377 \r \n \0 \0 \0 \0 \0 \0 0000020 \0 \0 \0 \0 003 \0 \0 \0 002 A F \0 \0 \0 013 A 0000040 F G H A N I S T A N 377 377 377 377 \0 003 0000060 \0 \0 \0 002 A L \0 \0 \0 007 A L B A N I 0000100 A 377 377 377 377 \0 003 \0 \0 \0 002 D Z \0 \0 \0 0000120 007 A L G E R I A 377 377 377 377 \0 003 \0 \0 0000140 \0 002 Z M \0 \0 \0 006 Z A M B I A 377 377 0000160 377 377 \0 003 \0 \0 \0 002 Z W \0 \0 \0 \b Z I 0000200 M B A B W E 377 377 377 377 377 377
#p#
NAME
COPY - copy data between a file and a table
SYNOPSIS
COPY tablename [ ( column [, ...] ) ] FROM { 'filename' | STDIN } [ [ WITH ] [ BINARY ] [ OIDS ] [ DELIMITER [ AS ] 'delimiter' ] [ NULL [ AS ] 'null string' ] ] COPY tablename [ ( column [, ...] ) ] TO { 'filename' | STDOUT } [ [ WITH ] [ BINARY ] [ OIDS ] [ DELIMITER [ AS ] 'delimiter' ] [ NULL [ AS ] 'null string' ] ]
DESCRIPTION
COPY moves data between PostgreSQL tables and standard file-system files. COPY TO copies the contents of a table to a file, while COPY FROM copies data from a file to a table (appending the data to whatever is in the table already).
If a list of columns is specified, COPY will only copy the data in the specified columns to or from the file. If there are any columns in the table that are not in the column list, COPY FROM will insert the default values for those columns.
COPY with a file name instructs the PostgreSQL server to directly read from or write to a file. The file must be accessible to the server and the name must be specified from the viewpoint of the server. When STDIN or STDOUT is specified, data is transmitted via the connection between the client and the server.
PARAMETERS
- tablename
- The name (optionally schema-qualified) of an existing table.
- column
- An optional list of columns to be copied. If no column list is specified, all columns will be used.
- filename
- The absolute path name of the input or output file.
- STDIN
- Specifies that input comes from the client application.
- STDOUT
- Specifies that output goes to the client application.
- BINARY
- Causes all data to be stored or read in binary format rather than as text. You cannot specify the DELIMITER or NULL options in binary mode.
- OIDS
- Specifies copying the OID for each row. (An error is raised if OIDS is specified for a table that does not have OIDs.)
- delimiter
- The single character that separates columns within each row (line) of the file. The default is a tab character.
- null string
- The string that represents a null value. The default is \N (backslash-N). You might prefer an empty string, for example.
- Note: On a COPY FROM, any data item that matches this string will be stored as a null value, so you should make sure that you use the same string as you used with COPY TO.
NOTES
COPY can only be used with plain tables, not with views.
The BINARY key word causes all data to be stored/read as binary format rather than as text. It is somewhat faster than the normal text mode, but a binary-format file is less portable across machine architectures and PostgreSQL versions.
You must have select privilege on the table whose values are read by COPY TO, and insert privilege on the table into which values are inserted by COPY FROM.
Files named in a COPY command are read or written directly by the server, not by the client application. Therefore, they must reside on or be accessible to the database server machine, not the client. They must be accessible to and readable or writable by the PostgreSQL user (the user ID the server runs as), not the client. COPY naming a file is only allowed to database superusers, since it allows reading or writing any file that the server has privileges to access.
Do not confuse COPY with the psql instruction \copy. \copy invokes COPY FROM STDIN or COPY TO STDOUT, and then fetches/stores the data in a file accessible to the psql client. Thus, file accessibility and access rights depend on the client rather than the server when \copy is used.
It is recommended that the file name used in COPY always be specified as an absolute path. This is enforced by the server in the case of COPY TO, but for COPY FROM you do have the option of reading from a file specified by a relative path. The path will be interpreted relative to the working directory of the server process (somewhere below the data directory), not the client's working directory.
COPY FROM will invoke any triggers and check constraints on the destination table. However, it will not invoke rules.
COPY stops operation at the first error. This should not lead to problems in the event of a COPY TO, but the target table will already have received earlier rows in a COPY FROM. These rows will not be visible or accessible, but they still occupy disk space. This may amount to a considerable amount of wasted disk space if the failure happened well into a large copy operation. You may wish to invoke VACUUM to recover the wasted space.
FILE FORMATS
TEXT FORMAT
When COPY is used without the BINARY option, the data read or written is a text file with one line per table row. Columns in a row are separated by the delimiter character. The column values themselves are strings generated by the output function, or acceptable to the input function, of each attribute's data type. The specified null string is used in place of columns that are null. COPY FROM will raise an error if any line of the input file contains more or fewer columns than are expected. If OIDS is specified, the OID is read or written as the first column, preceding the user data columns.
End of data can be represented by a single line containing just backslash-period (\.). An end-of-data marker is not necessary when reading from a file, since the end of file serves perfectly well; it is needed only when copying data to or from client applications using pre-3.0 client protocol.
Backslash characters (\) may be used in the COPY data to quote data characters that might otherwise be taken as row or column delimiters. In particular, the following characters must be preceded by a backslash if they appear as part of a column value: backslash itself, newline, carriage return, and the current delimiter character.
The specified null string is sent by COPY TO without adding any backslashes; conversely, COPY FROM matches the input against the null string before removing backslashes. Therefore, a null string such as \N cannot be confused with the actual data value \N (which would be represented as \\N).
The following special backslash sequences are recognized by COPY FROM: SequenceRepresents\bBackspace (ASCII 8)\fForm feed (ASCII 12)\nNewline (ASCII 10)\rCarriage return (ASCII 13)\tTab (ASCII 9)\vVertical tab (ASCII 11)\digitsBackslash followed by one to three octal digits specifies the character with that numeric code Presently, COPY TO will never emit an octal-digits backslash sequence, but it does use the other sequences listed above for those control characters.
Any other backslashed character that is not mentioned in the above table will be taken to represent itself. However, beware of adding backslashes unnecessarily, since that might accidentally produce a string matching the end-of-data marker (\.) or the null string (\N by default). These strings will be recognized before any other backslash processing is done.
It is strongly recommended that applications generating COPY data convert data newlines and carriage returns to the \n and \r sequences respectively. At present it is possible to represent a data carriage return by a backslash and carriage return, and to represent a data newline by a backslash and newline. However, these representations might not be accepted in future releases. They are also highly vulnerable to corruption if the COPY file is transferred across different machines (for example, from Unix to Windows or vice versa).
COPY TO will terminate each row with a Unix-style newline (``\n''). Servers running on MS Windows instead output carriage return/newline (``\r\n''), but only for COPY to a server file; for consistency across platforms, COPY TO STDOUT always sends ``\n'' regardless of server platform. COPY FROM can handle lines ending with newlines, carriage returns, or carriage return/newlines. To reduce the risk of error due to un-backslashed newlines or carriage returns that were meant as data, COPY FROM will complain if the line endings in the input are not all alike.
BINARY FORMAT
The file format used for COPY BINARY changed in PostgreSQL 7.4. The new format consists of a file header, zero or more tuples containing the row data, and a file trailer. Headers and data are now in network byte order.
FILE HEADER
The file header consists of 15 bytes of fixed fields, followed by a variable-length header extension area. The fixed fields are:
- Signature
- 11-byte sequence PGCOPY\n\377\r\n\0 --- note that the zero byte is a required part of the signature. (The signature is designed to allow easy identification of files that have been munged by a non-8-bit-clean transfer. This signature will be changed by end-of-line-translation filters, dropped zero bytes, dropped high bits, or parity changes.)
- Flags field
- 32-bit integer bit mask to denote important aspects of the file format. Bits are numbered from 0 (LSB) to 31 (MSB). Note that this field is stored in network byte order (most significant byte first), as are all the integer fields used in the file format. Bits 16-31 are reserved to denote critical file format issues; a reader should abort if it finds an unexpected bit set in this range. Bits 0-15 are reserved to signal backwards-compatible format issues; a reader should simply ignore any unexpected bits set in this range. Currently only one flag bit is defined, and the rest must be zero:
- Bit 16
- if 1, OIDs are included in the data; if 0, not
- Header extension area length
- 32-bit integer, length in bytes of remainder of header, not including self. Currently, this is zero, and the first tuple follows immediately. Future changes to the format might allow additional data to be present in the header. A reader should silently skip over any header extension data it does not know what to do with.
The header extension area is envisioned to contain a sequence of self-identifying chunks. The flags field is not intended to tell readers what is in the extension area. Specific design of header extension contents is left for a later release.
This design allows for both backwards-compatible header additions (add header extension chunks, or set low-order flag bits) and non-backwards-compatible changes (set high-order flag bits to signal such changes, and add supporting data to the extension area if needed).
TUPLES
Each tuple begins with a 16-bit integer count of the number of fields in the tuple. (Presently, all tuples in a table will have the same count, but that might not always be true.) Then, repeated for each field in the tuple, there is a 32-bit length word followed by that many bytes of field data. (The length word does not include itself, and can be zero.) As a special case, -1 indicates a NULL field value. No value bytes follow in the NULL case.
There is no alignment padding or any other extra data between fields.
Presently, all data values in a COPY BINARY file are assumed to be in binary format (format code one). It is anticipated that a future extension may add a header field that allows per-column format codes to be specified.
To determine the appropriate binary format for the actual tuple data you should consult the PostgreSQL source, in particular the *send and *recv functions for each column's data type (typically these functions are found in the src/backend/utils/adt/ directory of the source distribution).
If OIDs are included in the file, the OID field immediately follows the field-count word. It is a normal field except that it's not included in the field-count. In particular it has a length word --- this will allow handling of 4-byte vs. 8-byte OIDs without too much pain, and will allow OIDs to be shown as null if that ever proves desirable.
FILE TRAILER
The file trailer consists of a 16-bit integer word containing -1. This is easily distinguished from a tuple's field-count word.
A reader should report an error if a field-count word is neither -1 nor the expected number of columns. This provides an extra check against somehow getting out of sync with the data.
EXAMPLES
The following example copies a table to the client using the vertical bar (|) as the field delimiter:
COPY country TO STDOUT WITH DELIMITER '|';
To copy data from a file into the country table:
COPY country FROM '/usr1/proj/bray/sql/country_data';
Here is a sample of data suitable for copying into a table from STDIN:
AF AFGHANISTAN AL ALBANIA DZ ALGERIA ZM ZAMBIA ZW ZIMBABWE
Note that the white space on each line is actually a tab character.
The following is the same data, output in binary format. The data is shown after filtering through the Unix utility od -c. The table has three columns; the first has type char(2), the second has type text, and the third has type integer. All the rows have a null value in the third column.
0000000 P G C O P Y \n 377 \r \n \0 \0 \0 \0 \0 \0 0000020 \0 \0 \0 \0 003 \0 \0 \0 002 A F \0 \0 \0 013 A 0000040 F G H A N I S T A N 377 377 377 377 \0 003 0000060 \0 \0 \0 002 A L \0 \0 \0 007 A L B A N I 0000100 A 377 377 377 377 \0 003 \0 \0 \0 002 D Z \0 \0 \0 0000120 007 A L G E R I A 377 377 377 377 \0 003 \0 \0 0000140 \0 002 Z M \0 \0 \0 006 Z A M B I A 377 377 0000160 377 377 \0 003 \0 \0 \0 002 Z W \0 \0 \0 \b Z I 0000200 M B A B W E 377 377 377 377 377 377