OgrDatasource Class Reference

Represents GDAL/OGR vector datasource which may be represented by spatial database or file-based vector format. More...

Collaboration diagram for OgrDatasource:
Collaboration graph

Public Member Functions

void Close ()
 Closes datasource and underlying connection. More...
 
bool CreateLayer (string layerName, ShpfileType ShpType, GeoProjection Projection=null, string creationOptions="")
 Creates a new empty layer in the datasource. More...
 
bool DeleteLayer (int layerIndex)
 Deletes a layer with specified index from datasource. More...
 
bool ExecuteSQL (string sql, out string errorMessage)
 Executes SQL statement against datasource. More...
 
string get_DriverMetadata (tkGdalDriverMetadata metadata)
 Returns certain type of metadata associated with current driver. More...
 
string get_DriverMetadataItem (int metadataIndex)
 Gets metadata item with specified index associated with current driver. More...
 
string get_ErrorMsg (int ErrorCode)
 Gets the description of the specific error code. More...
 
OgrLayer GetLayer (int Index, bool forUpdate=false)
 Gets a layer with specified index from datasource. More...
 
OgrLayer GetLayer2 (int Index, bool forUpdate, bool newConnection)
 
OgrLayer GetLayerByName (string layerName, bool forUpdate=false)
 Gets a layer with specified name from the datasource. More...
 
string GetLayerName (int layerIndex)
 Gets a name of the layer with particular index. More...
 
object GetSchemas ()
 Gets the array with schema names in the datasources. More...
 
bool ImportShapefile (Shapefile shapefile, string layerName, string creationOptions="", tkShapeValidationMode validationMode=tkShapeValidationMode.TryFixSkipOnFailure)
 Creates a new layer in the datasource and populates it with data from specified shapefile. More...
 
int LayerIndexByName (string layerName)
 Returns index of layer with the specified name. More...
 
bool Open (string connectionString)
 Opens particular type of datasource supported by GDAL/OGR. More...
 
bool Open2 (string connectionString, bool forUpdate)
 Opens particular type of datasource supported by GDAL/OGR. More...
 
OgrLayer RunQuery (string sql)
 Runs a query against datasource and returns the result as a temporary layer. More...
 
bool TestCapability (tkOgrDSCapability capability)
 Test whether driver of the currently opened datasource supports particular capability. More...
 

Properties

int DriverMetadataCount [get]
 Gets the number of metadata items associated with current driver. More...
 
string DriverName [get]
 Gets name driver (name of format) for this datasource. More...
 
string GdalLastErrorMsg [get]
 Extracts the last error message reported by GDAL library. More...
 
ICallback GlobalCallback [get, set]
 Gets or sets a Callback object which handles progress and error messages. More...
 
string Key [get, set]
 Gets or sets a text string associated with object. Any value can be stored by developer in this property. More...
 
int LastErrorCode [get]
 Gets code of the last error which took place inside this object. More...
 
int LayerCount [get]
 Gets number of layers in the datasource. More...
 

Detailed Description

Represents GDAL/OGR vector datasource which may be represented by spatial database or file-based vector format.

The class can be used to access various vector datasources supported by GDAL/OGR. Depending on driver, datasources may be represented by particular file formats ( ESRI Shapefile, MapInfo TAB, KML, etc) or spatial databases (PostGIS, Microsoft SQL Server, SpatiaLite, etc). See the full list of formats in GDAL documentation.

dot_inline_dotgraph_51.png

OgrDatasource can be used for such tasks as:

An instance of OgrDatasource can't be added to the map directly, but instances of OgrLayer class opened by its methods can.

OgrDatasource encapsulates an instance of GDALDataset C++ class. Check its documentation to better understand what's going on under the hood.

Here is code sample which lists all layers available in PostGIS database.

private static string CONNECTION_STRING = "PG:host=localhost dbname=london user=postgres password=1234";
var ds = new OgrDatasource();
if (!ds.Open(CONNECTION_STRING))
{
Debug.Print("Failed to establish connection: " + ds.GdalLastErrorMsg);
}
else
{
int count = ds.LayerCount;
Debug.Print("Number of layers: " + count);
Debug.Print("List of layers by name:");
for (int i = 0; i < count; i++)
{
var lyr = ds.GetLayer(i);
Debug.Print("Layer name: " + lyr.Name);
Debug.Print("Projection: " + lyr.GeoProjection.ExportToProj4());
Debug.Print("Shape type: " + lyr.ShapeType);
lyr.Close();
}
ds.Close();
}

See more samples in description of particular methods.

String encoding.
OgrDatasource and OgrLayer classes by default use UTF-8 string encoding to interact with underlying drivers. This applies to connection strings, layer names, SQL queries and error messages. This behavior can be changed by setting GlobalSettings.OgrStringEncoding property. The new setting will be used immediately by all existing and new objects. See details about string encoding in the documentation of particular OGR driver.

