COPY 中文man頁面
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