% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ogr_manage.R
\name{ogr_manage}
\alias{ogr_manage}
\alias{ogr_ds_exists}
\alias{ogr_ds_format}
\alias{ogr_ds_test_cap}
\alias{ogr_ds_create}
\alias{ogr_ds_layer_count}
\alias{ogr_ds_layer_names}
\alias{ogr_ds_field_domain_names}
\alias{ogr_ds_add_field_domain}
\alias{ogr_ds_delete_field_domain}
\alias{ogr_layer_exists}
\alias{ogr_layer_test_cap}
\alias{ogr_layer_create}
\alias{ogr_layer_field_names}
\alias{ogr_layer_rename}
\alias{ogr_layer_delete}
\alias{ogr_field_index}
\alias{ogr_field_create}
\alias{ogr_geom_field_create}
\alias{ogr_field_rename}
\alias{ogr_field_set_domain_name}
\alias{ogr_field_delete}
\alias{ogr_execute_sql}
\title{Utility functions for managing vector data sources}
\usage{
ogr_ds_exists(dsn, with_update = FALSE)

ogr_ds_format(dsn)

ogr_ds_test_cap(dsn, with_update = TRUE)

ogr_ds_create(
  format,
  dsn,
  layer = NULL,
  layer_defn = NULL,
  geom_type = NULL,
  srs = NULL,
  fld_name = NULL,
  fld_type = NULL,
  dsco = NULL,
  lco = NULL,
  overwrite = FALSE,
  return_obj = FALSE
)

ogr_ds_layer_count(dsn)

ogr_ds_layer_names(dsn)

ogr_ds_field_domain_names(dsn)

ogr_ds_add_field_domain(dsn, fld_dom_defn)

ogr_ds_delete_field_domain(dsn, domain_name)

ogr_layer_exists(dsn, layer)

ogr_layer_test_cap(dsn, layer = NULL, with_update = TRUE)

ogr_layer_create(
  dsn,
  layer,
  layer_defn = NULL,
  geom_type = NULL,
  srs = NULL,
  lco = NULL,
  return_obj = FALSE
)

ogr_layer_field_names(dsn, layer = NULL)

ogr_layer_rename(dsn, layer, new_name)

ogr_layer_delete(dsn, layer)

ogr_field_index(dsn, layer, fld_name)

ogr_field_create(
  dsn,
  layer,
  fld_name,
  fld_defn = NULL,
  fld_type = "OFTInteger",
  fld_subtype = "OFSTNone",
  fld_width = 0L,
  fld_precision = 0L,
  is_nullable = TRUE,
  is_unique = FALSE,
  default_value = "",
  domain_name = NULL
)

ogr_geom_field_create(
  dsn,
  layer,
  fld_name,
  geom_fld_defn = NULL,
  geom_type = NULL,
  srs = NULL,
  is_nullable = TRUE
)

ogr_field_rename(dsn, layer, fld_name, new_name)

ogr_field_set_domain_name(dsn, layer, fld_name, domain_name)

ogr_field_delete(dsn, layer, fld_name)

ogr_execute_sql(dsn, sql, spatial_filter = NULL, dialect = NULL)
}
\arguments{
\item{dsn}{Character string. The vector data source name, e.g., a filename
or database connection string.}

\item{with_update}{Logical value. \code{TRUE} to request update access when
opening the dataset, or \code{FALSE} to open read-only.}

\item{format}{GDAL short name of the vector format as character string.
Examples of some common output formats include: \code{"GPKG"}, \code{"FlatGeobuf"},
\code{"ESRI Shapefile"}, \code{"SQLite"}.}

\item{layer}{Character string for a layer name in a vector dataset.
The \code{layer} argument may be given as empty string (\code{""}) in which case the
first layer by index will be opened (except with \code{ogr_layer_delete()} and
\code{ogr_layer_rename()} for which a layer name must be specified).}

\item{layer_defn}{A feature class definition for \code{layer} as a list of
zero or more attribute field definitions, and at least one geometry field
definition (see \link{ogr_define}).
Each field definition is a list with named elements containing values for
the field \code{type} element and other properties.
If \code{layer_defn} is given, it will be used and any additional parameters
passed that relate to the feature class definition will be ignored (i.e.,
\code{geom_type} and \code{srs}, as well as \code{fld_name} and \code{fld_type} in
\code{ogr_ds_create()}).
The first geometry field definition in \code{layer_defn} defines the
geometry type and spatial reference system for the layer (the geom field
definition must contain \code{type}, and should also contain \code{srs} when
creating a layer from a feature class definition).}

\item{geom_type}{Character string specifying a geometry type (see Details).}

\item{srs}{Character string containing a spatial reference system definition
as OGC WKT or other well-known format (e.g., the input formats usable with
\code{\link[=srs_to_wkt]{srs_to_wkt()}}).}

\item{fld_name}{Character string containing the name of an attribute field
in \code{layer}.}

\item{fld_type}{Character string containing the name of a field data type
(e.g., \code{"OFTInteger"}, \code{"OFTInteger64"}, \code{"OFTReal"}, \code{"OFTString"}, ...).}

\item{dsco}{Optional character vector of format-specific creation options
for \code{dsn} (\code{"NAME=VALUE"} pairs).}

\item{lco}{Optional character vector of format-specific creation options
for \code{layer} (\code{"NAME=VALUE"} pairs).}

\item{overwrite}{Logical value. \code{TRUE} to overwrite \code{dsn} if it already
exists when calling \code{ogr_ds_create()}. Default is \code{FALSE}.}

\item{return_obj}{Logical value. If \code{TRUE}, an object of class
\code{\link{GDALVector}} open on the newly created layer will be
returned. Defaults to \code{FALSE}. Must be used with either the \code{layer} or
\code{layer_defn} arguments.}

\item{fld_dom_defn}{A field domain definition, i.e., a list generated with
\code{\link[=ogr_def_field_domain]{ogr_def_field_domain()}}.}

\item{domain_name}{Character string specifying the name of the field domain.}

\item{new_name}{Character string containing a new name to assign.}

\item{fld_defn}{A field definition as list (see \code{\link[=ogr_def_field]{ogr_def_field()}}).
Additional arguments in \code{ogr_field_create()} will be ignored if a \code{fld_defn}
is given.}

\item{fld_subtype}{Character string containing the name of a field subtype.
One of \code{"OFSTNone"} (the default), \code{"OFSTBoolean"}, \code{"OFSTInt16"},
\code{"OFSTFloat32"}, \code{"OFSTJSON"}, \code{"OFSTUUID"}.}

\item{fld_width}{Optional integer value specifying max number of characters.}

\item{fld_precision}{Optional integer value specifying number of digits
after the decimal point.}

\item{is_nullable}{Optional NOT NULL field constraint (logical value).
Defaults to \code{TRUE}.}

\item{is_unique}{Optional UNIQUE constraint on the field (logical value).
Defaults to \code{FALSE}.}

\item{default_value}{Optional default value for the field as a character
string.}

\item{geom_fld_defn}{A geometry field definition as list (see
\code{\link[=ogr_def_geom_field]{ogr_def_geom_field()}}). Additional arguments in \code{ogr_geom_field_create()}
will be ignored if a \code{geom_fld_defn} is given.}

\item{sql}{Character string containing an SQL statement (see Note).}

\item{spatial_filter}{Either a numeric vector of length four containing a
bounding box (xmin, ymin, xmax, ymax), or a character string containing a
geometry as OGC WKT, representing a spatial filter.}

\item{dialect}{Character string specifying the SQL dialect to use.
The OGR SQL engine (\code{"OGRSQL"}) will be used by default if a value is not
given. The \code{"SQLite"} dialect can also be used (see Note).}
}
\description{
This set of functions can be used to create new vector datasets,
test existence of dataset/layer/field, test dataset and layer capabilities,
create new layers in an existing dataset, get the names of field domains
stored in a dataset, write field domains in a dataset, delete layers, create
new attribute and geometry fields on an existing layer, rename and delete
fields, and edit data with SQL statements.
}
\details{
These functions are complementary to \code{ogrinfo()} and \code{ogr2ogr()} for
vector data management. Bindings to OGR wrap portions of the GDAL
Vector API (ogr_core.h and ogr_api.h,
\url{https://gdal.org/en/stable/api/vector_c_api.html}).

\code{ogr_ds_exists()} tests whether a vector dataset can be opened from the
given data source name (DSN), potentially testing for update access.
Returns a logical value.

\code{ogr_ds_format()} returns a character string containing the short name of
the format driver for a given DSN, or \code{NULL} if the dataset cannot be
opened as a vector source.

\code{ogr_ds_test_cap()} tests the capabilities of a vector data source,
attempting to open it with update access by default.
Returns a list of capabilities with values \code{TRUE} or \code{FALSE}, or \code{NULL} is
returned if \code{dsn} cannot be opened with the requested access.
Wrapper of \code{GDALDatasetTestCapability()} in the GDAL API.
The returned list contains the following named elements:
\itemize{
\item \code{CreateLayer}: \code{TRUE} if this dataset can create new layers
\item \code{DeleteLayer}: \code{TRUE} if this dataset can delete existing layers
\item \code{CreateGeomFieldAfterCreateLayer}: \code{TRUE} if the layers of this
dataset supports geometry field creation just after layer creation
\item \code{CurveGeometries}: \code{TRUE} if this dataset supports curve geometries
\item \code{Transactions}: \code{TRUE} if this dataset supports (efficient)
transactions
\item \code{EmulatedTransactions}: \code{TRUE} if this dataset supports transactions
through emulation
\item \code{RandomLayerRead}: \code{TRUE} if this dataset has a dedicated
\code{GetNextFeature()} implementation, potentially returning features from
layers in a non-sequential way
\item \code{RandomLayerWrite}: \code{TRUE} if this dataset supports calling
\code{CreateFeature()} on layers in a non-sequential way
\item \code{AddFieldDomain}: \code{TRUE} if this dataset supports adding field domains
(GDAL >= 3.3)
\item \code{DeleteFieldDomain}: \code{TRUE} if this dataset supports deleting field
domains (GDAL >= 3.5)
\code{UpdateFieldDomain}: \code{TRUE} if this dataset supports updating a an existing
field domain by replacing its definition (GDAL >= 3.5)
}

\code{ogr_ds_create()} creates a new vector dataset, optionally also creating
a layer, and optionally creating one or more fields on the layer.
The attribute fields and geometry field(s) to create can be specified as a
feature class definition (\code{layer_defn} as list, see \link{ogr_define}), or
alternatively, by giving the \code{geom_type} and \code{srs}, optionally along with
one \code{fld_name} and \code{fld_type} to be created in the layer.
By default, returns logical \code{TRUE} indicating success (output written to
\code{dst_filename}), or an object of class \code{\link{GDALVector}} for the
output layer will be returned if \code{return_obj = TRUE}. An error is raised if
the operation fails.

\code{ogr_ds_layer_count()} returns the number of layers in a vector dataset.

\code{ogr_ds_layer_names()} returns a character vector of layer names in a
vector dataset, or \code{NULL} if no layers are found.

\code{ogr_ds_field_domain_names()} returns a character vector with the names of
all field domains stored in the dataset. Returns \code{NULL} and emits a warning
if an error occurs or if the format does not support reading field domains.
Returns a character vector of length 0 (\code{character(0)}) if the format
supports field domains but none are present in the dataset.
Requires GDAL >= 3.5. See \link{ogr_define} for information on field domains.

\code{ogr_ds_add_field_domain()} adds a field domain to a vector dataset. Only a
few drivers will support this operation, and some of them might only support
it only for some types of field domains. GeoPackage and OpenFileGDB drivers
support this operation. A dataset having at least some support should report
the \code{AddFieldDomain} dataset capability (see \code{ogr_ds_test_cap()}above).
Returns a logical value, \code{TRUE} indicating success. Requires GDAL >= 3.3.

\code{ogr_ds_delete_field_domain()} deletes a field domain from a vector dataset
if supported (see \code{ogr_ds_test_cap()}above for the \code{DeleteFieldDomain}
dataset capability). Returns a logical value, \code{TRUE} indicating success.
Requires GDAL >= 3.5.

\code{ogr_layer_exists()} tests whether a layer can be accessed by name in a
given vector dataset. Returns a logical value

\code{ogr_layer_test_cap()} tests whether a layer supports named capabilities,
attempting to open the dataset with update access by default.
Returns a list of capabilities with values \code{TRUE} or \code{FALSE}. \code{NULL} is
returned if \code{dsn} cannot be opened with the requested access, or \code{layer}
cannot be found. The returned list contains the following named elements:
\code{RandomRead}, \code{SequentialWrite}, \code{RandomWrite}, \code{UpsertFeature},
\code{FastSpatialFilter}, \code{FastFeatureCount}, \code{FastGetExtent},
\code{FastSetNextByIndex}, \code{CreateField}, \code{CreateGeomField}, \code{DeleteField},
\code{ReorderFields}, \code{AlterFieldDefn}, \code{AlterGeomFieldDefn}, \code{IgnoreFields},
\code{DeleteFeature}, \code{Rename}, \code{StringsAsUTF8}, \code{CurveGeometries}.
See the GDAL documentation for
\href{https://gdal.org/en/stable/api/vector_c_api.html#_CPPv420OGR_L_TestCapability9OGRLayerHPKc}{\code{OGR_L_TestCapability()}}.

\code{ogr_layer_create()} creates a new layer in an existing vector data source,
with a specified geometry type and spatial reference definition.
This function also accepts a feature class definition given as a list of
field names and their definitions (see \link{ogr_define}).
(Note: use \code{ogr_ds_create()} to create single-layer formats such as "ESRI
Shapefile", "FlatGeobuf", "GeoJSON", etc.)
By default, returns logical \code{TRUE} indicating success, or an object of class
\code{\link{GDALVector}} will be returned if \code{return_obj = TRUE}.
An error is raised if the operation fails.

\code{ogr_layer_field_names()} returns a character vector of field names on a
layer, or \code{NULL} if no fields are found. The first layer by index is opened
if \code{NULL} is given for the \code{layer} argument.

\code{ogr_layer_rename()} renames a layer in a vector dataset. This operation is
implemented only by layers that expose the \code{Rename} capability (see
\code{ogr_layer_test_cap()} above). This operation will fail if a layer with the
new name already exists. Returns a logical value, \code{TRUE} indicating success.
Requires GDAL >= 3.5.

\code{ogr_layer_delete()} deletes an existing layer in a vector dataset.
Returns a logical value, \code{TRUE} indicating success.

\code{ogr_field_index()} tests for existence of an attribute field by name.
Returns the field index on the layer (0-based), or \code{-1} if the field does
not exist.

\code{ogr_field_create()} creates a new attribute field of specified data type in
a given DSN/layer. Several optional field properties can be specified in
addition to the type. Returns a logical value, \code{TRUE} indicating success.

\code{ogr_geom_field_create()} creates a new geometry field of specified type in
a given DSN/layer. Returns a logical value, \code{TRUE} indicating success.

\code{ogr_field_rename()} renames an existing field on a vector layer.
Not all format drivers support this function. Some drivers may only support
renaming a field while there are still no features in the layer.
\code{AlterFieldDefn} is the relevant layer capability to check.
Returns a logical value, \code{TRUE} indicating success.

\code{ogr_field_set_domain_name()} sets the field domain name for an existing
attribute field on a vector layer. \code{AlterFieldDefn} layer capability is
required. Returns a logical value, \code{TRUE} indicating success.
Requires GDAL >= 3.3.

\code{ogr_field_delete()} deletes an existing field on a vector layer.
Not all format drivers support this function. Some drivers may only support
deleting a field while there are still no features in the layer.
Returns a logical value, \code{TRUE} indicating success.

\code{ogr_execute_sql()} executes an SQL statement against the data store.
This function can be used to modify the schema or edit data using SQL
(e.g., \verb{ALTER TABLE}, \verb{DROP TABLE}, \verb{CREATE INDEX}, \verb{DROP INDEX}, \code{INSERT},
\code{UPDATE}, \code{DELETE}), or to execute a query (i.e., \code{SELECT}).
Returns \code{NULL} (invisibly) for statements that are in error, or that have no
results set, or an object of class \code{GDALVector} representing a results set
from the query. Wrapper of \code{GDALDatasetExecuteSQL()} in the GDAL API.
}
\note{
The OGR SQL document linked under \strong{See Also} contains information on the
SQL dialect supported internally by GDAL/OGR. Some format drivers (e.g.,
PostGIS) pass the SQL directly through to the underlying RDBMS (unless
\code{OGRSQL} is explicitly passed as the dialect). The SQLite dialect can also
be requested with the \code{SQLite} string passed as the \code{dialect} argument of
\code{ogr_execute_sql()}. This assumes that GDAL/OGR is built with support for
SQLite, and preferably also with Spatialite support to benefit from spatial
functions. The GDAL document for SQLite dialect has detailed information.

Other SQL dialects may also be present for some vector formats.
For example, the \code{"INDIRECT_SQLITE"} dialect might potentially be used with
GeoPackage format (\url{https://gdal.org/en/stable/drivers/vector/gpkg.html#sql}).

The function \code{\link[=ogrinfo]{ogrinfo()}} can also be used to edit data with SQL statements
(GDAL >= 3.7).

The name of the geometry column of a layer is empty (\code{""}) with some formats
such as ESRI Shapefile and FlatGeobuf. Implications for SQL may depend on the
dialect used. See the GDAL documentation for the "OGR SQL" and "SQLite"
dialects for details.
}
\examples{
## Create GeoPackage and manage schema
dsn <- file.path(tempdir(), "test1.gpkg")
ogr_ds_create("GPKG", dsn)
ogr_ds_exists(dsn, with_update = TRUE)
# dataset capabilities
ogr_ds_test_cap(dsn)

ogr_layer_create(dsn, layer = "layer1", geom_type = "Polygon",
                 srs = "EPSG:5070")

ogr_field_create(dsn, layer = "layer1",
                 fld_name = "field1",
                 fld_type = "OFTInteger64",
                 is_nullable = FALSE)
ogr_field_create(dsn, layer = "layer1",
                 fld_name = "field2",
                 fld_type = "OFTString")

ogr_ds_layer_count(dsn)
ogr_ds_layer_names(dsn)
ogr_layer_field_names(dsn, layer = "layer1")

# delete a field
if (ogr_layer_test_cap(dsn, "layer1")$DeleteField) {
  ogr_field_delete(dsn, layer = "layer1", fld_name = "field2")
}

ogr_layer_field_names(dsn, "layer1")

# define a feature class and create layer
defn <- ogr_def_layer("Point", srs = epsg_to_wkt(4326))
# add the attribute fields
defn$id_field <- ogr_def_field(fld_type = "OFTInteger64",
                               is_nullable = FALSE,
                               is_unique = TRUE)
defn$str_field <- ogr_def_field(fld_type = "OFTString",
                                fld_width = 25,
                                is_nullable = FALSE,
                                default_value = "'a default string'")
defn$numeric_field <- ogr_def_field(fld_type = "OFTReal",
                                    default_value = "0.0")

ogr_layer_create(dsn, layer = "layer2", layer_defn = defn)
ogr_ds_layer_names(dsn)
ogr_layer_field_names(dsn, layer = "layer2")

# add a field using SQL instead
ogr_execute_sql(dsn, sql = "ALTER TABLE layer2 ADD field4 float")

# rename a field
if (ogr_layer_test_cap(dsn, "layer1")$AlterFieldDefn) {
  ogr_field_rename(dsn, layer = "layer2",
                   fld_name = "field4",
                   new_name = "renamed_field")
}
ogr_layer_field_names(dsn, layer = "layer2")

# GDAL >= 3.7
if (gdal_version_num() >= gdal_compute_version(3, 7, 0))
  ogrinfo(dsn, "layer2")

\dontshow{deleteDataset(dsn)}
## Edit data using SQL
src <- system.file("extdata/ynp_fires_1984_2022.gpkg", package="gdalraster")
perims_shp <- file.path(tempdir(), "mtbs_perims.shp")
ogr2ogr(src_dsn = src, dst_dsn = perims_shp, src_layers = "mtbs_perims")
ogr_ds_format(dsn = perims_shp)
ogr_ds_layer_names(dsn = perims_shp)
ogr_layer_field_names(dsn = perims_shp, layer = "mtbs_perims")

alt_tbl <- "ALTER TABLE mtbs_perims ADD burn_bnd_ha float"
ogr_execute_sql(dsn = perims_shp, sql = alt_tbl)

upd <- "UPDATE mtbs_perims SET burn_bnd_ha = (burn_bnd_ac / 2.471)"
ogr_execute_sql(dsn = perims_shp, sql = upd, dialect = "SQLite")
ogr_layer_field_names(dsn = perims_shp, layer = "mtbs_perims")

# if GDAL >= 3.7:
#   ogrinfo(dsn = perims_shp, layer = "mtbs_perims")
# or, for output incl. the feature data (omit the default "-so" arg):
#   ogrinfo(dsn = perims_shp, layer = "mtbs_perims", cl_arg = "-nomd")
\dontshow{deleteDataset(perims_shp)}
}
\seealso{
OGR SQL dialect and SQLite SQL dialect:\cr
\url{https://gdal.org/en/stable/user/ogr_sql_sqlite_dialect.html}
}
