forked from SharpMap/SharpMap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOracle.cs
More file actions
606 lines (551 loc) · 24.8 KB
/
Oracle.cs
File metadata and controls
606 lines (551 loc) · 24.8 KB
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
// Copyright 2006 - Humberto Ferreira
// Oracle provider by Humberto Ferreira (humbertojdf@gmail.com)
//
// Date 2006-09-05
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Globalization;
using GeoAPI.Geometries;
using Oracle.ManagedDataAccess.Client;
using SharpMap.Converters.WellKnownBinary;
using Geometry = GeoAPI.Geometries.IGeometry;
namespace SharpMap.Data.Providers
{
/// <summary>
/// Oracle dataprovider
/// </summary>
/// <remarks>
/// <para>This provider needs the Oracle software client installed on the PC where the application runs.
/// If you need to connect to an Oracle database, it has to have oracle client (or Oracle Instant Client) installed. </para>
/// <para>You can download Oracle Client here:
/// http://www.oracle.com/technology/software/index.html</para>
/// <para>If client don4t need an instance of Oracle, a better option is to use Oracle Instant client
/// http://www.oracle.com/technology/tech/oci/instantclient/index.html</para>
/// <example>
/// Adding a datasource to a layer:
/// <code lang="C#">
/// SharpMap.Layers.VectorLayer myLayer = new SharpMap.Layers.VectorLayer("My layer");
/// string ConnStr = "Server=127.0.0.1;Port=5432;User Id=userid;Password=password;Database=myGisDb;";
/// myLayer.DataSource = new SharpMap.Data.Providers.Oracle(ConnStr, "myTable", "GeomColumn", "OidColumn");
/// </code>
/// </example>
/// <para>SharpMap Oracle provider by Humberto Ferreira (humbertojdf at gmail com).</para>
/// </remarks>
[Serializable]
public class Oracle : BaseProvider
{
private string _definitionQuery;
private string _geometryColumn;
private string _objectIdColumn;
private string _table;
/// <summary>
/// Initializes a new connection to Oracle
/// </summary>
/// <param name="connectionStr">Connectionstring</param>
/// <param name="tablename">Name of data table</param>
/// <param name="geometryColumnName">Name of geometry column</param>
/// /// <param name="oidColumnName">Name of column with unique identifier</param>
public Oracle(string connectionStr, string tablename, string geometryColumnName, string oidColumnName)
:base(-2)
{
ConnectionString = connectionStr;
Table = tablename;
GeometryColumn = geometryColumnName;
ObjectIdColumn = oidColumnName;
}
/// <summary>
/// Initializes a new connection to Oracle
/// </summary>
/// <param name="username">Username</param>
/// <param name="password">Password</param>
/// <param name="datasource">Datasoure</param>
/// <param name="tablename">Tablename</param>
/// <param name="geometryColumnName">Geometry column name</param>
/// <param name="oidColumnName">Object ID column</param>
public Oracle(string username, string password, string datasource, string tablename, string geometryColumnName,
string oidColumnName)
: this(
"User Id=" + username + ";Password=" + password + ";Data Source=" + datasource, tablename,
geometryColumnName, oidColumnName)
{
}
/// <summary>
/// Initializes a new connection to Oracle
/// </summary>
/// <param name="connectionStr">Connectionstring</param>
/// <param name="tablename">Name of data table</param>
/// <param name="oidColumnName">Name of column with unique identifier</param>
public Oracle(string connectionStr, string tablename, string oidColumnName)
: this(connectionStr, tablename, "", oidColumnName)
{
GeometryColumn = GetGeometryColumn();
}
/// <summary>
/// Connectionstring
/// </summary>
public string ConnectionString
{
get { return ConnectionID; }
set { ConnectionID = value; }
}
/// <summary>
/// Data table name
/// </summary>
public string Table
{
get { return _table; }
set { _table = value; }
}
/// <summary>
/// Name of geometry column
/// </summary>
public string GeometryColumn
{
get { return _geometryColumn; }
set { _geometryColumn = value; }
}
/// <summary>
/// Name of column that contains the Object ID
/// </summary>
public string ObjectIdColumn
{
get { return _objectIdColumn; }
set { _objectIdColumn = value; }
}
/// <summary>
/// Definition query used for limiting dataset
/// </summary>
public string DefinitionQuery
{
get { return _definitionQuery; }
set { _definitionQuery = value; }
}
#region IProvider Members
/// <summary>
/// Returns geometries within the specified bounding box
/// </summary>
/// <param name="bbox"></param>
/// <returns></returns>
public override Collection<Geometry> GetGeometriesInView(Envelope bbox)
{
var features = new Collection<Geometry>();
using (var conn = new OracleConnection(ConnectionString))
{
//Get bounding box string
string strBbox = GetBoxFilterStr(bbox);
//string strSQL = "SELECT AsBinary(" + this.GeometryColumn + ") AS Geom ";
string strSql = "SELECT g." + GeometryColumn + ".Get_WKB() ";
strSql += " FROM " + Table + " g WHERE ";
if (!String.IsNullOrEmpty(_definitionQuery))
strSql += DefinitionQuery + " AND ";
strSql += strBbox;
using (var command = new OracleCommand(strSql, conn))
{
conn.Open();
using (OracleDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
if (dr[0] != DBNull.Value)
{
Geometry geom = GeometryFromWKB.Parse((byte[]) dr[0], Factory);
if (geom != null)
features.Add(geom);
}
}
}
conn.Close();
}
}
return features;
}
/// <summary>
/// Returns the geometry corresponding to the Object ID
/// </summary>
/// <param name="oid">Object ID</param>
/// <returns>geometry</returns>
public override Geometry GetGeometryByID(uint oid)
{
Geometry geom = null;
using (var conn = new OracleConnection(ConnectionString))
{
string strSql = "SELECT g." + GeometryColumn + ".Get_WKB() FROM " + Table + " g WHERE " + ObjectIdColumn +
"='" + oid.ToString(CultureInfo.InvariantCulture) + "'";
conn.Open();
using (var command = new OracleCommand(strSql, conn))
{
using (OracleDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
if (dr[0] != DBNull.Value)
geom = GeometryFromWKB.Parse((byte[]) dr[0], Factory);
}
}
}
conn.Close();
}
return geom;
}
/// <summary>
/// Returns geometry Object IDs whose bounding box intersects 'bbox'
/// </summary>
/// <param name="bbox"></param>
/// <returns></returns>
public override Collection<uint> GetObjectIDsInView(Envelope bbox)
{
var objectlist = new Collection<uint>();
using (var conn = new OracleConnection(ConnectionString))
{
//Get bounding box string
string strBbox = GetBoxFilterStr(bbox);
string strSql = "SELECT g." + ObjectIdColumn + " ";
strSql += "FROM " + Table + " g WHERE ";
if (!String.IsNullOrEmpty(_definitionQuery))
strSql += DefinitionQuery + " AND ";
strSql += strBbox;
using (var command = new OracleCommand(strSql, conn))
{
conn.Open();
using (OracleDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
if (dr[0] != DBNull.Value)
{
var id = (uint) (decimal) dr[0];
objectlist.Add(id);
}
}
}
conn.Close();
}
}
return objectlist;
}
/// <summary>
/// Returns the features that intersects with 'geom'
/// </summary>
/// <param name="geom"></param>
/// <param name="ds">FeatureDataSet to fill data into</param>
protected override void OnExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds)
{
using (var conn = new OracleConnection(ConnectionString))
{
string strGeom = "MDSYS.SDO_GEOMETRY('" + geom.AsText() + "', #SRID#)";
strGeom = strGeom.Replace("#SRID#", SRID > 0 ? SRID.ToString(Map.NumberFormatEnUs) : "NULL");
strGeom = "SDO_RELATE(g." + GeometryColumn + ", " + strGeom +
", 'mask=ANYINTERACT querytype=WINDOW') = 'TRUE'";
string strSql = "SELECT g.* , g." + GeometryColumn + ").Get_WKB() As sharpmap_tempgeometry FROM " +
Table + " g WHERE ";
if (!String.IsNullOrEmpty(_definitionQuery))
strSql += DefinitionQuery + " AND ";
strSql += strGeom;
using (var adapter = new OracleDataAdapter(strSql, conn))
{
conn.Open();
adapter.Fill(ds);
conn.Close();
if (ds.Tables.Count > 0)
{
var fdt = new FeatureDataTable(ds.Tables[0]);
foreach (DataColumn col in ds.Tables[0].Columns)
if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
foreach (DataRow dr in ds.Tables[0].Rows)
{
var fdr = fdt.NewRow();
foreach (DataColumn col in ds.Tables[0].Columns)
if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
fdr[col.ColumnName] = dr[col];
fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"], Factory);
fdt.AddRow(fdr);
}
ds.Tables.Add(fdt);
}
}
}
}
/// <summary>
/// Returns the number of features in the dataset
/// </summary>
/// <returns>number of features</returns>
public override int GetFeatureCount()
{
using (var conn = new OracleConnection(ConnectionString))
{
string strSql = "SELECT COUNT(*) FROM " + Table;
if (!String.IsNullOrEmpty(_definitionQuery))
strSql += " WHERE " + DefinitionQuery;
using (var command = new OracleCommand(strSql, conn))
{
conn.Open();
return (int) command.ExecuteScalar();
}
}
}
///// <summary>
///// Spacial Reference ID
///// </summary>
//public int SRID
//{
// get
// {
// if (_srid == -2)
// {
// string strSQL = "select SRID from USER_SDO_GEOM_METADATA WHERE TABLE_NAME='" + Table + "'";
// using (OracleConnection conn = new OracleConnection(ConnectionString))
// {
// using (OracleCommand command = new OracleCommand(strSQL, conn))
// {
// try
// {
// conn.Open();
// _srid = (int) (decimal) command.ExecuteScalar();
// conn.Close();
// }
// catch
// {
// _srid = -1;
// }
// }
// }
// }
// return _srid;
// }
// set { throw (new ApplicationException("Spatial Reference ID cannot by set on a Oracle table")); }
//}
/// <summary>
/// Returns a datarow based on a RowID
/// </summary>
/// <param name="rowId"></param>
/// <returns>datarow</returns>
public override FeatureDataRow GetFeature(uint rowId)
{
using (var conn = new OracleConnection(ConnectionString))
{
string strSql = "select g.* , g." + GeometryColumn + ").Get_WKB() As sharpmap_tempgeometry from " +
Table + " g WHERE " + ObjectIdColumn + "='" + rowId.ToString(NumberFormatInfo.InvariantInfo) + "'";
using (var adapter = new OracleDataAdapter(strSql, conn))
{
var ds = new DataSet();
conn.Open();
adapter.Fill(ds);
conn.Close();
if (ds.Tables.Count > 0)
{
var fdt = new FeatureDataTable(ds.Tables[0]);
foreach (DataColumn col in ds.Tables[0].Columns)
if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
if (ds.Tables[0].Rows.Count > 0)
{
DataRow dr = ds.Tables[0].Rows[0];
var fdr = fdt.NewRow();
foreach (DataColumn col in ds.Tables[0].Columns)
if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
fdr[col.ColumnName] = dr[col];
fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"], Factory);
return fdr;
}
else
return null;
}
else
return null;
}
}
}
/// <summary>
/// Boundingbox of dataset
/// </summary>
/// <returns>boundingbox</returns>
public override Envelope GetExtents()
{
using (var conn = new OracleConnection(ConnectionString))
{
string strSql = "SELECT SDO_AGGR_MBR(g." + GeometryColumn + ").Get_WKT() FROM " + Table + " g ";
if (!String.IsNullOrEmpty(_definitionQuery))
strSql += " WHERE " + DefinitionQuery;
using (var command = new OracleCommand(strSql, conn))
{
conn.Open();
var result = command.ExecuteScalar();
conn.Close();
if (result == DBNull.Value)
return null;
var strBox = (string) result;
if (strBox.StartsWith("POLYGON", StringComparison.InvariantCultureIgnoreCase))
{
strBox = strBox.Replace("POLYGON", "");
strBox = strBox.Trim();
strBox = strBox.Replace("(", "");
strBox = strBox.Replace(")", "");
var xX = new List<double>();
var yY = new List<double>();
String[] points = strBox.Split(',');
foreach (string s in points)
{
string point = s.Trim();
String[] nums = point.Split(' ');
xX.Add(double.Parse(nums[0], Map.NumberFormatEnUs));
yY.Add(double.Parse(nums[1], Map.NumberFormatEnUs));
}
double minX = Double.MaxValue;
double minY = Double.MaxValue;
double maxX = Double.MinValue;
double maxY = Double.MinValue;
foreach (double d in xX)
{
if (d > maxX)
{
maxX = d;
}
if (d < minX)
{
minX = d;
}
}
foreach (double d in yY)
{
if (d > maxY)
{
maxY = d;
}
if (d < minY)
{
minY = d;
}
}
return new Envelope(minX, maxX, minY, maxY);
}
return null;
}
}
}
/// <summary>
/// Returns all features with the view box
/// </summary>
/// <param name="bbox">view box</param>
/// <param name="ds">FeatureDataSet to fill data into</param>
public override void ExecuteIntersectionQuery(Envelope bbox, FeatureDataSet ds)
{
using (var conn = new OracleConnection(ConnectionString))
{
//Get bounding box string
var strBbox = GetBoxFilterStr(bbox);
var strSql = "SELECT g.*, g." + GeometryColumn + ".Get_WKB() AS sharpmap_tempgeometry ";
strSql += "FROM " + Table + " g WHERE ";
if (!String.IsNullOrEmpty(_definitionQuery))
strSql += DefinitionQuery + " AND ";
strSql += strBbox;
using (var adapter = new OracleDataAdapter(strSql, conn))
{
conn.Open();
var ds2 = new DataSet();
adapter.Fill(ds2);
conn.Close();
if (ds2.Tables.Count > 0)
{
var fdt = new FeatureDataTable(ds2.Tables[0]);
foreach (DataColumn col in ds2.Tables[0].Columns)
if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
foreach (DataRow dr in ds2.Tables[0].Rows)
{
FeatureDataRow fdr = fdt.NewRow();
foreach (DataColumn col in ds2.Tables[0].Columns)
if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
fdr[col.ColumnName] = dr[col];
fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"], Factory);
fdt.AddRow(fdr);
}
ds.Tables.Add(fdt);
}
}
}
}
#endregion
/// <summary>
/// Returns the box filter string needed in SQL query
/// </summary>
/// <param name="bbox"></param>
/// <returns></returns>
protected string GetBoxFilterStr(Envelope bbox)
{
string strBbox = "SDO_FILTER(g." + GeometryColumn + ", mdsys.sdo_geometry(2003,#SRID#,NULL," +
"mdsys.sdo_elem_info_array(1,1003,3)," +
"mdsys.sdo_ordinate_array(" +
bbox.MinX.ToString(Map.NumberFormatEnUs) + ", " +
bbox.MinY.ToString(Map.NumberFormatEnUs) + ", " +
bbox.MaxX.ToString(Map.NumberFormatEnUs) + ", " +
bbox.MaxY.ToString(Map.NumberFormatEnUs) + ")), " +
"'querytype=window') = 'TRUE'";
strBbox = strBbox.Replace("#SRID#", SRID > 0 ? SRID.ToString(Map.NumberFormatEnUs) : "NULL");
return strBbox;
}
///// <summary>
///// Convert WellKnownText to linestrings
///// </summary>
///// <param name="WKT"></param>
///// <returns></returns>
//private LineString WktToLineString(string WKT)
//{
// LineString line = new LineString();
// WKT = WKT.Substring(WKT.LastIndexOf('(') + 1).Split(')')[0];
// string[] strPoints = WKT.Split(',');
// foreach (string strPoint in strPoints)
// {
// string[] coord = strPoint.Split(' ');
// line.Vertices.Add(new Point(double.Parse(coord[0], Map.NumberFormatEnUs),
// double.Parse(coord[1], Map.NumberFormatEnUs)));
// }
// return line;
//}
/// <summary>
/// Queries the Oracle database to get the name of the Geometry Column. This is used if the columnname isn't specified in the constructor
/// </summary>
/// <remarks></remarks>
/// <returns>Name of column containing geometry</returns>
private string GetGeometryColumn()
{
string strSql = "select COLUMN_NAME from USER_SDO_GEOM_METADATA WHERE TABLE_NAME='" + Table + "'";
using (var conn = new OracleConnection(ConnectionString))
using (var command = new OracleCommand(strSql, conn))
{
conn.Open();
object columnname = command.ExecuteScalar();
conn.Close();
if (columnname == DBNull.Value)
throw new ApplicationException("Table '" + Table + "' does not contain a geometry column");
return (string) columnname;
}
}
/// <summary>
/// Returns all features with the view box
/// </summary>
/// <param name="bbox">view box</param>
/// <param name="ds">FeatureDataSet to fill data into</param>
[Obsolete("Use ExecuteIntersectionQuery(box) instead")]
public void GetFeaturesInView(Envelope bbox, FeatureDataSet ds)
{
ExecuteIntersectionQuery(bbox, ds);
}
}
}