Here is a diagram for the OgrDatasource class.

dot_inline_dotgraph_52.png

Graph description

New API 4.9.3:
Added in version 4.9.3

Member Function Documentation

◆ Close()

void OgrDatasource.Close ( )

Closes datasource and underlying connection.

This method should be called as soon as datasource is no longer needed.

◆ CreateLayer()

bool OgrDatasource.CreateLayer ( string  layerName,
ShpfileType  ShpType,
GeoProjection  Projection = null,
string  creationOptions = "" 
)

Creates a new empty layer in the datasource.

SRID will be set to 0 if null or empty GeoProjection object is passed. See OgrDatasource.ImportShapefile for the details on creation options.
Known issues: creation of layer in nonexistent schema in PostGIS databases completes successfully, yet the neither schema nor objects in it are visible afterwards.

Parameters
layerNameName of the new layer.
ShpTypeShpType of the new layer. Will be converted to appropriate OGRwkbGeometryType.
ProjectionGeoProjection object which sets SRID of the new layer.
creationOptionsFormat specific creation options separated with semicolon, e.g. "OVERWRITE=YES;MW_MULTI_PART=no".
Returns
True on success.

◆ DeleteLayer()

bool OgrDatasource.DeleteLayer ( int  layerIndex)

Deletes a layer with specified index from datasource.

Use OgrDatasource.TestCapability(tkOgrDSCapability.odcDeleteLayer) to check whether functionality is supported by particular driver.

Parameters
layerIndexLayer index within datasource.
Returns
True on success.

◆ ExecuteSQL()

bool OgrDatasource.ExecuteSQL ( string  sql,
out string  errorMessage 
)

Executes SQL statement against datasource.

Should be used for non-SELECT instructions which don't return resulting set of rows. To select data use OgrDatasource.RunQuery instead.


Parameters
sqlSQL instruction.
errorMessageError message provided in case of failure.
Returns
True on success and false otherwise.

The following code deletes records from underlying database table with gid > 100.

var ds = new OgrDatasource();
if (!ds.Open(CONNECTION_STRING))
{
Debug.Pring("Failed to establish connection: " + ds.GdalLastErrorMsg);
}
else
{
string errorMsg;
bool result = ds.ExecuteSQL("DELETE FROM tableName WHERE gid > 100", out errorMsg);
if (!result)
{
Debug.Pring("Error on running SQL: " + errorMsg);
}
else
{
Debug.Pring("SQL was executed successfully.");
}
ds.Close();
}

◆ get_DriverMetadata()

string OgrDatasource.get_DriverMetadata ( tkGdalDriverMetadata  metadata)

Returns certain type of metadata associated with current driver.

Parameters
metadataType of metadata to be returned.
Returns
Metadata or empty string if requested type of metadata isn't set for the driver.
var ds = new OgrDatasource();
if (!ds.Open(CONNECTION_STRING))
{
Debug.Print("Failed to establish connection: " + ds.GdalLastErrorMsg);
}
else
{
// first display couple of specific items
Debug.Print("Layer creation options: " + ds.get_DriverMetadata(tkGdalDriverMetadata.dmdLAYER_CREATIONOPTIONLIST));
Debug.Print("Long name: " + ds.get_DriverMetadata(tkGdalDriverMetadata.dmdLONGNAME));
// now display all the available items
Debug.Print("Metadata items: ");
for (int i = 0; i < ds.DriverMetadataCount; i++)
{
Debug.Print(ds.get_DriverMetadataItem(i));
}
ds.Close();
}

◆ get_DriverMetadataItem()

string OgrDatasource.get_DriverMetadataItem ( int  metadataIndex)

Gets metadata item with specified index associated with current driver.

Parameters
metadataIndexIndex of metadata item to be returned.
Returns
String with metadata.

◆ get_ErrorMsg()

string OgrDatasource.get_ErrorMsg ( int  ErrorCode)

Gets the description of the specific error code.

Parameters
ErrorCodeThe error code returned by LastErrorCode property.
Returns
String with the description.

◆ GetLayer()

OgrLayer OgrDatasource.GetLayer ( int  Index,
bool  forUpdate = false 
)

Gets a layer with specified index from datasource.

Resulting OgrLayer has no reference to OgrDatasource object, which can safely closed if it is no longer needed.

Parameters
IndexIndex of layer to be returned.
forUpdateIndicates whether the returned layer will support saving of changes back to source (the functionality should be supported by particular driver).
Returns
Instance of OgrLayer or null on failure.

The following code adds all layers found in the datasource to the map:

