Struct gdal::Transaction

source ·
pub struct Transaction<'a> { /* private fields */ }
Expand description

Represents an in-flight transaction on a dataset.

It can either be committed by calling commit or rolled back by calling rollback.

If the transaction is not explicitly committed when it is dropped, it is implicitly rolled back.

The transaction holds a mutable borrow on the Dataset that it was created from, so during the lifetime of the transaction you will need to access the dataset by dereferencing the Transaction through its Deref or DerefMut implementations.

Implementations§

source§

impl<'a> Transaction<'a>

source

pub fn dataset(&self) -> &Dataset

👎Deprecated: Transaction now implements Deref<Target = Dataset>, so you can call Dataset methods on it directly. Use .deref() if you need a reference to the underlying Dataset.

Returns a reference to the dataset from which this Transaction was created.

source

pub fn dataset_mut(&mut self) -> &mut Dataset

👎Deprecated: Transaction now implements DerefMut<Target = Dataset>, so you can call Dataset methods on it directly. Use .deref_mut() if you need a mutable reference to the underlying Dataset.

Returns a mutable reference to the dataset from which this Transaction was created.

source

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

Commits this transaction.

If the commit fails, will return OGRErr::OGRERR_FAILURE.

Depending on drivers, this may or may not abort layer sequential readings that are active.

source

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

Rolls back the dataset to its state before the start of this transaction.

If the rollback fails, will return OGRErr::OGRERR_FAILURE.

Methods from Deref<Target = 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 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 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 layer_by_name(&self, name: &str) -> Result<Layer<'_>>

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

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<'a> Debug for Transaction<'a>

source§

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

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

impl<'a> Deref for Transaction<'a>

§

type Target = Dataset

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl<'a> DerefMut for Transaction<'a>

source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
source§

impl<'a> Drop for Transaction<'a>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<'a> RefUnwindSafe for Transaction<'a>

§

impl<'a> Send for Transaction<'a>

§

impl<'a> !Sync for Transaction<'a>

§

impl<'a> Unpin for Transaction<'a>

§

impl<'a> !UnwindSafe for Transaction<'a>

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.