Title: | R Interface to a 'PostGIS' Database |
---|---|
Description: | Provides an interface between R and 'PostGIS'-enabled 'PostgreSQL' databases to transparently transfer spatial data. Both vector (points, lines, polygons) and raster data are supported in read and write modes. Also provides convenience functions to execute common procedures in 'PostgreSQL/PostGIS'. |
Authors: | Adrian Cidre Gonzalez [aut, cre] , Mathieu Basille [aut] , David Bucklin [aut] |
Maintainer: | Adrian Cidre Gonzalez <[email protected]> |
License: | GPL (>= 3) |
Version: | 1.6.0 |
Built: | 2024-12-06 18:41:26 UTC |
Source: | CRAN |
Add a primary or foreign key to a table column.
dbAddKey( conn, name, colname, type = c("primary", "foreign"), reference, colref, display = TRUE, exec = TRUE )
dbAddKey( conn, name, colname, type = c("primary", "foreign"), reference, colref, display = TRUE, exec = TRUE )
conn |
A connection object. |
name |
A character string, or a character vector, specifying a PostgreSQL table name. |
colname |
A character string specifying the name of the column to which the key will be assign; alternatively, a character vector specifying the name of the columns for keys spanning more than one column. |
type |
The type of the key, either |
reference |
A character string specifying a foreign table
name to which the foreign key will be associated (ignored if
|
colref |
A character string specifying the name of the
primary key in the foreign table to which the foreign key will
be associated; alternatively, a character vector specifying
the name of the columns for keys spanning more than one column
(ignored if |
display |
Logical. Whether to display the query (defaults to
|
exec |
Logical. Whether to execute the query (defaults to
|
If exec = TRUE
, returns (invisibly) TRUE
if the key was successfully added.
Mathieu Basille [email protected]
The PostgreSQL documentation: http://www.postgresql.org/docs/current/static/sql-altertable.html
## Examples use a dummy connection from DBI package conn <- DBI::ANSI() ## Primary key dbAddKey(conn, name = c("sch1", "tbl1"), colname = "id1", exec = FALSE) ## Primary key using multiple columns dbAddKey(conn, name = c("sch1", "tbl1"), colname = c("id1", "id2", "id3"), exec = FALSE) ## Foreign key dbAddKey(conn, name = c("sch1", "tbl1"), colname = "id", type = "foreign", reference = c("sch2", "tbl2"), colref = "id", exec = FALSE) ## Foreign key using multiple columns dbAddKey(conn, name = c("sch1", "tbl1"), colname = c("id1", "id2"), type = "foreign", reference = c("sch2", "tbl2"), colref = c("id3", "id4"), exec = FALSE)
## Examples use a dummy connection from DBI package conn <- DBI::ANSI() ## Primary key dbAddKey(conn, name = c("sch1", "tbl1"), colname = "id1", exec = FALSE) ## Primary key using multiple columns dbAddKey(conn, name = c("sch1", "tbl1"), colname = c("id1", "id2", "id3"), exec = FALSE) ## Foreign key dbAddKey(conn, name = c("sch1", "tbl1"), colname = "id", type = "foreign", reference = c("sch2", "tbl2"), colref = "id", exec = FALSE) ## Foreign key using multiple columns dbAddKey(conn, name = c("sch1", "tbl1"), colname = c("id1", "id2"), type = "foreign", reference = c("sch2", "tbl2"), colref = c("id3", "id4"), exec = FALSE)
Convert a date field to a timestamp with or without time zone.
dbAsDate(conn, name, date = "date", tz = NULL, display = TRUE, exec = TRUE)
dbAsDate(conn, name, date = "date", tz = NULL, display = TRUE, exec = TRUE)
conn |
A connection object. |
name |
A character string specifying a PostgreSQL table name. |
date |
A character string specifying the date field. |
tz |
A character string specifying the time zone, in
|
display |
Logical. Whether to display the query (defaults to
|
exec |
Logical. Whether to execute the query (defaults to
|
If exec = TRUE
, returns (invisibly) TRUE
if the
conversion was successful.
Mathieu Basille [email protected]
The PostgreSQL documentation: http://www.postgresql.org/docs/current/static/datatype-datetime.html
## Example uses a dummy connection from DBI package conn <- DBI::ANSI() dbAsDate(conn, name = c("schema", "table"), date = "date", tz = "GMT", exec = FALSE)
## Example uses a dummy connection from DBI package conn <- DBI::ANSI() dbAsDate(conn, name = c("schema", "table"), date = "date", tz = "GMT", exec = FALSE)
Add or remove a column to/from a table.
dbColumn( conn, name, colname, action = c("add", "drop"), coltype = "integer", cascade = FALSE, display = TRUE, exec = TRUE )
dbColumn( conn, name, colname, action = c("add", "drop"), coltype = "integer", cascade = FALSE, display = TRUE, exec = TRUE )
conn |
A connection object. |
name |
A character string specifying a PostgreSQL table name. |
colname |
A character string specifying the name of the column |
action |
A character string specifying if the column is to be
added ( |
coltype |
A character string indicating the type of the
column, if |
cascade |
Logical. Whether to drop foreign key constraints of
other tables, if |
display |
Logical. Whether to display the query (defaults to
|
exec |
Logical. Whether to execute the query (defaults to
|
If exec = TRUE
, returns (invisibly) TRUE
if the column was
successfully added or removed.
Mathieu Basille [email protected]
The PostgreSQL documentation: http://www.postgresql.org/docs/current/static/sql-altertable.html
## examples use a dummy connection from DBI package conn<-DBI::ANSI() ## Add an integer column dbColumn(conn, name = c("schema", "table"), colname = "field", exec = FALSE) ## Drop a column (with CASCADE) dbColumn(conn, name = c("schema", "table"), colname = "field", action = "drop", cascade = TRUE, exec = FALSE)
## examples use a dummy connection from DBI package conn<-DBI::ANSI() ## Add an integer column dbColumn(conn, name = c("schema", "table"), colname = "field", exec = FALSE) ## Drop a column (with CASCADE) dbColumn(conn, name = c("schema", "table"), colname = "field", action = "drop", cascade = TRUE, exec = FALSE)
Comment on a table, a view or a schema.
dbComment( conn, name, comment, type = c("table", "view", "schema"), display = TRUE, exec = TRUE )
dbComment( conn, name, comment, type = c("table", "view", "schema"), display = TRUE, exec = TRUE )
conn |
A connection object. |
name |
A character string specifying a PostgreSQL table, view or schema name. |
comment |
A character string specifying the comment. |
type |
The type of the object to comment, either |
display |
Logical. Whether to display the query (defaults to
|
exec |
Logical. Whether to execute the query (defaults to
|
If exec = TRUE
, returns (invisibly) TRUE
if the comment was
successfully applied.
Mathieu Basille [email protected]
The PostgreSQL documentation: http://www.postgresql.org/docs/current/static/sql-comment.html
## examples use a dummy connection from DBI package conn <- DBI::ANSI() dbComment(conn, name = c("schema", "table"), comment = "Comment on a view.", type = "view", exec = FALSE) dbComment(conn, name = "test_schema", comment = "Comment on a schema.", type = "schema", exec = FALSE)
## examples use a dummy connection from DBI package conn <- DBI::ANSI() dbComment(conn, name = c("schema", "table"), comment = "Comment on a view.", type = "view", exec = FALSE) dbComment(conn, name = "test_schema", comment = "Comment on a schema.", type = "schema", exec = FALSE)
Drop a table, a view or a schema.
dbDrop( conn, name, type = c("table", "schema", "view", "materialized view"), ifexists = FALSE, cascade = FALSE, display = TRUE, exec = TRUE )
dbDrop( conn, name, type = c("table", "schema", "view", "materialized view"), ifexists = FALSE, cascade = FALSE, display = TRUE, exec = TRUE )
conn |
A connection object. |
name |
A character string specifying a PostgreSQL table, schema, or view name. |
type |
The type of the object to drop, either |
ifexists |
Do not throw an error if the object does not exist. A notice is issued in this case. |
cascade |
Automatically drop objects that depend on the object (such as views). |
display |
Logical. Whether to display the query (defaults to
|
exec |
Logical. Whether to execute the query (defaults to
|
If exec = TRUE
, returns (invisibly) TRUE
if the table/schema/view
was successfully dropped.
Mathieu Basille [email protected]
The PostgreSQL documentation: http://www.postgresql.org/docs/current/static/sql-droptable.html, http://www.postgresql.org/docs/current/static/sql-dropview.html, http://www.postgresql.org/docs/current/static/sql-dropschema.html
## examples use a dummy connection from DBI package conn <- DBI::ANSI() dbDrop(conn, name = c("schema", "view_name"), type = "view", exec = FALSE) dbDrop(conn, name = "test_schema", type = "schema", cascade = "TRUE", exec = FALSE)
## examples use a dummy connection from DBI package conn <- DBI::ANSI() dbDrop(conn, name = c("schema", "view_name"), type = "view", exec = FALSE) dbDrop(conn, name = "test_schema", type = "schema", cascade = "TRUE", exec = FALSE)
Defines a new index on a PostgreSQL table.
dbIndex( conn, name, colname, idxname, unique = FALSE, method = c("btree", "hash", "rtree", "gist"), display = TRUE, exec = TRUE )
dbIndex( conn, name, colname, idxname, unique = FALSE, method = c("btree", "hash", "rtree", "gist"), display = TRUE, exec = TRUE )
conn |
A connection object. |
name |
A character string specifying a PostgreSQL table name. |
colname |
A character string, or a character vector specifying the name of the column to which the key will be associated; alternatively, a character vector specifying the name of the columns to build the index. |
idxname |
A character string specifying the name of the index
to be created. By default, this uses the name of the table
(without the schema) and the name of the columns as follows:
|
unique |
Logical. Causes the system to check for duplicate values in the table when the index is created (if data already exist) and each time data is added. Attempts to insert or update data which would result in duplicate entries will generate an error. |
method |
The name of the method to be used for the
index. Choices are |
display |
Logical. Whether to display the query (defaults to
|
exec |
Logical. Whether to execute the query (defaults to
|
If exec = TRUE
, returns (invisibly) TRUE
if the index was
successfully created.
Mathieu Basille [email protected]
The PostgreSQL documentation: http://www.postgresql.org/docs/current/static/sql-createindex.html; the PostGIS documentation for GiST indexes: http://postgis.net/docs/using_postgis_dbmanagement.html#id541286
## Examples use a dummy connection from DBI package conn <- DBI::ANSI() ## GIST index dbIndex(conn, name = c("sch", "tbl"), colname = "geom", method = "gist", exec = FALSE) ## Regular BTREE index on multiple columns dbIndex(conn, name = c("sch", "tbl"), colname = c("col1", "col2", "col3"), exec = FALSE)
## Examples use a dummy connection from DBI package conn <- DBI::ANSI() ## GIST index dbIndex(conn, name = c("sch", "tbl"), colname = "geom", method = "gist", exec = FALSE) ## Regular BTREE index on multiple columns dbIndex(conn, name = c("sch", "tbl"), colname = c("col1", "col2", "col3"), exec = FALSE)
Checks the existence, and if necessary, creates a schema.
dbSchema(conn, name, display = TRUE, exec = TRUE)
dbSchema(conn, name, display = TRUE, exec = TRUE)
conn |
A connection object (required, even if |
name |
A character string specifying a PostgreSQL schema name. |
display |
Logical. Whether to display the query (defaults to
|
exec |
Logical. Whether to execute the query (defaults to
|
If exec = TRUE
, returns (invisible) TRUE
if the schema exists
(whether it was already available or was just created).
Mathieu Basille [email protected]
The PostgreSQL documentation: http://www.postgresql.org/docs/current/static/sql-createschema.html
## Not run: dbSchema(conn, name = "schema", exec = FALSE) ## End(Not run)
## Not run: dbSchema(conn, name = "schema", exec = FALSE) ## End(Not run)
Get information about columns in a PostgreSQL table.
dbTableInfo(conn, name, allinfo = FALSE)
dbTableInfo(conn, name, allinfo = FALSE)
conn |
A connection object to a PostgreSQL database. |
name |
A character string specifying a PostgreSQL schema (if
necessary), and table or view name (e.g., |
allinfo |
Logical, Get all information on table? Default is column names, types, nullable, and maximum length of character columns. |
data frame
David Bucklin [email protected]
## Not run: dbTableInfo(conn, c("schema", "table")) ## End(Not run)
## Not run: dbTableInfo(conn, c("schema", "table")) ## End(Not run)
Performs a VACUUM (garbage-collect and optionally analyze) on a table.
dbVacuum( conn, name, full = FALSE, verbose = FALSE, analyze = TRUE, display = TRUE, exec = TRUE )
dbVacuum( conn, name, full = FALSE, verbose = FALSE, analyze = TRUE, display = TRUE, exec = TRUE )
conn |
A connection object. |
name |
A character string specifying a PostgreSQL table name. |
full |
Logical. Whether to perform a "full" vacuum, which can reclaim more space, but takes much longer and exclusively locks the table. |
verbose |
Logical. Whether to print a detailed vacuum activity report for each table. |
analyze |
Logical. Whether to update statistics used by the
planner to determine the most efficient way to execute a query
(default to |
display |
Logical. Whether to display the query (defaults to
|
exec |
Logical. Whether to execute the query (defaults to
|
If exec = TRUE
, returns (invisibly) TRUE if query is successfully executed.
Mathieu Basille [email protected]
The PostgreSQL documentation: http://www.postgresql.org/docs/current/static/sql-vacuum.html
## examples use a dummy connection from DBI package conn <- DBI::ANSI() dbVacuum(conn, name = c("schema", "table"), full = TRUE, exec = FALSE)
## examples use a dummy connection from DBI package conn <- DBI::ANSI() dbVacuum(conn, name = c("schema", "table"), full = TRUE, exec = FALSE)
Write data.frame
or similar (e.g. tibble
) to database table,
with column definitions, row names, and a new integer primary key column.
Read back into R with dbReadDataFrame
, which recreates original
data.
dbWriteDataFrame(conn, name, df, overwrite = FALSE, only.defs = FALSE) dbReadDataFrame(conn, name, df = NULL)
dbWriteDataFrame(conn, name, df, overwrite = FALSE, only.defs = FALSE) dbReadDataFrame(conn, name, df = NULL)
conn |
A connection object to a PostgreSQL database |
name |
Character, schema and table of the PostgreSQL table |
df |
The data frame to write (for |
overwrite |
Logical; if TRUE, a new table ( |
only.defs |
Logical; if |
Writing in data frame mode is only for new database tables (or for overwriting an existing one). It will save all column names as they appear in R, along with column data types and attributes. This is done by adding metadata to a lookup table in the table's schema named ".R_df_defs" (will be created if not present). It also adds two fields with fixed names to the database table: ".R_rownames" (storing the row.names of the data frame), and ".db_pkid", which is a new integer primary key. Existing columns in the data.frame matching these names will be automatically changed.
The rpostgis
database table read functions
dbReadDataFrame
and pgGetGeom
will use the metadata
created in data frame mode to recreate a data.frame in R, if it is
available. Otherwise, it will be imported using default
RPostgreSQL::dbGetQuery
methods.
All spatial objects must be written with pgWriteGeom()
.
For more flexible writing of data.frame
s to the database
(including all writing into existing database tables), use
pgWriteGeom()
with df.mode = FALSE
.
invisible TRUE
for successful write with
dbWriteDataFrame
, data.frame
for
dbReadDataFrame
David Bucklin [email protected]
Adrián Cidre González [email protected]
## Not run: library(datasets) ## Write the mtcars data.frame to the database: dbWriteDataFrame(conn, name = "mtcars_data", df = mtcars) ## Reads it back into a different object: mtcars2 <- dbReadDataFrame(conn, name = "mtcars_data") ## Check equality: all.equal(mtcars, mtcars2) ## Should return TRUE. ## End(Not run)
## Not run: library(datasets) ## Write the mtcars data.frame to the database: dbWriteDataFrame(conn, name = "mtcars_data", df = mtcars) ## Reads it back into a different object: mtcars2 <- dbReadDataFrame(conn, name = "mtcars_data") ## Check equality: all.equal(mtcars, mtcars2) ## Should return TRUE. ## End(Not run)
Retrieve bounding envelope (rectangle) of all geometries or
rasters in a PostGIS table as a sfc
object.
pgGetBoundary(conn, name, geom = "geom", clauses = NULL, returnclass = "sf")
pgGetBoundary(conn, name, geom = "geom", clauses = NULL, returnclass = "sf")
conn |
A connection object to a PostgreSQL database |
name |
A character string specifying a PostgreSQL schema and
table/view name holding the geometry (e.g., |
geom |
A character string specifying the name of the geometry column
in the table |
clauses |
character, additional SQL to append to modify select
query from table. Must begin with an SQL clause (e.g., "WHERE ...",
"ORDER BY ...", "LIMIT ..."); same usage as in |
returnclass |
'sf' by default; 'terra' for |
object of class sfc (list-column with geometries); SpatVector or sp object
David Bucklin [email protected] and Adrian Cidre González [email protected]
## Not run: pgGetBoundary(conn, c("schema", "polys"), geom = "geom") pgGetBoundary(conn, c("schema", "rasters"), geom = "rast") ## End(Not run)
## Not run: pgGetBoundary(conn, c("schema", "polys"), geom = "geom") pgGetBoundary(conn, c("schema", "rasters"), geom = "rast") ## End(Not run)
Retrieve geometries from a PostGIS table/view/query, and convert
it to an R sf
object.
pgGetGeom( conn, name, geom = "geom", gid = NULL, other.cols = TRUE, clauses = NULL, boundary = NULL, query = NULL, returnclass = "sf" )
pgGetGeom( conn, name, geom = "geom", gid = NULL, other.cols = TRUE, clauses = NULL, boundary = NULL, query = NULL, returnclass = "sf" )
conn |
A connection object to a PostgreSQL database |
name |
A character string specifying a PostgreSQL schema and
table/view name holding the geometry (e.g., |
geom |
The name of the geometry/(geography) column. (Default = |
gid |
Name of the column in |
other.cols |
Names of specific columns in the table to
retrieve, in a character vector (e.g. |
clauses |
character, additional SQL to append to modify select query from table. Must begin with an SQL clause (e.g., "WHERE ...", "ORDER BY ...", "LIMIT ..."); see below for examples. |
boundary |
|
query |
character, a full SQL query including a geometry column. For use with query mode only (see details). |
returnclass |
'sf' by default; 'terra' for |
The features of the table to retrieve must have the same geometry type.
The query mode version of pgGetGeom
allows the user to enter a
complete SQL query (query
) that returns a Geometry column, and save
the query as a new view (name
) if desired. If (name
) is not
specified, a temporary view with name ".rpostgis_TEMPview" is used only
within the function execution. In this mode, the other arguments can be used
normally to modify the Spatial* object returned from the query.
sf, SpatVector or sp object
David Bucklin [email protected]
Mathieu Basille [email protected]
Adrián Cidre González [email protected]
## Not run: ## Retrieve a sf with all data from table ## 'schema.tablename', with geometry in the column 'geom' pgGetGeom(conn, c("schema", "tablename")) ## Return a sf with columns c1 & c2 as data pgGetGeom(conn, c("schema", "tablename"), other.cols = c("c1","c2")) ## Return a spatial-only (no data frame), ## retaining id from table as rownames pgGetGeom(conn, c("schema", "tablename"), gid = "table_id", other.cols = FALSE) ## Return a spatial-only (no data frame), ## retaining id from table as rownames and with a subset of the data pgGetGeom(conn, c("schema", "roads"), geom = "roadgeom", gid = "road_ID", other.cols = FALSE, clauses = "WHERE road_type = 'highway'") ## Query mode pgGetGeom(conn, query = "SELECT r.gid as id, ST_Buffer(r.geom, 100) as geom FROM schema.roads r, schema.adm_boundaries b WHERE ST_Intersects(r.geom, b.geom);") ## End(Not run)
## Not run: ## Retrieve a sf with all data from table ## 'schema.tablename', with geometry in the column 'geom' pgGetGeom(conn, c("schema", "tablename")) ## Return a sf with columns c1 & c2 as data pgGetGeom(conn, c("schema", "tablename"), other.cols = c("c1","c2")) ## Return a spatial-only (no data frame), ## retaining id from table as rownames pgGetGeom(conn, c("schema", "tablename"), gid = "table_id", other.cols = FALSE) ## Return a spatial-only (no data frame), ## retaining id from table as rownames and with a subset of the data pgGetGeom(conn, c("schema", "roads"), geom = "roadgeom", gid = "road_ID", other.cols = FALSE, clauses = "WHERE road_type = 'highway'") ## Query mode pgGetGeom(conn, query = "SELECT r.gid as id, ST_Buffer(r.geom, 100) as geom FROM schema.roads r, schema.adm_boundaries b WHERE ST_Intersects(r.geom, b.geom);") ## End(Not run)
Retrieve rasters from a PostGIS table into a terra SpatRaster
object
pgGetRast( conn, name, rast = "rast", bands = 1, boundary = NULL, clauses = NULL, returnclass = "terra", progress = TRUE )
pgGetRast( conn, name, rast = "rast", bands = 1, boundary = NULL, clauses = NULL, returnclass = "terra", progress = TRUE )
conn |
A connection object to a PostgreSQL database |
name |
A character string specifying a PostgreSQL schema and
table/view name holding the geometry (e.g., |
rast |
Name of the column in |
bands |
Index number(s) for the band(s) to retrieve (defaults to 1).
The special case ( |
boundary |
|
clauses |
character, optional SQL to append to modify select query from table. Must begin with 'WHERE'. |
returnclass |
'terra' by default; or 'raster' for |
progress |
whether to show a progress bar (TRUE by default). The progress bar mark the progress of reading bands from the database. |
Since version 1.5.0, this function retrieve SpatRaster objects from
terra
package by default. The argument returnclass
can be
used to return raster
objects instead.
The argument bands
can take as argument:
The index of the desirable band (e.g. bands = 2 will fetch the second band of the raster).
More than one index for several bands (e.g. bands = c(2,4) will return a
SpatRaster
with two bands).
All bands in the raster (bands = TRUE).
SpatRaster
; raster
; or RasterStack
object
David Bucklin [email protected] and Adrián Cidre González [email protected]
## Not run: pgGetRast(conn, c("schema", "tablename")) pgGetRast(conn, c("schema", "DEM"), boundary = c(55, 50, 17, 12)) ## End(Not run)
## Not run: pgGetRast(conn, c("schema", "tablename")) pgGetRast(conn, c("schema", "DEM"), boundary = c(55, 50, 17, 12)) ## End(Not run)
This function has been deprecated in favour of pgWriteGeom()
and will be
removed in a future release.
This function takes a take an R sp
object (Spatial*
or
Spatial*DataFrame
), or a regular data.frame
, and performs the
database insert (and table creation, when the table does not exist)
on the database.
If new.id
is specified, a new sequential integer field is
added to the data frame for insert. For Spatial*
-only
objects (no data frame), a new ID column is created by default with name
"gid"
.
This function will use st_as_text for geography types, and st_as_binary for geometry types.
In the event of function or database error, the database uses ROLLBACK to revert to the previous state.
If the user specifies return.pgi = TRUE
, and data preparation is
successful, the function will return
a pgi
object (see next paragraph), regardless of whether the
insert was successful or not. This object can be useful for debugging,
or re-used as the data.obj
in pgInsert
;
(e.g., when data preparation is slow, and the exact same data
needs to be inserted into tables in two separate
tables or databases). If return.pgi = FALSE
(default), the function will return TRUE
for successful insert and
FALSE
for failed inserts.
Use this function with df.mode = TRUE
to save data frames from
Spatial*
-class objects to the database in "data frame mode". Along with normal
dbwriteDataFrame
operation, the proj4string of the spatial
data will also be saved, and re-attached to the data when using
pgGetGeom
to import the data. Note that other attributes
of Spatial*
objects are not saved (e.g., coords.nrs
,
which is used to specify the column index of x/y columns in SpatialPoints*
).
pgi objects are a list containing four character strings: (1) in.table, the table name which will be created or inserted into (2) db.new.table, the SQL statement to create the new table, (3) db.cols.insert, a character string of the database column names to insert into, and (4) insert.data, a character string of the data to insert.
pgInsert( conn, name, data.obj, geom = "geom", df.mode = FALSE, partial.match = FALSE, overwrite = FALSE, new.id = NULL, row.names = FALSE, upsert.using = NULL, alter.names = FALSE, encoding = NULL, return.pgi = FALSE, df.geom = NULL, geog = FALSE )
pgInsert( conn, name, data.obj, geom = "geom", df.mode = FALSE, partial.match = FALSE, overwrite = FALSE, new.id = NULL, row.names = FALSE, upsert.using = NULL, alter.names = FALSE, encoding = NULL, return.pgi = FALSE, df.geom = NULL, geog = FALSE )
conn |
A connection object to a PostgreSQL database |
name |
A character string specifying a PostgreSQL schema and
table name (e.g., |
data.obj |
A |
geom |
character string. For |
df.mode |
Logical; Whether to write the (Spatial) data frame in data frame mode
(preserving data frame column attributes and row.names).
A new table must be created with this mode (or overwrite set to TRUE),
and the |
partial.match |
Logical; allow insert on partial column
matches between data frame and database table. If |
overwrite |
Logical; if true, a new table ( |
new.id |
Character, name of a new sequential integer ID
column to be added to the table for insert (for spatial objects without
data frames, this column is created even if left |
row.names |
Whether to add the data frame row names to the database table. Column name will be '.R_rownames'. |
upsert.using |
Character, name of the column(s) in the database table or constraint name used to identify already-existing rows in the table, which will be updated rather than inserted. The column(s) must have a unique constraint already created in the database table (e.g., a primary key). Requires PostgreSQL 9.5+. |
alter.names |
Logical, whether to make database column names
DB-compliant (remove special characters/capitalization). Default is
|
encoding |
Character vector of length 2, containing the
from/to encodings for the data (as in the function
|
return.pgi |
Whether to return a formatted list of insert parameters
(i.e., a |
df.geom |
Character vector, name of a character column in an R data.frame
storing PostGIS geometries, this argument can be used to insert a geometry
stored as character type in a data.frame (do not use with Spatial* data types).
If only the column name is used (e.g., |
geog |
Logical; Whether to write the spatial data as a PostGIS
'GEOGRAPHY' type. By default, FALSE, unless |
Returns TRUE
if the insertion was successful,
FALSE
if failed, or a pgi
object if specified.
David Bucklin [email protected]
## Not run: library(sp) data(meuse) coords <- SpatialPoints(meuse[, c("x", "y")]) spdf <- SpatialPointsDataFrame(coords, meuse) ## Insert data in new database table pgInsert(conn, name = c("public", "meuse_data"), data.obj = spdf) ## The same command will insert into already created table (if all R ## columns match) pgInsert(conn, name = c("public", "meuse_data"), data.obj = spdf) ## If not all database columns match, need to use partial.match = TRUE, ## where non-matching columns are not inserted colnames(spdf@data)[4] <- "cu" pgInsert(conn, name = c("public", "meuse_data"), data.obj = spdf, partial.match = TRUE) ## End(Not run)
## Not run: library(sp) data(meuse) coords <- SpatialPoints(meuse[, c("x", "y")]) spdf <- SpatialPointsDataFrame(coords, meuse) ## Insert data in new database table pgInsert(conn, name = c("public", "meuse_data"), data.obj = spdf) ## The same command will insert into already created table (if all R ## columns match) pgInsert(conn, name = c("public", "meuse_data"), data.obj = spdf) ## If not all database columns match, need to use partial.match = TRUE, ## where non-matching columns are not inserted colnames(spdf@data)[4] <- "cu" pgInsert(conn, name = c("public", "meuse_data"), data.obj = spdf, partial.match = TRUE) ## End(Not run)
List all geometry/(geography) or raster columns available in a PostGIS database.
pgListGeom(conn, geog = TRUE) pgListRast(conn)
pgListGeom(conn, geog = TRUE) pgListRast(conn)
conn |
A PostgreSQL database connection. |
geog |
Logical. For pgListGeom, whether to include PostGIS geography-type columns stored in the database |
If exec = TRUE
, a data frame with schema, table,
geometry/(geography) or raster (for pgListRast) column, and geometry/(geography) type.
David Bucklin [email protected]
## Not run: pgListGeom(conn) pgListRast(conn) ## End(Not run)
## Not run: pgListGeom(conn) pgListRast(conn) ## End(Not run)
Add a new POINT or LINESTRING geometry field.
pgMakePts( conn, name, colname = "geom", x = "x", y = "y", srid, index = TRUE, display = TRUE, exec = TRUE ) pgMakeStp( conn, name, colname = "geom", x = "x", y = "y", dx = "dx", dy = "dy", srid, index = TRUE, display = TRUE, exec = TRUE )
pgMakePts( conn, name, colname = "geom", x = "x", y = "y", srid, index = TRUE, display = TRUE, exec = TRUE ) pgMakeStp( conn, name, colname = "geom", x = "x", y = "y", dx = "dx", dy = "dy", srid, index = TRUE, display = TRUE, exec = TRUE )
conn |
A connection object. |
name |
A character string specifying a PostgreSQL schema and
table name (e.g., |
colname |
A character string specifying the name of the new geometry column. |
x |
The name of the x/longitude field. |
y |
The name of the y/latitude field. |
srid |
A valid SRID for the new geometry. |
index |
Logical. Whether to create an index on the new geometry. |
display |
Logical. Whether to display the query (defaults to
|
exec |
Logical. Whether to execute the query (defaults to
|
dx |
The name of the dx field (i.e. increment in x direction). |
dy |
The name of the dy field (i.e. increment in y direction). |
If exec = TRUE
, returns TRUE
if the geometry
field was successfully created.
Mathieu Basille [email protected] and Adrián Cidre González [email protected]
The PostGIS documentation for ST_MakePoint
:
http://postgis.net/docs/ST_MakePoint.html, and for
ST_MakeLine
:
http://postgis.net/docs/ST_MakeLine.html, which are the
main functions of the call.
## Examples use a dummy connection from DBI package conn <- DBI::ANSI() ## Create a new POINT field called 'pts_geom' pgMakePts(conn, name = c("schema", "table"), colname = "pts_geom", x = "longitude", y = "latitude", srid = 4326, exec = FALSE) ## Create a new LINESTRING field called 'stp_geom' pgMakeStp(conn, name = c("schema", "table"), colname = "stp_geom", x = "longitude", y = "latitude", dx = "xdiff", dy = "ydiff", srid = 4326, exec = FALSE)
## Examples use a dummy connection from DBI package conn <- DBI::ANSI() ## Create a new POINT field called 'pts_geom' pgMakePts(conn, name = c("schema", "table"), colname = "pts_geom", x = "longitude", y = "latitude", srid = 4326, exec = FALSE) ## Create a new LINESTRING field called 'stp_geom' pgMakeStp(conn, name = c("schema", "table"), colname = "stp_geom", x = "longitude", y = "latitude", dx = "xdiff", dy = "ydiff", srid = 4326, exec = FALSE)
The function checks for the availability of the PostGIS extension, and if it is available, but not installed, install it. Additionally, can also install Topology, Tiger Geocoder, SFCGAL and Raster extensions.
pgPostGIS( conn, topology = FALSE, tiger = FALSE, sfcgal = FALSE, raster = FALSE, display = TRUE, exec = TRUE )
pgPostGIS( conn, topology = FALSE, tiger = FALSE, sfcgal = FALSE, raster = FALSE, display = TRUE, exec = TRUE )
conn |
A connection object (required, even if |
topology |
Logical. Whether to check/install the Topology extension. |
tiger |
Logical. Whether to check/install the Tiger Geocoder extension. Will also install extensions "fuzzystrmatch", "address_standardizer", and "address_standardizer_data_us" if all are available. |
sfcgal |
Logical. Whether to check/install the SFCGAL extension. |
raster |
Logical. Whether to check/install the Raster extension |
display |
Logical. Whether to display the query (defaults to
|
exec |
Logical. Whether to execute the query (defaults to
|
If exec = TRUE
, returns (invisibly) TRUE
if PostGIS is installed.
Mathieu Basille [email protected] and Adrián Cidre González [email protected]
## 'exec = FALSE' does not install any extension, but nevertheless ## check for available and installed extensions: ## Not run: pgPostGIS(con, topology = TRUE, tiger = TRUE, sfcgal = TRUE, exec = FALSE) ## End(Not run)
## 'exec = FALSE' does not install any extension, but nevertheless ## check for available and installed extensions: ## Not run: pgPostGIS(con, topology = TRUE, tiger = TRUE, sfcgal = TRUE, exec = FALSE) ## End(Not run)
This function takes sf::st_crs()
-class object and a
PostgreSQL database connection (with PostGIS extension), and
returns the matching SRID(s) for that CRS. If a match is not
found, a new entry can be created in the PostgreSQL
spatial_ref_sys
table using the parameters specified by the
CRS. New entries will be created with auth_name = 'rpostgis_custom'
, with the default value being the next open value
between 880001-889999 (a different SRID value can be entered if desired.)
pgSRID(conn, crs, create.srid = FALSE, new.srid = NULL)
pgSRID(conn, crs, create.srid = FALSE, new.srid = NULL)
conn |
A connection object to a PostgreSQL database. |
crs |
crs object, created through a call to
|
create.srid |
Logical. If no matching SRID is found, should a new
SRID be created? User must have write access on
|
new.srid |
Integer. Optional SRID to give to a newly created
SRID. If left NULL (default), the next open value of
|
SRID code (integer).
David Bucklin [email protected] and Adrián Cidre González [email protected]
## Not run: drv <- dbDriver("PostgreSQL") conn <- dbConnect(drv, dbname = "dbname", host = "host", port = "5432", user = "user", password = "password") (crs <- sf::st_crs("+proj=longlat")) pgSRID(conn, crs) (crs2 <- sf::st_crs(paste("+proj=stere", "+lat_0=52.15616055555555 +lon_0=5.38763888888889", "+k=0.999908 +x_0=155000 +y_0=463000", "+ellps=bessel", "+towgs84=565.237,50.0087,465.658,-0.406857,0.350733,-1.87035,4.0812", "+units=m"))) pgSRID(conn, crs2, create.srid = TRUE) ## End(Not run)
## Not run: drv <- dbDriver("PostgreSQL") conn <- dbConnect(drv, dbname = "dbname", host = "host", port = "5432", user = "user", password = "password") (crs <- sf::st_crs("+proj=longlat")) pgSRID(conn, crs) (crs2 <- sf::st_crs(paste("+proj=stere", "+lat_0=52.15616055555555 +lon_0=5.38763888888889", "+k=0.999908 +x_0=155000 +y_0=463000", "+ellps=bessel", "+towgs84=565.237,50.0087,465.658,-0.406857,0.350733,-1.87035,4.0812", "+units=m"))) pgSRID(conn, crs2, create.srid = TRUE) ## End(Not run)
This function takes a take an R sf
, a SpatVector
or sp
object (Spatial*
or
Spatial*DataFrame
); or a regular data.frame
, and performs the
database insert (and table creation, when the table does not exist)
on the database.
pgWriteGeom( conn, name, data.obj, geom = "geom", df.mode = FALSE, partial.match = FALSE, overwrite = FALSE, new.id = NULL, row.names = FALSE, upsert.using = NULL, alter.names = FALSE, encoding = NULL, return.pgi = FALSE, df.geom = NULL, geog = FALSE ) ## S3 method for class 'pgi' print(x, ...)
pgWriteGeom( conn, name, data.obj, geom = "geom", df.mode = FALSE, partial.match = FALSE, overwrite = FALSE, new.id = NULL, row.names = FALSE, upsert.using = NULL, alter.names = FALSE, encoding = NULL, return.pgi = FALSE, df.geom = NULL, geog = FALSE ) ## S3 method for class 'pgi' print(x, ...)
conn |
A connection object to a PostgreSQL database |
name |
A character string specifying a PostgreSQL schema and
table name (e.g., |
data.obj |
A |
geom |
character string. For |
df.mode |
Logical; Whether to write the (Spatial) data frame in data frame mode
(preserving data frame column attributes and row.names).
A new table must be created with this mode (or overwrite set to TRUE),
and the |
partial.match |
Logical; allow insert on partial column
matches between data frame and database table. If |
overwrite |
Logical; if true, a new table ( |
new.id |
Character, name of a new sequential integer ID
column to be added to the table for insert (for spatial objects without
data frames, this column is created even if left |
row.names |
Whether to add the data frame row names to the database table. Column name will be '.R_rownames'. |
upsert.using |
Character, name of the column(s) in the database table or constraint name used to identify already-existing rows in the table, which will be updated rather than inserted. The column(s) must have a unique constraint already created in the database table (e.g., a primary key). Requires PostgreSQL 9.5+. |
alter.names |
Logical, whether to make database column names
DB-compliant (remove special characters/capitalization). Default is
|
encoding |
Character vector of length 2, containing the
from/to encodings for the data (as in the function
iconv. For example, if the dataset contain certain
latin characters (e.g., accent marks), and the database is in
UTF-8, use |
return.pgi |
Whether to return a formatted list of insert parameters
(i.e., a |
df.geom |
Character vector, name of a character column in an R data.frame
storing PostGIS geometries, this argument can be used to insert a geometry
stored as character type in a data.frame (do not use with Spatial* data types).
If only the column name is used (e.g., |
geog |
Logical; Whether to write the spatial data as a PostGIS
'GEOGRAPHY' type. By default, FALSE, unless |
x |
A list of class |
... |
Further arguments not used. |
If new.id
is specified, a new sequential integer field is
added to the data frame for insert. For spatial
-only
objects (no data frame), a new ID column is created by default with name
"gid"
.
This function will use sf::st_as_text()
for geography types, and
sf::st_as_binary()
for geometry types.
In the event of function or database error, the database uses ROLLBACK to revert to the previous state.
If the user specifies return.pgi = TRUE
, and data preparation is
successful, the function will return
a pgi
object (see next paragraph), regardless of whether the
insert was successful or not. This object can be useful for debugging,
or re-used as the data.obj
in pgWriteGeom
;
(e.g., when data preparation is slow, and the exact same data
needs to be inserted into tables in two separate
tables or databases). If return.pgi = FALSE
(default), the function will return TRUE
for successful insert and
FALSE
for failed inserts.
Use this function with df.mode = TRUE
to save data frames from
spatial
-class objects to the database in "data frame mode". Along with normal
dbwriteDataFrame
operation, the proj4string of the spatial
data will also be saved, and re-attached to the data when using
pgGetGeom
to import the data. Note that other attributes
of spatial
objects are not saved (e.g., coords.nrs
,
which is used to specify the column index of x/y columns in *POINT
and
SpatialPoints*
).
pgi objects are a list containing four character strings: (1) in.table, the table name which will be created or inserted into (2) db.new.table, the SQL statement to create the new table, (3) db.cols.insert, a character string of the database column names to insert into, and (4) insert.data, a character string of the data to insert.
Returns TRUE
if the insertion was successful,
FALSE
if failed, or a pgi
object if specified.
David Bucklin [email protected] and Adrián Cidre González [email protected]
## Not run: library(sf) pts <- st_sf(a = 1:2, geom = st_sfc(st_point(0:1), st_point(1:2)), crs = 4326) ## Insert data in new database table pgWriteGeom(conn, name = c("public", "my_pts"), data.obj = pts) ## The same command will insert into already created table (if all R ## columns match) pgWriteGeom(conn, name = c("public", "my_pts"), data.obj = pts) ## If not all database columns match, need to use partial.match = TRUE, ## where non-matching columns are not inserted names(pts)[1] <- "b" pgWriteGeom(conn, name = c("public", "my_pts"), data.obj = pts, partial.match = TRUE) ## End(Not run)
## Not run: library(sf) pts <- st_sf(a = 1:2, geom = st_sfc(st_point(0:1), st_point(1:2)), crs = 4326) ## Insert data in new database table pgWriteGeom(conn, name = c("public", "my_pts"), data.obj = pts) ## The same command will insert into already created table (if all R ## columns match) pgWriteGeom(conn, name = c("public", "my_pts"), data.obj = pts) ## If not all database columns match, need to use partial.match = TRUE, ## where non-matching columns are not inserted names(pts)[1] <- "b" pgWriteGeom(conn, name = c("public", "my_pts"), data.obj = pts, partial.match = TRUE) ## End(Not run)
Sends R raster to a PostGIS database table.
pgWriteRast( conn, name, raster, bit.depth = NULL, blocks = NULL, constraints = TRUE, overwrite = FALSE, append = FALSE )
pgWriteRast( conn, name, raster, bit.depth = NULL, blocks = NULL, constraints = TRUE, overwrite = FALSE, append = FALSE )
conn |
A connection object to a PostgreSQL database. |
name |
A character string specifying a PostgreSQL schema in the
database (if necessary) and table name to hold the raster (e.g.,
|
raster |
An terra |
bit.depth |
The bit depth of the raster. Will be set to 32-bit (unsigned int, signed int, or float, depending on the data) if left null, but can be specified (as character) as one of the PostGIS pixel types (see http://postgis.net/docs/RT_ST_BandPixelType.html). |
blocks |
Optional desired number of blocks (tiles) to split the raster into in the resulting PostGIS table. This should be specified as a one or two-length (columns, rows) integer vector. See also 'Details'. |
constraints |
Whether to create constraints from raster data. Recommended
to leave |
overwrite |
Whether to overwrite the existing table ( |
append |
Whether to append to the existing table ( |
SpatRaster band names will be stored in an array in the column
"band_names", which will be restored in R when imported with the function
pgGetRast()
.
Rasters from the sp
and raster
packages are converted to
terra
objects prior to insert.
If blocks = NULL
, the number of block will vary by raster size, with
a default value of 100 copies of the data in the memory at any point in time.
If a specified number of blocks is desired, set blocks to a one or two-length
integer vector. Note that fewer, larger blocks generally results in faster
write times.
TRUE (invisibly) for successful import.
David Bucklin [email protected] and Adrián Cidre González [email protected]
Function follows process from http://postgis.net/docs/using_raster_dataman.html#RT_Creating_Rasters.
## Not run: pgWriteRast(conn, c("schema", "tablename"), raster_name) # basic test r <- terra::rast(nrows=180, ncols=360, xmin=-180, xmax=180, ymin=-90, ymax=90, vals=1) pgWriteRast(conn, c("schema", "test"), raster = r, bit.depth = "2BUI", overwrite = TRUE) ## End(Not run)
## Not run: pgWriteRast(conn, c("schema", "tablename"), raster_name) # basic test r <- terra::rast(nrows=180, ncols=360, xmin=-180, xmax=180, ymin=-90, ymax=90, vals=1) pgWriteRast(conn, c("schema", "test"), raster = r, bit.depth = "2BUI", overwrite = TRUE) ## End(Not run)