private static string CONNECTION_STRING = "PG:host=localhost dbname=london user=postgres password=1234";
private static bool DisplayAllLayers()
{
var ds = new OgrDatasource();
if (!ds.Open(CONNECTION_STRING))
{
Debug.WriteLine("Failed to establish connection: " + ds.GdalLastErrorMsg);
}
else
{
// make sure it matches SRID of the layers (4326 in our case)
map.Projection = tkMapProjection.PROJECTION_WGS84;
for (int i = 0; i < ds.LayerCount; i++)
{
var layer = ds.GetLayer(i);
if (layer != null)
{
int handle = map.AddLayer(layer, true);
if (handle == -1)
{
Debug.WriteLine("Failed to add layer to the map: " + map.get_ErrorMsg(map.LastErrorCode));
}
else
{
Debug.WriteLine("Layer was added the map: " + layer.Name);
}
}
}
ds.Close();
}
return true;
}

See more details on projection & coordinates strategies in Map projection and coordinates section.

◆ GetLayer2()

OgrLayer OgrDatasource.GetLayer2 ( int  Index,
bool  forUpdate,
bool  newConnection 
)

◆ GetLayerByName()

OgrLayer OgrDatasource.GetLayerByName ( string  layerName,
bool  forUpdate = false 
)

Gets a layer with specified name from the datasource.

In case of spatial databases layerName corresponds to name of the underlying table. However there can be some format specifics. For example name may include schema prefix and name of geometry column (in case there is more than one geometry column in the table). For example, "public.buildings(geom2)" may correspond to "geom2" column of table named "buildings" in "public" schema.
Resulting layer has no reference to OgrDatasource object, which can safely closed if it is no longer needed.

Parameters
layerNameLayer name (case insensitive).
forUpdateIndicates whether the returned layer will support saving of changes back to source (the functionality should be supported by particular driver).
Returns
Instance of OgrLayer or null on failure.

◆ GetLayerName()

string OgrDatasource.GetLayerName ( int  layerIndex)

Gets a name of the layer with particular index.

Parameters
layerIndexIndex of layer.
Returns
Name of layer or empty string for invalid layer index.

◆ GetSchemas()

object OgrDatasource.GetSchemas ( )

Gets the array with schema names in the datasources.

Returns
Boxed string array.
New API 4.9.4:
Added in version 4.9.4

◆ ImportShapefile()

bool OgrDatasource.ImportShapefile ( Shapefile  shapefile,
string  layerName,
string  creationOptions = "",
tkShapeValidationMode  validationMode = tkShapeValidationMode.TryFixSkipOnFailure 
)

Creates a new layer in the datasource and populates it with data from specified shapefile.

The list of available creation options can be found in GDAL on-line documentation or retrieved by calling OgrDatasource.get_DriverMetadata(tkGdalDriverMetadata.dmdLAYER_CREATIONOPTIONLIST).

In addition MapWinGIS defines its own options:

  • MW_MULTI_PART={YES, NO} - sets whether single part or multipart geometry type column will be created to store data. The default value is "YES", i.e. MultiLineString will be used for polylines and MultiPolygon for polygons. "NO" option will result in LineString and Polygon types respectively, which won't allow multi-part polylines or polygons with multiple outer rings.
  • MW_POSTGIS_VACUUM={YES, NO} - indicates whether a VACUUM operation should be called after importing a layer into PostGIS database. The default value is "YES".
    Depending on driver invalid geometries may be accepted in the datasource, but they may cause errors on trying to perform spatial queries against these layers later on.
    Results of validation may be accessed via Shapefile.LastInputValidation of shapefile parameter.
Parameters
shapefileShapefile to import.
layerNameName for the imported layer.
creationOptionsFormat specific creation options separated with semicolon, e.g. "OVERWRITE=YES;MW_MULTI_PART=no".
validationModeSets validation mode for input shapes, ranging from no validation to abort the whole operation on the first invalid shape.
Returns
True on success.

The following code imports all shapefiles from the specified folder as layers into the datasource.

private static string CONNECTION_STRING = "PG:host=localhost dbname=london user=postgres password=1234";
private static bool ImportShapefileFromFolder()
{
var ds = new OgrDatasource();
if (!ds.Open(CONNECTION_STRING))
{
Debug.Pring("Failed to establish connection: " + ds.GdalLastErrorMsg);
}
else
{
string path = @"d:\data\sf\london";
var files = Directory.GetFiles(path, "*.shp");
foreach (var file in files)
{
var sf = new Shapefile();
if (!sf.Open(file))
{
Debug.Print("Failed to open shapefile: {0}\n{1}", file, sf.get_ErrorMsg(sf.LastErrorCode));
}
else
{
string name = Path.GetFileNameWithoutExtension(file);
if (!ds.ImportShapefile(sf, name, "OVERWRITE=YES", tkShapeValidationMode.NoValidation))
{
Debug.Print("Failed to import shapefile: " + name);
}
else
{
Debug.Print("Layer was imported: " + name);
var layer = ds.GetLayerByName(name);
if (layer != null)
{
Debug.Print("Imported features count: " + layer.FeatureCount);
layer.Close();
}
}
}
}
ds.Close();
}
return true;
}

