Struct gdal::Dataset

source ·
pub struct Dataset { /* private fields */ }
Expand description

Wrapper around a GDALDataset object.

Represents both a vector dataset containing a collection of layers; and a raster dataset containing a collection of raster-bands.

Implementations§

source§

impl Dataset

source

pub unsafe fn c_dataset(&self) -> GDALDatasetH

Returns the wrapped C pointer

Safety

This method returns a raw C pointer

source

pub fn open<P: AsRef<Path>>(path: P) -> Result<Dataset>

Open a dataset at the given path with default options.

source

pub fn open_ex<P: AsRef<Path>>( path: P, options: DatasetOptions<'_> ) -> Result<Dataset>

Open a dataset with extended options. See GDALOpenEx.

source

pub fn flush_cache(&mut self) -> Result<()>

Flush all write cached data to disk.

See [GDALFlushCache].

Note: on GDAL versions older than 3.7, this function always succeeds.

source

pub fn close(self) -> Result<()>

Close the dataset.

See [GDALClose].

Note: on GDAL versions older than 3.7.0, this function always succeeds.

source

pub unsafe fn from_c_dataset(c_dataset: GDALDatasetH) -> Dataset

Creates a new Dataset by wrapping a C pointer

Safety

This method operates on a raw C pointer The dataset must not have been closed (using [GDALClose]) before.

source

pub fn projection(&self) -> String

Fetch the projection definition string for this dataset.

source

pub fn set_projection(&mut self, projection: &str) -> Result<()>

Set the projection reference string for this dataset.

source

pub fn spatial_ref(&self) -> Result<SpatialRef>

Get the spatial reference system for this dataset.

source

pub fn set_spatial_ref(&mut self, spatial_ref: &SpatialRef) -> Result<()>

Set the spatial reference system for this dataset.

source

pub fn create_copy<P: AsRef<Path>>( &self, driver: &Driver, filename: P, options: &[RasterCreationOption<'_>] ) -> Result<Dataset>

source

pub fn driver(&self) -> Driver

Fetch the driver to which this dataset relates.

source

pub fn rasterband(&self, band_index: isize) -> Result<RasterBand<'_>>

Fetch a band object for a dataset.

Applies to raster datasets, and fetches the rasterband at the given 1-based index.

source

pub fn root_group(&self) -> Result<Group<'_>>

Opens the root group of a multi-dim GDAL raster

Note

You must have opened the dataset with the GdalOpenFlags::GDAL_OF_MULTIDIM_RASTER flag in order for it to work.

source

pub fn build_overviews( &mut self, resampling: &str, overviews: &[i32], bands: &[i32] ) -> Result<()>

Builds overviews for the current Dataset. See GDALBuildOverviews.

Arguments
  • resampling - resampling method, as accepted by GDAL, e.g. "CUBIC"
  • overviews - list of overview decimation factors, e.g. &[2, 4, 8, 16, 32]
  • bands - list of bands to build the overviews for, or empty for all bands
source

pub fn layer_count(&self) -> isize

Get the number of layers in this dataset.

source

pub fn layer(&self, idx: isize) -> Result<Layer<'_>>

Fetch a layer by index.

Applies to vector datasets, and fetches by the given 0-based index.

source

pub fn into_layer(self, idx: isize) -> Result<OwnedLayer>

Fetch a layer by index.

Applies to vector datasets, and fetches by the given 0-based index.

source

pub fn layer_by_name(&self, name: &str) -> Result<Layer<'_>>

Fetch a layer by name.

source

pub fn into_layer_by_name(self, name: &str) -> Result<OwnedLayer>

Fetch a layer by name.

source

pub fn layers(&self) -> LayerIterator<'_>

Returns an iterator over the layers of the dataset.

source

pub fn raster_count(&self) -> isize

Fetch the number of raster bands on this dataset.

source

pub fn raster_size(&self) -> (usize, usize)

Returns the raster dimensions: (width, height).

source

pub fn create_layer(&mut self, options: LayerOptions<'_>) -> Result<Layer<'_>>

Creates a new layer. The LayerOptions struct implements Default, so you only need to specify those options that deviate from the default.

Examples

Create a new layer with an empty name, no spatial reference, and unknown geometry type:

let blank_layer = dataset.create_layer(Default::default()).unwrap();

Create a new named line string layer using WGS84:

let roads = dataset.create_layer(LayerOptions {
    name: "roads",
    srs: Some(&SpatialRef::from_epsg(4326).unwrap()),
    ty: gdal_sys::OGRwkbGeometryType::wkbLineString,
    ..Default::default()
}).unwrap();
source

pub fn set_geo_transform(&mut self, transformation: &GeoTransform) -> Result<()>

Set the Dataset’s affine transformation; also called a geo-transformation.

This is like a linear transformation preserves points, straight lines and planes. Also, sets of parallel lines remain parallel after an affine transformation.

Arguments
  • transformation - coefficients of the transformation, which are:
    • x-coordinate of the top-left corner pixel (x-offset)
    • width of a pixel (x-resolution)
    • row rotation (typically zero)
    • y-coordinate of the top-left corner pixel
    • column rotation (typically zero)
    • height of a pixel (y-resolution, typically negative)
source

pub fn geo_transform(&self) -> Result<GeoTransform>

Get the coefficients of the Dataset’s affine transformation.

Returns
  • x-coordinate of the top-left corner pixel (x-offset)
  • width of a pixel (x-resolution)
  • row rotation (typically zero)
  • y-coordinate of the top-left corner pixel
  • column rotation (typically zero)
  • height of a pixel (y-resolution, typically negative)
source

pub fn start_transaction(&mut self) -> Result<Transaction<'_>>

For datasources which support transactions, this creates a transaction.

Because the transaction implements DerefMut, it can be used in place of the original Dataset to make modifications. All changes done after the start of the transaction are applied to the datasource when commit is called. They may be canceled by calling rollback instead, or by dropping the Transaction without calling commit.

Depending on the driver, using a transaction can give a huge performance improvement when creating a lot of geometry at once. This is because the driver doesn’t need to commit every feature to disk individually.

If starting the transaction fails, this function will return OGRErr::OGRERR_FAILURE. For datasources that do not support transactions, this function will always return OGRErr::OGRERR_UNSUPPORTED_OPERATION.

Limitations:

  • Datasources which do not support efficient transactions natively may use less efficient emulation of transactions instead; as of GDAL 3.1, this only applies to the closed-source FileGDB driver, which (unlike OpenFileGDB) is not available in a GDAL build by default.

  • At the time of writing, transactions only apply on vector layers.

  • Nested transactions are not supported.

  • If an error occurs after a successful start_transaction, the whole transaction may or may not be implicitly canceled, depending on the driver. For example, the PG driver will cancel it, but the SQLite and GPKG drivers will not.

Example:

fn create_point_grid(dataset: &mut Dataset) -> gdal::errors::Result<()> {
    use gdal::vector::Geometry;

    // Start the transaction.
    let mut txn = dataset.start_transaction()?;

    let mut layer = txn.create_layer(LayerOptions {
        name: "grid",
        ty: gdal_sys::OGRwkbGeometryType::wkbPoint,
        ..Default::default()
    })?;
    for y in 0..100 {
        for x in 0..100 {
            let wkt = format!("POINT ({} {})", x, y);
            layer.create_feature(Geometry::from_wkt(&wkt)?)?;
        }
    }

    // We got through without errors. Commit the transaction and return.
    txn.commit()?;
    Ok(())
}
source

pub fn execute_sql<S: AsRef<str>>( &self, query: S, spatial_filter: Option<&Geometry>, dialect: Dialect ) -> Result<Option<ResultSet<'_>>>

Execute a SQL query against the Dataset. It is equivalent to calling GDALDatasetExecuteSQL. Returns a sql::ResultSet, which can be treated just as any other Layer.

Queries such as ALTER TABLE, CREATE INDEX, etc. have no sql::ResultSet, and return None, which is distinct from an empty sql::ResultSet.

Arguments
Example
use gdal::vector::sql;
use gdal::vector::LayerAccess;

let ds = Dataset::open(Path::new("fixtures/roads.geojson")).unwrap();
let query = "SELECT kind, is_bridge, highway FROM roads WHERE highway = 'pedestrian'";
let mut result_set = ds.execute_sql(query, None, sql::Dialect::DEFAULT).unwrap().unwrap();

assert_eq!(10, result_set.feature_count());

for feature in result_set.features() {
    let highway = feature
        .field("highway")
        .unwrap()
        .unwrap()
        .into_string()
        .unwrap();

    assert_eq!("pedestrian", highway);
}
source§

impl Dataset

source

pub fn gcp_spatial_ref(&self) -> Option<SpatialRef>

Get output spatial reference system for GCPs.

Notes
  • This is separate and distinct from Dataset::spatial_ref, and only applies to the representation of ground control points, when embedded.

See: GDALGetGCPSpatialRef

source

pub fn gcp_projection(&self) -> Option<String>

Get the projection definition string for the GCPs in this dataset.

Notes

See: GDALGetGCPProjection

source

pub fn gcps(&self) -> &[GcpRef<'_>]

Fetch GCPs.

See: GDALDataset::GetGCPs

source

pub fn set_gcps(&self, gcps: Vec<Gcp>, spatial_ref: &SpatialRef) -> Result<()>

Assign GCPs.

This method assigns the passed set of GCPs to this dataset, as well as setting their coordinate system.

See: GDALDataset::SetGCPs(int, const GDAL_GCP *, const OGRSpatialReference *)

Panics

Panics if gcps has more than libc::c_int::MAX elements.

Trait Implementations§

source§

impl Debug for Dataset

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Drop for Dataset

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl From<Dataset> for MultiDimTranslateDestination

source§

fn from(dataset: Dataset) -> Self

Converts to this type from the input type.
source§

impl From<OwnedLayer> for Dataset

source§

fn from(owned_layer: OwnedLayer) -> Self

Converts to this type from the input type.
source§

impl Metadata for Dataset

source§

fn description(&self) -> Result<String>

For most crate::Datasets, method returns this is the originating filename. For crate::raster::RasterBands it is a description (if supported) or "". Read more
source§

fn metadata_domains(&self) -> Vec<String>

Metadata in GDAL is partitioned into namespaces, knows as “domains” in the GDAL Data Model. GDAL types with metadata (a.k.a. “Major Objects”) have a default or “root” domain identified by the empty string (""). Specific “Major Object” types may have other conventionally recognized domains. For example, in raster Datasets you may come across the domains SUBDATASETS, IMAGE_STRUCTURE, RPC, IMAGERY, xml:, etc. Read more
source§

fn metadata_domain(&self, domain: &str) -> Option<Vec<String>>

Get all the metadata values within the given domain. Returns None if domain is not defined. Entries in the returned Vec<String> are formatted as “Name=value” pairs Read more
source§

fn metadata_item(&self, key: &str, domain: &str) -> Option<String>

Get a single metadata entry, as indicated by key and domain. Read more
source§

fn set_metadata_item( &mut self, key: &str, value: &str, domain: &str ) -> Result<()>

Set a metadata item in given domain at given key. Read more
source§

fn set_description(&mut self, description: &str) -> Result<()>

For Datasets this sets the dataset name; normally application code should not set the “description” for GDALDatasets. For RasterBands it is actually a description (if supported) or "".
source§

fn metadata(&self) -> MetadataIter<'_>where Self: Sized,

Get an iterator over metadata entries, across all domains. Read more
source§

impl Send for Dataset

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.