pg_create_foreign_table | R Documentation |
The use case for this function is as follows: You get a large file (csv, tab-delimited) and would rather wrangle such data in postgres. Instead of go ahead and copy all the data into a table, let's create a foreign table that you can query just like a regular table.
pg_create_foreign_table(
con,
file_path,
table,
sep = ";",
nrows = 10000,
header = TRUE,
na.strings = c("", "NA", "NULL"),
colClasses = NULL,
col.names,
encoding = "UTF-8",
...,
drop_table = FALSE,
cascade = FALSE,
if_not_exists = FALSE,
create_foreign_server = TRUE,
execute = FALSE,
quote = "\b",
escape = quote,
null = "NULL"
)
con |
A database connection. |
file_path |
path to a text file (csv, tab-delimited, etc.) |
table |
The table name, passed on to
|
sep |
The separator between columns. Defaults to the character in the set |
nrows |
The maximum number of rows to read. Unlike |
header |
Does the first data line contain column names? Defaults according to whether every non-empty field on the first data line is type character. If so, or TRUE is supplied, any empty column names are given a default name. |
na.strings |
A character vector of strings which are to be interpreted as |
colClasses |
As in |
col.names |
A vector of optional names for the variables (columns). The default is to use the header column if present or detected, or if not "V" followed by the column number. This is applied after |
encoding |
default is |
... |
Other arguments used by individual methods. |
drop_table |
logical, whether to drop the table before creating it |
cascade |
logical, whether to add CASCADE to the DROP statement |
if_not_exists |
logical, to add IF NOT EXISTS to the query |
create_foreign_server |
logical, to create the extension and server for the foreign data wrapper (https://www.postgresql.org/docs/10/file-fdw.html) |
execute |
logical, whether to execute the query using |
quote |
By default ( |
escape |
"character that should appear before a data character that matches the QUOTE value" |
null |
"Specifies the string that represents a null value." |
Some notes:
The file must be accesible to the postgres server. This function tries to edit file's privileges to make sure is readable from the server. However, if the file is in a network share, that may not be enough because the server should be able to access the network resource. It is likely the default user running the server cannot access network shared resources, so the workaround is to change the user running the server
See Postgres documentation:
Foreign table https://www.postgresql.org/docs/10/sql-createforeigntable .html
Foreign-data wrapper for files https://www.postgresql.org/docs/10/file- fdw.html
Options documented in COPY https://www.postgresql.org/docs/10/sql-copy .html
invisibly returns a character vector (length 1) with the sql statement
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.