◆ LayerIndexByName()

int OgrDatasource.LayerIndexByName ( string  layerName)

Returns index of layer with the specified name.

Parameters
layerNameLayer name (case insensitive).
Returns
Index of layer or -1 in case it wasn't found.

◆ Open()

bool OgrDatasource.Open ( string  connectionString)

Opens particular type of datasource supported by GDAL/OGR.

See details about connection strings here: http://www.gdal.org/ogr_formats.html

Parameters
connectionStringConnection string for RDMSs or filename for file-based formats.
Returns
True on success.

◆ Open2()

bool OgrDatasource.Open2 ( string  connectionString,
bool  forUpdate 
)

Opens particular type of datasource supported by GDAL/OGR.

See details about connection strings here: http://www.gdal.org/ogr_formats.html

Parameters
connectionStringConnection string for RDMSs or filename for file-based formats.
forUpdateIndicates whether datasource will be opened with update flag.
Returns
True on success.

◆ RunQuery()

OgrLayer OgrDatasource.RunQuery ( string  sql)

Runs a query against datasource and returns the result as a temporary layer.

Usually some sort of SELECT query returning a set of rows with one or several geometry columns is expected here. Other types of SQL instructions will also be processed, however OgrDatasource.ExecuteSQL is recommended way to do it.

Resulting layer has no reference to OgrDatasource object, which can safely closed if it is no longer needed.

Parameters
sqlSQL query.
Returns
Temporary layer or null on failure.

The following code builds 0.01 degree buffer zones around waterways layer extracted from database and displays both waterways and buffer layers on the map. st_buffer function is supported by PostGIS. See documentation of particular spatial database for list of supported functions and their arguments.

private static string CONNECTION_STRING = "PG:host=localhost dbname=london user=postgres password=1234";
private static bool TestSpatialQuery()
{
var ds = new OgrDatasource();
if (!ds.Open(CONNECTION_STRING))
{
Debug.WriteLine("Failed to establish connection: " + ds.GdalLastErrorMsg);
}
else
{
map.Projection = tkMapProjection.PROJECTION_WGS84;
// build a buffer in a first query
string sql = "SELECT st_buffer(wkb_geometry, 0.01) AS buffer, * FROM waterways;";
var buffer = ds.RunQuery(sql);
if (buffer == null)
{
Debug.WriteLine("Failed to build buffer: " + gs.GdalLastErrorMsg);
}
else
{
Debug.WriteLine("Number of features in a buffer: " + buffer.FeatureCount);
map.AddLayer(buffer, true);
buffer.GetBuffer().DefaultDrawingOptions.FillColor = 255; // red
}
// simply extract unaltered source features in the second query and display them above the buffer
string sql2 = "SELECT * FROM waterways;";
var layer = ds.RunQuery(sql2);
if (layer == null)
{
Debug.WriteLine("Failed to open layer: " + gs.GdalLastErrorMsg);
}
else
{
Debug.WriteLine("Number of features in layer: " + layer.FeatureCount);
map.AddLayer(layer, true);
}
ds.Close();
}
return true;
}

◆ TestCapability()

bool OgrDatasource.TestCapability ( tkOgrDSCapability  capability)

Test whether driver of the currently opened datasource supports particular capability.

Parameters
capabilityA capability to test.
Returns
True in case the capability is supported by the driver.

Property Documentation

◆ DriverMetadataCount

int OgrDatasource.DriverMetadataCount
get

Gets the number of metadata items associated with current driver.

◆ DriverName

string OgrDatasource.DriverName
get

Gets name driver (name of format) for this datasource.

◆ GdalLastErrorMsg

string OgrDatasource.GdalLastErrorMsg
get

Extracts the last error message reported by GDAL library.

◆ GlobalCallback

ICallback OgrDatasource.GlobalCallback
getset

Gets or sets a Callback object which handles progress and error messages.

Deprecated:
v4.9.3 Use GlobalSettings.ApplicationCallback instead.

◆ Key

string OgrDatasource.Key
getset

Gets or sets a text string associated with object. Any value can be stored by developer in this property.

◆ LastErrorCode

int OgrDatasource.LastErrorCode
get

Gets code of the last error which took place inside this object.

◆ LayerCount

int OgrDatasource.LayerCount
get

Gets number of layers in the datasource.