/usr/lib/thuban/Extensions/ogr/ogrshapes.py is in thuban 1.2.2-5.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 | # Copyright (C) 2004, 2007 by Intevation GmbH vim:encoding=latin-1:
# Authors:
# Nina Hüffmeyer <nhueffme@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with the software for details.
from __future__ import generators
__version__ = "$Revision: 2770 $"
# $Source$
# $Id: ogrshapes.py 2770 2007-05-22 08:54:41Z bh $
try:
from osgeo import ogr
except ImportError:
ogr = None
import os
from Thuban import _
from Thuban.Model import table
from Thuban.Model import transientdb
from Thuban.Model.transientdb import TransientDatabase
from Thuban.Model.data import SHAPETYPE_POLYGON, SHAPETYPE_ARC, SHAPETYPE_POINT
from Thuban.Model.data import RAW_PYTHON, RAW_SHAPEFILE, RAW_WKT
from Thuban.Model.data import FileShapeStore
def has_ogr_support():
"""Return whether this Thuban instance supports ogr file formats
Having OGR support means that the ogr module can be
imported.
"""
return ogr is not None
if ogr is not None:
SHAPETYPE_UNKNOWN = ogr.wkbUnknown
SHAPETYPE_GEOMCOLL = ogr.wkbGeometryCollection
SHAPETYPE_NONE = ogr.wkbNone
# mapping from ogr-lib shapetypes and table constants to our constants
ogrlib_shapetypes = {ogr.wkbPolygon: SHAPETYPE_POLYGON,
ogr.wkbLineString: SHAPETYPE_ARC,
ogr.wkbPoint: SHAPETYPE_POINT,
ogr.wkbUnknown: SHAPETYPE_UNKNOWN,
ogr.wkbNone: SHAPETYPE_NONE,
ogr.wkbGeometryCollection: SHAPETYPE_GEOMCOLL}
fieldtype_map = {ogr.OFTString: table.FIELDTYPE_STRING,
ogr.OFTInteger: table.FIELDTYPE_INT,
ogr.OFTReal: table.FIELDTYPE_DOUBLE}
else:
ogrlib_shapetypes = {}
fieldtype_map = {}
SHAPETYPE_UNKNOWN = 0
SHAPETYPE_GEOMCOLL = 7
SHAPETYPE_NONE = 100
class OGRShape:
"""Represent one shape of an OGRShapeStore
"""
def __init__(self, shapestore, shape):
"""Initialize the shape object.
shapestore should be an instance of OGRShapeStore,
shape should be an instance of an OGRFeature.
"""
self.ogrlayer = shapestore.ogrlayer
id_column = shapestore.Id_column()
self.feature = shape
if id_column is None:
self.shapeid = self.feature.GetFID()
else:
self.shapeid = self.feature.GetField(id_column)
self.geom = self.feature.GetGeometryRef()
if self.geom:
self.shapetype = self.geom.GetGeometryType()
self.bbox = self._compute_bbox()
self.points = self._points()
else:
self.shapetype = ogr.wkbNone
self.bbox = None
self.points = [[]]
try:
self.shapetype = ogrlib_shapetypes[self.shapetype]
except:
self.shapetype = ogrlib_shapetypes[ogr.wkbUnknown]
self.geoms = self._geoms()
def _geoms(self):
"""Return a list of geometry objects.
If the shape is a geometry collection, all contained geometry
objects are stored to the list as OGRGeometry objects.
"""
geoms = []
if self.shapetype == SHAPETYPE_GEOMCOLL:
for i in range(self.geom.GetGeometryCount()):
geoms.append(OGRGeometry(self, self.geom, i))
return geoms
def _compute_bbox(self):
"""
Compute the bounding box of the shape as a tuple (minx,miny,maxx,maxy)
"""
minx, maxx, miny, maxy = self.geom.GetEnvelope()
return (minx, miny, maxx, maxy)
def compute_bbox(self):
"""
Return the bounding box of the shape as a tuple (minx,miny,maxx,maxy)
"""
return self.bbox
def ShapeID(self):
"""Return the feature id of this shape.
"""
return self.shapeid
def Points(self):
"""Return the coordinates of the shape as a list of lists of pairs
"""
return self.points
def _points(self):
"""Get the coordinates of the shape as a list of lists of pairs
"""
shape = []
if self.geom is None:
return shape.append([])
# if geometry object is of type point or line
if self.geom.GetGeometryCount() == 0:
points =[]
for point in range(self.geom.GetPointCount()):
x = self.geom.GetX(point)
y = self.geom.GetY(point)
points.append((x, y))
return [points]
# if geometry object is of type polygon or multipolygon
for i in range(self.geom.GetGeometryCount()):
points = []
geometry = self.geom.GetGeometryRef(i)
# if geometry object is polygon
if geometry.GetGeometryCount() == 0:
for point in range(geometry.GetPointCount()):
x = geometry.GetX(point)
y = geometry.GetY(point)
points.append((x, y))
shape.append(points)
# if geometry object is of type multipolygon or geometry collection
else:
for j in range(geometry.GetGeometryCount()):
points = []
subgeom = geometry.GetGeometryRef(j)
for point in range(subgeom.GetPointCount()):
x = subgeom.GetX(point)
y = subgeom.GetY(point)
points.append((x, y))
shape.append(points)
return shape
def RawData(self):
"""Return the shape id to use with the shapestore
"""
return self.shapeid
def OGRLayer(self):
"""Return the ogrlayer object
"""
return self.ogrlayer
def ShapeType(self):
"""Return the shapetype of this shape (may differ from the layer's
shapetype)
"""
return self.shapetype
def GetGeoms(self):
"""Return the list of geometries of this feature.
If this feature is a geometry collection, all contained geometries
are given. Else the returned list is empty.
"""
return self.geoms
def GetGeom(self, index):
"""Return the OGRGeometry object at the specified index.
This is not none only if the shape is a geometry collection.
"""
if index < len(self.geoms):
return self.geoms[index]
else:
return None
class OGRGeometry:
"""This class represents a geometry belonging to a specified feature.
"""
def __init__(self, shape, geom, index):
"""Initialize the geometry object.
shape should be an OGRShape, which this geometry belongs to.
geom is the base geometry, index is the ReferenceID.
"""
self.shape = shape
self.index = index
self.geom = geom.GetGeometryRef(index)
try:
self.shapetype = ogrlib_shapetypes[self.geom.GetGeometryType()]
except:
self.shapetype = ogrlib_shapetypes[ogr.wkbUnknown]
def ShapeType(self):
"""Return the shapetype of this geometry object."""
return self.shapetype
class OGRShapeStore:
"""Corresponds to an OGRLayer object, containing features/shapes and
providing the same methods like ShapefileStore.
In fact, for all file based shape stores, the class OGRFileShapeStore
should be used. Only database shape stores should be
used with OGRShapeStore. It is subject to re-factoring
to end up with better class names and sensible base classes.
"""
# TODO: re-factor this class to be not responsible for file-based
# stores anymore.
def __init__(self, session, filename, layername, id_column = None):
"""Initialize the shapestore.
All required information is loaded from the datasource.
"""
# if id_column is None, data is loaded from file, so we need path
# if id_column is not None, data is loaded from database
if id_column is None:
self.filename = os.path.abspath(filename)
else:
self.filename = filename
self.layername = layername
self.ogrdatasource = ogr.Open(filename)
self.ogrlayer = (self.ogrdatasource).GetLayerByName(layername)
if id_column is not None:
self.id_column = id_column
else:
self.id_column = None
self.table = OGRTable(session, self.ogrdatasource, self.ogrlayer,
self.id_column)
self._open_ogrlayer(layername)
def _open_ogrlayer(self, layername):
"""Get all required information from the datasource.
"""
self.numshapes = self.ogrlayer.GetFeatureCount()
self.shapetype = self.ogrlayer.GetLayerDefn().GetGeomType()
extent = self.ogrlayer.GetExtent()
if extent:
self.bbox = [extent[0], extent[2], extent[1], extent[3]]
else:
self.bbox = None
try:
self.shapetype = ogrlib_shapetypes[self.shapetype]
except:
# if shapetype is not contained in ogrlib_shapetypes
# treat it like SHAPETYPE_UNKNOWN
self.shapetype = ogrlib_shapetypes[ogr.wkbUnknown]
self.shapes = self.shapes()
def shapes(self):
"""Return a collection of all features as OGRShape objects.
"""
shapes = {}
self.ogrlayer.ResetReading()
if self.id_column is None:
nextFeature = self.ogrlayer.GetNextFeature()
while nextFeature is not None:
fid = nextFeature.GetFID()
shape = OGRShape(self, nextFeature)
shapes[shape.ShapeID()] = shape
nextFeature = self.ogrlayer.GetNextFeature()
else:
lay = self.ogrdatasource.ExecuteSQL("SELECT %s, * from %s"
% (self.id_column, self.layername))
if lay is not None:
lay.ResetReading()
nextFeature = lay.GetNextFeature()
while nextFeature is not None:
fid = nextFeature.GetField(0)
shape = OGRShape(self, nextFeature)
shapes[shape.ShapeID()] = shape
nextFeature = lay.GetNextFeature()
self.ogrdatasource.ReleaseResultSet(lay)
return shapes
def OGRLayer(self):
"""Return the OGRLayer object
"""
return self.ogrlayer
def FileName(self):
"""Return the filename used to open the file
"""
return self.filename
def FileType(self):
"""Return the filetype. This is depending on the driver used to open
the file.
"""
return self.ogrdatasource.GetDriver().GetName()
def ShapeType(self):
"""Return the type of the shapes in the shapestore.
This is either SHAPETYPE_POINT, SHAPETYPE_ARC, SHAPETYPE_POLYGON,
SHAEPTYPE_GEOMCOLL, SHAPETYPE_NONE or SHAPETYPE_UNKNOWN.
"""
return self.shapetype
def RawShapeFormat(self):
"""Return the raw data format of the shape data, i.e. RAW_PYTHON
"""
return RAW_PYTHON
def NumShapes(self):
"""Return the number of shapes in the shape store
"""
return self.numshapes
def BoundingBox(self):
"""Return the bounding box of the shapes in the shapestore.
"""
return self.bbox
def ShapesInRegion(self, bbox):
"""Return an iterable over the shapes that overlap the bounding box.
The bbox parameter should be the bounding box as a tuple in the
form (minx, miny, maxx, maxy) in the coordinate system of the
shape store.
"""
left, bottom, right, top = bbox
# create a geometry which can be passed to the layer as spatial filter
bboxpolygon = ogr.CreateGeometryFromWkt(
('Polygon((%s %s, %s %s, %s %s,%s %s, %s %s))'
%(left, bottom, left, top, right, top,
right, bottom, left, bottom)))
if self.ogrlayer.GetSpatialRef():
bboxpolygon.AssignSpatialReference(self.ogrlayer.GetSpatialRef())
self.ogrlayer.ResetReading()
#ogrlayer.SetSpatialFilterRect(left, bottom, right, top)
self.ogrlayer.SetSpatialFilter(bboxpolygon)
numFeatures = self.ogrlayer.GetFeatureCount()
# if no features are in bbox, return all features as shapesInRegion
# (PostGIS sometimes returns no features even if they are within
# the bounding box)
if numFeatures == 0:
self.ogrlayer.SetSpatialFilter(None)
numFeatures = self.ogrlayer.GetFeatureCount()
for feature in range(numFeatures):
nextFeature = self.ogrlayer.GetNextFeature()
if self.id_column is None:
yield self.shapes[nextFeature.GetFID()]
else:
yield self.shapes[nextFeature.GetField(self.id_column)]
self.ogrlayer.SetSpatialFilter(None)
bboxpolygon.Destroy()
def AllShapes(self):
"""Return an iterable over the shapes in the shape store.
"""
for id in range(len(self.shapes)):
yield self.shapes[id]
def Shape(self, fid):
"""Return the shape with fid = fid
"""
if fid in self.table.ids.keys():
return self.shapes[fid]
else:
return None
def Table(self):
"""Return the table containing the attribute data
"""
return self.table
def Dependencies(self):
"""Return the empty tuple.
"""
return ()
def OrigShapeStore(self):
"""Return None."""
return None
def Id_column(self):
"""Return the id_column.
"""
return self.id_column
class OGRFileShapeStore(FileShapeStore):
"""Corresponds to an OGRLayer object, containing features/shapes and
providing the same methods like ShapefileStore.
"""
def __init__(self, session, filename, layername, id_column = None):
"""Initialize the shapestore.
All required information is loaded from the datasource.
"""
self._bbox = None
self.ogrdatasource = ogr.Open(filename)
# filetype is depending on the driver used to open the file.
self._filetype = self.ogrdatasource.GetDriver().GetName()
if self._filetype == 'ESRI Shapefile':
self._filetype = "shapefile"
FileShapeStore.__init__(self, filename,
sublayer_name = layername)
self.ogrlayer = (self.ogrdatasource).GetLayerByName(layername)
self._table = OGRTable(session, self.ogrdatasource, self.ogrlayer,
id_column)
self._open_ogrlayer(layername)
def _open_ogrlayer(self, layername):
"""Get all required information from the datasource.
"""
self.numshapes = self.ogrlayer.GetFeatureCount()
self.shapetype = self.ogrlayer.GetLayerDefn().GetGeomType()
extent = self.ogrlayer.GetExtent()
if extent:
self._bbox = [extent[0], extent[2], extent[1], extent[3]]
else:
self._bbox = None
try:
self.shapetype = ogrlib_shapetypes[self.shapetype]
except:
# if shapetype is not contained in ogrlib_shapetypes
# treat it like SHAPETYPE_UNKNOWN
self.shapetype = ogrlib_shapetypes[ogr.wkbUnknown]
self.shapes = self.shapes()
def FileType(self):
"""Return the filetype."""
return self._filetype
def BoundingBox(self):
"""Return the bounding box of the shapes in the shape file.
The coordinate system used is whatever was used in the shape file.
If the shape file is empty, return None.
"""
return self._bbox
def shapes(self):
"""Return a collection of all features as OGRShape objects.
"""
shapes = {}
self.ogrlayer.ResetReading()
nextFeature = self.ogrlayer.GetNextFeature()
while nextFeature is not None:
fid = nextFeature.GetFID()
shape = OGRShape(self, nextFeature)
shapes[shape.ShapeID()] = shape
nextFeature = self.ogrlayer.GetNextFeature()
return shapes
def OGRLayer(self):
"""Return the OGRLayer object
"""
return self.ogrlayer
def ShapeType(self):
"""Return the type of the shapes in the shapestore.
This is either SHAPETYPE_POINT, SHAPETYPE_ARC, SHAPETYPE_POLYGON,
SHAEPTYPE_GEOMCOLL, SHAPETYPE_NONE or SHAPETYPE_UNKNOWN.
"""
return self.shapetype
def RawShapeFormat(self):
"""Return the raw data format of the shape data, i.e. RAW_PYTHON
"""
return RAW_PYTHON
def NumShapes(self):
"""Return the number of shapes in the shape store
"""
return self.numshapes
def ShapesInRegion(self, bbox):
"""Return an iterable over the shapes that overlap the bounding box.
The bbox parameter should be the bounding box as a tuple in the
form (minx, miny, maxx, maxy) in the coordinate system of the
shape store.
"""
left, bottom, right, top = bbox
# create a geometry which can be passed to the layer as spatial filter
bboxpolygon = ogr.CreateGeometryFromWkt(
('Polygon((%s %s, %s %s, %s %s,%s %s, %s %s))'
%(left, bottom, left, top, right, top,
right, bottom, left, bottom)))
if self.ogrlayer.GetSpatialRef():
bboxpolygon.AssignSpatialReference(self.ogrlayer.GetSpatialRef())
self.ogrlayer.ResetReading()
#ogrlayer.SetSpatialFilterRect(left, bottom, right, top)
self.ogrlayer.SetSpatialFilter(bboxpolygon)
numFeatures = self.ogrlayer.GetFeatureCount()
# if no features are in bbox, return all features as shapesInRegion
# (PostGIS sometimes returns no features even if they are within
# the bounding box)
if numFeatures == 0:
self.ogrlayer.SetSpatialFilter(None)
numFeatures = self.ogrlayer.GetFeatureCount()
for feature in range(numFeatures):
nextFeature = self.ogrlayer.GetNextFeature()
yield self.shapes[nextFeature.GetFID()]
self.ogrlayer.SetSpatialFilter(None)
bboxpolygon.Destroy()
def AllShapes(self):
"""Return an iterable over the shapes in the shape store.
"""
for id in range(len(self.shapes)):
yield self.shapes[id]
def Shape(self, fid):
"""Return the shape with fid = fid
"""
if fid in self.Table().ids.keys():
return self.shapes[fid]
else:
return None
def Table(self):
"""Return the table containing the attribute data."""
return self._table
def Dependencies(self):
"""Return the empty tuple.
"""
return ()
def OrigShapeStore(self):
"""Return None."""
return None
def Id_column(self):
"""Return the id_column.
"""
return None
class OGRTable(transientdb.AutoTransientTable):
"""A Table for an ogr datasource.
"""
def __init__(self, session, ds, layer, id_column):
"""Initialize the OGRTable.
session - should be the current session.
ds - should be an instance of OGRDatasource.
layer - should be an instance of OGRLayer.
id_column - should be the name of the column used as ID column
"""
self.datasource = ds
self.layer = layer
self.tablename = self.layer.GetName()
self.id_column = id_column
# Map column names and indices to column objects.
self.column_map = {}
# Map feature ids to ordinals.
self._map_ords_and_ids()
self._fetch_table_information()
self._fetch_table_content()
transientdb.AutoTransientTable.__init__(self, session.TransientDB(),
self)
def _fetch_table_information(self):
"""Internal: Update information about the table
"""
self.columns = []
layerdefn = self.layer.GetLayerDefn()
# if FID column is of interest
#col = OGRColumn("FID", table.FIELDTYPE_INT, layerdefn.GetFieldCount())
#self.columns.append(col)
for i in range(layerdefn.GetFieldCount()):
fielddef = layerdefn.GetFieldDefn(i)
fieldname = fielddef.GetName()
fieldtype = fieldtype_map[fielddef.GetType()]
fieldindex = layerdefn.GetFieldIndex(fieldname)
col = OGRColumn(fieldname, fieldtype, fieldindex)
if col is not None:
self.columns.append(col)
for col in self.columns:
self.column_map[col.name] = col
self.column_map[col.index] = col
def _fetch_table_content(self):
"""Internal: Update information contained in the table
"""
self.content = []
layerdefn = self.layer.GetLayerDefn()
self.layer.ResetReading()
for i in range(self.layer.GetFeatureCount()):
nextFeature = self.layer.GetNextFeature()
row = []
for j in range(layerdefn.GetFieldCount()):
row.append(nextFeature.GetField(j))
# if FID should be listed in the table
#if self.id_column is None:
# row.append(nextFeature.GetFID())
#else:
# row.append(nextFeature.GetField(self.id_column))
self.content.append(row)
def _map_ords_and_ids(self):
"""Create collections which map ordinals to ids and verse visa.
"""
self.ordinals = {}
self.ids = {}
if self.id_column is not None:
lay = self.datasource.ExecuteSQL("SELECT %s from %s"
%(self.id_column, self.tablename))
lay.ResetReading()
nextFeature = lay.GetNextFeature()
else:
self.layer.ResetReading()
nextFeature = self.layer.GetNextFeature()
ord = 0
while nextFeature is not None:
if self.id_column is not None:
id = nextFeature.GetField(self.id_column)
nextFeature = lay.GetNextFeature()
else:
id = nextFeature.GetFID()
nextFeature = self.layer.GetNextFeature()
self.ordinals[ord] = id
self.ids[id] = ord
ord = ord + 1
if self.id_column is not None:
self.datasource.ReleaseResultSet(lay)
def TableName(self):
"""Return the name of the table, which is the name of the layer
"""
return self.tablename
def Title(self):
"""Return the title of the table.
"""
return self.tablename
def Dependencies(self):
"""Return an empty tuple.
"""
return ()
def NumColumns(self):
"""Return the number of columns.
"""
return len(self.columns)
def Columns(self):
"""Return all columns.
"""
return self.columns
def Column(self, col):
"""Return the column col. col can be either a string or an integer.
"""
return self.column_map[col]
def HasColumn(self, col):
"""Return if column col exists. col can be either a string or an
integer.
"""
return self.column_map.has_key(col)
def NumRows(self):
"""Return the number of rows in the table, which equals the number of
features in the layer.
"""
return len(self.ids)
def RowIdToOrdinal(self, gid):
"""Return the row ordinal given its id
"""
if gid < 0:
return gid
else:
ord = self.ids[gid]
return ord
def RowOrdinalToId(self, num):
"""Return the rowid for given its ordinal
"""
if num >= 0:
id = self.ordinals[num]
return id
else:
return num
def ReadRowAsDict(self, row, row_is_ordinal = 0):
"""Return a dictionary which contains all the fields.
"""
if row_is_ordinal == 0:
rowId = self.RowIdToOrdinal(row)
else:
rowId = row
result = {}
for i in range(self.NumColumns()):
result[self.Column(i).name] = self.content[rowId][i]
return result
def ReadValue(self, row, col, row_is_ordinal = 0):
"""Return the requested value.
"""
if row_is_ordinal == 0:
rowId = self.RowIdToOrdinal(row)
else:
rowId = row
colIndex = self.column_map[col].index
return self.content[rowId][colIndex]
def ValueRange(self, col):
"""Return the value range of the given column (given as string).
"""
result = self.datasource.ExecuteSQL("SELECT min(%s), max(%s) FROM %s"
%(col, col, self.layer.GetName()))
result.ResetReading()
feature = result.GetNextFeature()
try:
min = feature.GetField(0)
max = feature.GetField(1)
except:
min = 0
max = 0
self.datasource.ReleaseResultSet(result)
return (min, max)
def UniqueValues(self, col):
"""Return all the values being found in the column (given as string).
"""
result = self.datasource.ExecuteSQL((
"SELECT DISTINCT %s FROM %s ORDER BY %s"
%(col,self.layer.GetName(),col)))
values = []
while 1:
feature = result.GetNextFeature()
if feature is None:
break
values.append(feature.GetField(0))
self.datasource.ReleaseResultSet(result)
return values
def SimpleQuery(self, left, comparison, right):
"""Return the FIDs resulting from the given query.
"""
if comparison not in ("==", "!=", "<", "<=", ">=", ">"):
raise ValueError("Comparison operator %r not allowed" %comparison)
if comparison == "==":
comparison = "="
if isinstance(right, OGRColumn):
right_template = right.name
else:
right_template = right
if self.id_column is None:
id = "FID"
else:
id = self.id_column
query = ("SELECT %s FROM %s WHERE %s %s %s ORDER BY %s"
% (id, self.tablename,left.name, comparison,
right_template, id))
lay = self.datasource.ExecuteSQL(query)
result = []
while lay is not None:
feature = lay.GetNextFeature()
if feature is None:
break
result.append(feature.GetField(0))
if lay is not None:
self.datasource.ReleaseResultSet(lay)
return result
def Id_column(self):
"""Return the id_column.
"""
return self.id_column
class OGRColumn:
"""Column description for a table for an ogr file
"""
def __init__(self, name, type, index):
self.name = name
self.type = type
self.index = index
|