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 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
|
/******************************************************************************
* $Id: ogrmssqlspatialdatasource.cpp 25988 2013-05-05 14:09:05Z tamas $
*
* Project: MSSQL Spatial driver
* Purpose: Implements OGRMSSQLSpatialDataSource class..
* Author: Tamas Szekeres, szekerest at gmail.com
*
******************************************************************************
* Copyright (c) 2010, Tamas Szekeres
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "ogr_mssqlspatial.h"
CPL_CVSID("$Id: ogrmssqlspatialdatasource.cpp 25988 2013-05-05 14:09:05Z tamas $");
/************************************************************************/
/* OGRMSSQLSpatialDataSource() */
/************************************************************************/
OGRMSSQLSpatialDataSource::OGRMSSQLSpatialDataSource()
{
pszName = NULL;
pszCatalog = NULL;
papoLayers = NULL;
nLayers = 0;
nKnownSRID = 0;
panSRID = NULL;
papoSRS = NULL;
nGeometryFormat = MSSQLGEOMETRY_NATIVE;
bUseGeometryColumns = CSLTestBoolean(CPLGetConfigOption("MSSQLSPATIAL_USE_GEOMETRY_COLUMNS", "YES"));
}
/************************************************************************/
/* ~OGRMSSQLSpatialDataSource() */
/************************************************************************/
OGRMSSQLSpatialDataSource::~OGRMSSQLSpatialDataSource()
{
int i;
CPLFree( pszName );
CPLFree( pszCatalog );
for( i = 0; i < nLayers; i++ )
delete papoLayers[i];
CPLFree( papoLayers );
for( i = 0; i < nKnownSRID; i++ )
{
if( papoSRS[i] != NULL )
papoSRS[i]->Release();
}
CPLFree( panSRID );
CPLFree( papoSRS );
}
/************************************************************************/
/* TestCapability() */
/************************************************************************/
int OGRMSSQLSpatialDataSource::TestCapability( const char * pszCap )
{
if( EQUAL(pszCap,ODsCCreateLayer) || EQUAL(pszCap,ODsCDeleteLayer) )
return TRUE;
else
return FALSE;
}
/************************************************************************/
/* GetLayer() */
/************************************************************************/
OGRLayer *OGRMSSQLSpatialDataSource::GetLayer( int iLayer )
{
if( iLayer < 0 || iLayer >= nLayers )
return NULL;
else
return papoLayers[iLayer];
}
/************************************************************************/
/* DeleteLayer() */
/************************************************************************/
int OGRMSSQLSpatialDataSource::DeleteLayer( int iLayer )
{
if( iLayer < 0 || iLayer >= nLayers )
return OGRERR_FAILURE;
/* -------------------------------------------------------------------- */
/* Blow away our OGR structures related to the layer. This is */
/* pretty dangerous if anything has a reference to this layer! */
/* -------------------------------------------------------------------- */
const char* pszLayerName = papoLayers[iLayer]->GetTableName();
const char* pszSchemaName = papoLayers[iLayer]->GetSchemaName();
CPLODBCStatement oStmt( &oSession );
if (bUseGeometryColumns)
oStmt.Appendf( "DELETE FROM geometry_columns WHERE f_table_schema = '%s' AND f_table_name = '%s'\n",
pszSchemaName, pszLayerName );
oStmt.Appendf("DROP TABLE [%s].[%s]", pszSchemaName, pszLayerName );
CPLDebug( "MSSQLSpatial", "DeleteLayer(%s)", pszLayerName );
delete papoLayers[iLayer];
memmove( papoLayers + iLayer, papoLayers + iLayer + 1,
sizeof(void *) * (nLayers - iLayer - 1) );
nLayers--;
if ( strlen(pszLayerName) == 0 )
return OGRERR_NONE;
/* -------------------------------------------------------------------- */
/* Remove from the database. */
/* -------------------------------------------------------------------- */
oSession.BeginTransaction();
if( !oStmt.ExecuteSQL() )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Error deleting layer: %s", GetSession()->GetLastError() );
return OGRERR_FAILURE;
}
oSession.CommitTransaction();
return OGRERR_NONE;
}
/************************************************************************/
/* CreateLayer() */
/************************************************************************/
OGRLayer * OGRMSSQLSpatialDataSource::CreateLayer( const char * pszLayerName,
OGRSpatialReference *poSRS,
OGRwkbGeometryType eType,
char ** papszOptions )
{
char *pszTableName = NULL;
char *pszSchemaName = NULL;
const char *pszGeomType = NULL;
const char *pszGeomColumn = NULL;
int nCoordDimension = 3;
/* determine the dimension */
if( eType == wkbFlatten(eType) )
nCoordDimension = 2;
if( CSLFetchNameValue( papszOptions, "DIM") != NULL )
nCoordDimension = atoi(CSLFetchNameValue( papszOptions, "DIM"));
/* MSSQL Schema handling:
Extract schema name from input layer name or passed with -lco SCHEMA.
Set layer name to "schema.table" or to "table" if schema is not
specified
*/
const char* pszDotPos = strstr(pszLayerName,".");
if ( pszDotPos != NULL )
{
int length = pszDotPos - pszLayerName;
pszSchemaName = (char*)CPLMalloc(length+1);
strncpy(pszSchemaName, pszLayerName, length);
pszSchemaName[length] = '\0';
if( CSLFetchBoolean(papszOptions,"LAUNDER", TRUE) )
pszTableName = LaunderName( pszDotPos + 1 ); //skip "."
else
pszTableName = CPLStrdup( pszDotPos + 1 ); //skip "."
}
else
{
pszSchemaName = NULL;
if( CSLFetchBoolean(papszOptions,"LAUNDER", TRUE) )
pszTableName = LaunderName( pszLayerName ); //skip "."
else
pszTableName = CPLStrdup( pszLayerName ); //skip "."
}
if( CSLFetchNameValue( papszOptions, "SCHEMA" ) != NULL )
{
CPLFree(pszSchemaName);
pszSchemaName = CPLStrdup(CSLFetchNameValue( papszOptions, "SCHEMA" ));
}
if (pszSchemaName == NULL)
pszSchemaName = CPLStrdup("dbo");
/* -------------------------------------------------------------------- */
/* Do we already have this layer? If so, should we blow it */
/* away? */
/* -------------------------------------------------------------------- */
int iLayer;
for( iLayer = 0; iLayer < nLayers; iLayer++ )
{
if( EQUAL(pszLayerName,papoLayers[iLayer]->GetTableName()) )
{
if( CSLFetchNameValue( papszOptions, "OVERWRITE" ) != NULL
&& !EQUAL(CSLFetchNameValue(papszOptions,"OVERWRITE"),"NO") )
{
if (!pszSchemaName)
pszSchemaName = CPLStrdup(papoLayers[iLayer]->GetSchemaName());
DeleteLayer( iLayer );
}
else
{
CPLError( CE_Failure, CPLE_AppDefined,
"Layer %s already exists, CreateLayer failed.\n"
"Use the layer creation option OVERWRITE=YES to "
"replace it.",
pszLayerName );
CPLFree( pszSchemaName );
CPLFree( pszTableName );
return NULL;
}
}
}
/* -------------------------------------------------------------------- */
/* Handle the GEOM_TYPE option. */
/* -------------------------------------------------------------------- */
pszGeomType = CSLFetchNameValue( papszOptions, "GEOM_TYPE" );
if( !pszGeomType )
pszGeomType = "geometry";
if( !EQUAL(pszGeomType, "geometry")
&& !EQUAL(pszGeomType, "geography"))
{
CPLError( CE_Failure, CPLE_AppDefined,
"FORMAT=%s not recognised or supported.",
pszGeomType );
CPLFree( pszSchemaName );
CPLFree( pszTableName );
return NULL;
}
/* determine the geometry column name */
pszGeomColumn = CSLFetchNameValue( papszOptions, "GEOM_NAME");
if (!pszGeomColumn)
pszGeomColumn = "ogr_geometry";
/* -------------------------------------------------------------------- */
/* Initialize the metadata tables */
/* -------------------------------------------------------------------- */
if (InitializeMetadataTables() != OGRERR_NONE)
{
CPLFree( pszSchemaName );
CPLFree( pszTableName );
return NULL;
}
/* -------------------------------------------------------------------- */
/* Try to get the SRS Id of this spatial reference system, */
/* adding to the srs table if needed. */
/* -------------------------------------------------------------------- */
int nSRSId = 0;
if( CSLFetchNameValue( papszOptions, "SRID") != NULL )
nSRSId = atoi(CSLFetchNameValue( papszOptions, "SRID"));
if( nSRSId == 0 && poSRS != NULL )
nSRSId = FetchSRSId( poSRS );
/* -------------------------------------------------------------------- */
/* Create a new table and create a new entry in the geometry, */
/* geometry_columns metadata table. */
/* -------------------------------------------------------------------- */
if( eType != wkbNone )
{
const char *pszGeometryType = OGRToOGCGeomType(eType);
CPLODBCStatement oStmt( &oSession );
if (bUseGeometryColumns)
{
oStmt.Appendf( "DELETE FROM geometry_columns WHERE f_table_schema = '%s' "
"AND f_table_name = '%s'\n", pszSchemaName, pszTableName );
oStmt.Appendf("INSERT INTO [geometry_columns] ([f_table_catalog], [f_table_schema] ,[f_table_name], "
"[f_geometry_column],[coord_dimension],[srid],[geometry_type]) VALUES ('%s', '%s', '%s', '%s', %d, %d, '%s')\n",
pszCatalog, pszSchemaName, pszTableName, pszGeomColumn, nCoordDimension, nSRSId, pszGeometryType );
}
oStmt.Appendf("CREATE TABLE [%s].[%s] ([ogr_fid] [int] IDENTITY(1,1) NOT NULL, "
"[%s] [%s] NULL, CONSTRAINT [PK_%s] PRIMARY KEY CLUSTERED ([ogr_fid] ASC))",
pszSchemaName, pszTableName, pszGeomColumn, pszGeomType, pszTableName);
oSession.BeginTransaction();
if( !oStmt.ExecuteSQL() )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Error creating layer: %s", GetSession()->GetLastError() );
return NULL;
}
oSession.CommitTransaction();
}
/* -------------------------------------------------------------------- */
/* Create the layer object. */
/* -------------------------------------------------------------------- */
OGRMSSQLSpatialTableLayer *poLayer;
poLayer = new OGRMSSQLSpatialTableLayer( this );
poLayer->SetLaunderFlag( CSLFetchBoolean(papszOptions,"LAUNDER",TRUE) );
poLayer->SetPrecisionFlag( CSLFetchBoolean(papszOptions,"PRECISION",TRUE));
char *pszWKT = NULL;
if( poSRS && poSRS->exportToWkt( &pszWKT ) != OGRERR_NONE )
{
CPLFree(pszWKT);
pszWKT = NULL;
}
if (poLayer->Initialize(pszSchemaName, pszTableName, pszGeomColumn, nCoordDimension, nSRSId, pszWKT, eType) == OGRERR_FAILURE)
{
CPLFree( pszSchemaName );
CPLFree( pszTableName );
CPLFree( pszWKT );
return NULL;
}
CPLFree( pszSchemaName );
CPLFree( pszTableName );
CPLFree( pszWKT );
/* -------------------------------------------------------------------- */
/* Add layer to data source layer list. */
/* -------------------------------------------------------------------- */
papoLayers = (OGRMSSQLSpatialTableLayer **)
CPLRealloc( papoLayers, sizeof(OGRMSSQLSpatialTableLayer *) * (nLayers+1) );
papoLayers[nLayers++] = poLayer;
return poLayer;
}
/************************************************************************/
/* OpenTable() */
/************************************************************************/
int OGRMSSQLSpatialDataSource::OpenTable( const char *pszSchemaName, const char *pszTableName,
const char *pszGeomCol, int nCoordDimension,
int nSRID, const char *pszSRText, OGRwkbGeometryType eType, int bUpdate )
{
/* -------------------------------------------------------------------- */
/* Create the layer object. */
/* -------------------------------------------------------------------- */
OGRMSSQLSpatialTableLayer *poLayer = new OGRMSSQLSpatialTableLayer( this );
if( poLayer->Initialize( pszSchemaName, pszTableName, pszGeomCol, nCoordDimension, nSRID, pszSRText, eType ) )
{
delete poLayer;
return FALSE;
}
/* -------------------------------------------------------------------- */
/* Add layer to data source layer list. */
/* -------------------------------------------------------------------- */
papoLayers = (OGRMSSQLSpatialTableLayer **)
CPLRealloc( papoLayers, sizeof(OGRMSSQLSpatialTableLayer *) * (nLayers+1) );
papoLayers[nLayers++] = poLayer;
return TRUE;
}
/************************************************************************/
/* GetLayerCount() */
/************************************************************************/
int OGRMSSQLSpatialDataSource::GetLayerCount()
{
return nLayers;
}
/************************************************************************/
/* ParseValue() */
/************************************************************************/
int OGRMSSQLSpatialDataSource::ParseValue(char** pszValue, char* pszSource, const char* pszKey, int nStart, int nNext, int nTerm, int bRemove)
{
int nLen = strlen(pszKey);
if ((*pszValue) == NULL && nStart + nLen < nNext &&
EQUALN(pszSource + nStart, pszKey, nLen))
{
*pszValue = (char*)CPLMalloc( sizeof(char) * (nNext - nStart - nLen + 1) );
if (*pszValue)
strncpy(*pszValue, pszSource + nStart + nLen, nNext - nStart - nLen);
(*pszValue)[nNext - nStart - nLen] = 0;
if (bRemove)
{
// remove the value from the source string
if (pszSource[nNext] == ';')
memmove( pszSource + nStart, pszSource + nNext + 1, nTerm - nNext);
else
memmove( pszSource + nStart, pszSource + nNext, nTerm - nNext + 1);
}
return TRUE;
}
return FALSE;
}
/************************************************************************/
/* Open() */
/************************************************************************/
int OGRMSSQLSpatialDataSource::Open( const char * pszNewName, int bUpdate,
int bTestOpen )
{
CPLAssert( nLayers == 0 );
if( !EQUALN(pszNewName,"MSSQL:",6) )
{
if( !bTestOpen )
CPLError( CE_Failure, CPLE_AppDefined,
"%s does not conform to MSSSQLSpatial naming convention,"
" MSSQL:*\n", pszNewName );
return FALSE;
}
/* Determine if the connection string contains specific values */
char* pszTableSpec = NULL;
char* pszGeometryFormat = NULL;
char* pszConnectionName = CPLStrdup(pszNewName + 6);
char* pszDriver = NULL;
int nCurrent, nNext, nTerm;
nCurrent = nNext = nTerm = strlen(pszConnectionName);
while (nCurrent > 0)
{
--nCurrent;
if (pszConnectionName[nCurrent] == ';')
{
nNext = nCurrent;
continue;
}
if (ParseValue(&pszCatalog, pszConnectionName, "database=",
nCurrent, nNext, nTerm, FALSE))
continue;
if (ParseValue(&pszTableSpec, pszConnectionName, "tables=",
nCurrent, nNext, nTerm, TRUE))
continue;
if (ParseValue(&pszDriver, pszConnectionName, "driver=",
nCurrent, nNext, nTerm, FALSE))
continue;
if (ParseValue(&pszGeometryFormat, pszConnectionName,
"geometryformat=", nCurrent, nNext, nTerm, TRUE))
{
if (EQUALN(pszGeometryFormat,"wkbzm",5))
nGeometryFormat = MSSQLGEOMETRY_WKBZM;
else if (EQUALN(pszGeometryFormat, "wkb",3))
nGeometryFormat = MSSQLGEOMETRY_WKB;
else if (EQUALN(pszGeometryFormat,"wkt",3))
nGeometryFormat = MSSQLGEOMETRY_WKT;
else if (EQUALN(pszGeometryFormat,"native",6))
nGeometryFormat = MSSQLGEOMETRY_NATIVE;
else
{
CPLError( CE_Failure, CPLE_AppDefined,
"Invalid geometry type specified: %s,"
" MSSQL:*\n", pszGeometryFormat );
CPLFree(pszTableSpec);
CPLFree(pszGeometryFormat);
CPLFree(pszConnectionName);
CPLFree(pszDriver);
return FALSE;
}
CPLFree(pszGeometryFormat);
pszGeometryFormat = NULL;
continue;
}
}
/* Determine if the connection string contains the catalog portion */
if( pszCatalog == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined,
"'%s' does not contain the 'database' portion\n", pszNewName );
CPLFree(pszTableSpec);
CPLFree(pszGeometryFormat);
CPLFree(pszConnectionName);
CPLFree(pszDriver);
return FALSE;
}
pszName = CPLStrdup(pszNewName);
char **papszTableNames=NULL;
char **papszSchemaNames=NULL;
char **papszGeomColumnNames=NULL;
char **papszCoordDimensions=NULL;
char **papszSRIds=NULL;
char **papszSRTexts=NULL;
/* Determine if the connection string contains the TABLES portion */
if( pszTableSpec != NULL )
{
char **papszTableList;
int i;
papszTableList = CSLTokenizeString2( pszTableSpec, ",", 0 );
for( i = 0; i < CSLCount(papszTableList); i++ )
{
char **papszQualifiedParts;
// Get schema and table name
papszQualifiedParts = CSLTokenizeString2( papszTableList[i],
".", 0 );
/* Find the geometry column name if specified */
if( CSLCount( papszQualifiedParts ) >= 1 )
{
char* pszGeomColumnName = NULL;
char* pos = strchr(papszQualifiedParts[CSLCount( papszQualifiedParts ) - 1], '(');
if (pos != NULL)
{
*pos = '\0';
pszGeomColumnName = pos+1;
int len = strlen(pszGeomColumnName);
if (len > 0)
pszGeomColumnName[len - 1] = '\0';
}
papszGeomColumnNames = CSLAddString( papszGeomColumnNames,
pszGeomColumnName ? pszGeomColumnName : "");
}
if( CSLCount( papszQualifiedParts ) == 2 )
{
papszSchemaNames = CSLAddString( papszSchemaNames,
papszQualifiedParts[0] );
papszTableNames = CSLAddString( papszTableNames,
papszQualifiedParts[1] );
}
else if( CSLCount( papszQualifiedParts ) == 1 )
{
papszSchemaNames = CSLAddString( papszSchemaNames, "dbo");
papszTableNames = CSLAddString( papszTableNames,
papszQualifiedParts[0] );
}
CSLDestroy(papszQualifiedParts);
}
CSLDestroy(papszTableList);
}
CPLFree(pszTableSpec);
/* Initialize the SQL Server connection. */
int nResult;
if ( pszDriver != NULL )
{
/* driver has been specified */
CPLDebug( "OGR_MSSQLSpatial", "EstablishSession(Connection:\"%s\")", pszConnectionName);
nResult = oSession.EstablishSession( pszConnectionName, "", "" );
}
else
{
/* no driver has been specified, defautls to SQL Server */
CPLDebug( "OGR_MSSQLSpatial", "EstablishSession(Connection:\"%s\")", pszConnectionName);
nResult = oSession.EstablishSession( CPLSPrintf("DRIVER=SQL Server;%s", pszConnectionName), "", "" );
}
CPLFree(pszDriver);
if( !nResult )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Unable to initialize connection to the server for %s,\n"
"%s", pszNewName, oSession.GetLastError() );
CSLDestroy( papszTableNames );
CSLDestroy( papszSchemaNames );
CSLDestroy( papszGeomColumnNames );
CSLDestroy( papszCoordDimensions );
CSLDestroy( papszSRIds );
CSLDestroy( papszSRTexts );
CPLFree(pszGeometryFormat);
CPLFree(pszConnectionName);
return FALSE;
}
char** papszTypes = NULL;
/* Determine the available tables if not specified. */
if (papszTableNames == NULL && bUseGeometryColumns)
{
CPLODBCStatement oStmt( &oSession );
oStmt.Append( "SELECT f_table_schema, f_table_name, f_geometry_column, coord_dimension, g.srid, srtext, geometry_type FROM dbo.geometry_columns g JOIN INFORMATION_SCHEMA.COLUMNS ON f_table_schema = TABLE_SCHEMA and f_table_name = TABLE_NAME and f_geometry_column = COLUMN_NAME left outer join dbo.spatial_ref_sys s on g.srid = s.srid");
if( oStmt.ExecuteSQL() )
{
while( oStmt.Fetch() )
{
papszSchemaNames =
CSLAddString( papszSchemaNames, oStmt.GetColData(0) );
papszTableNames =
CSLAddString( papszTableNames, oStmt.GetColData(1) );
papszGeomColumnNames =
CSLAddString( papszGeomColumnNames, oStmt.GetColData(2) );
papszCoordDimensions =
CSLAddString( papszCoordDimensions, oStmt.GetColData(3) );
papszSRIds =
CSLAddString( papszSRIds, oStmt.GetColData(4) );
papszSRTexts =
CSLAddString( papszSRTexts, oStmt.GetColData(5) );
papszTypes =
CSLAddString( papszTypes, oStmt.GetColData(6) );
}
}
else
bUseGeometryColumns = FALSE;
}
/* Query catalog for tables having geometry columns */
if (papszTableNames == NULL)
{
CPLODBCStatement oStmt( &oSession );
oStmt.Append( "SELECT sys.schemas.name, sys.schemas.name + '.' + sys.objects.name, sys.columns.name from sys.columns join sys.types on sys.columns.system_type_id = sys.types.system_type_id and sys.columns.user_type_id = sys.types.user_type_id join sys.objects on sys.objects.object_id = sys.columns.object_id join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and (sys.objects.type = 'U' or sys.objects.type = 'V')");
if( oStmt.ExecuteSQL() )
{
while( oStmt.Fetch() )
{
papszSchemaNames =
CSLAddString( papszSchemaNames, oStmt.GetColData(0) );
papszTableNames =
CSLAddString( papszTableNames, oStmt.GetColData(1) );
papszGeomColumnNames =
CSLAddString( papszGeomColumnNames, oStmt.GetColData(2) );
}
}
}
int nSRId, nCoordDimension;
OGRwkbGeometryType eType;
for( int iTable = 0;
papszTableNames != NULL && papszTableNames[iTable] != NULL;
iTable++ )
{
if (papszSRIds != NULL)
nSRId = atoi(papszSRIds[iTable]);
else
nSRId = -1;
if (papszCoordDimensions != NULL)
nCoordDimension = atoi(papszCoordDimensions[iTable]);
else
nCoordDimension = 2;
if (papszTypes != NULL)
eType = OGRFromOGCGeomType(papszTypes[iTable]);
else
eType = wkbUnknown;
if( strlen(papszGeomColumnNames[iTable]) > 0 )
OpenTable( papszSchemaNames[iTable], papszTableNames[iTable], papszGeomColumnNames[iTable],
nCoordDimension, nSRId, papszSRTexts? papszSRTexts[iTable] : NULL, eType, bUpdate );
else
OpenTable( papszSchemaNames[iTable], papszTableNames[iTable], NULL,
nCoordDimension, nSRId, papszSRTexts? papszSRTexts[iTable] : NULL, eType, bUpdate );
}
CSLDestroy( papszTableNames );
CSLDestroy( papszSchemaNames );
CSLDestroy( papszGeomColumnNames );
CSLDestroy( papszCoordDimensions );
CSLDestroy( papszSRIds );
CSLDestroy( papszSRTexts );
CSLDestroy( papszTypes );
CPLFree(pszGeometryFormat);
CPLFree(pszConnectionName);
bDSUpdate = bUpdate;
return TRUE;
}
/************************************************************************/
/* ExecuteSQL() */
/************************************************************************/
OGRLayer * OGRMSSQLSpatialDataSource::ExecuteSQL( const char *pszSQLCommand,
OGRGeometry *poSpatialFilter,
const char *pszDialect )
{
/* -------------------------------------------------------------------- */
/* Use generic imlplementation for OGRSQL dialect. */
/* -------------------------------------------------------------------- */
if( pszDialect != NULL && EQUAL(pszDialect,"OGRSQL") )
return OGRDataSource::ExecuteSQL( pszSQLCommand,
poSpatialFilter,
pszDialect );
/* -------------------------------------------------------------------- */
/* Special case DELLAYER: command. */
/* -------------------------------------------------------------------- */
if( EQUALN(pszSQLCommand,"DELLAYER:",9) )
{
const char *pszLayerName = pszSQLCommand + 9;
while( *pszLayerName == ' ' )
pszLayerName++;
for( int iLayer = 0; iLayer < nLayers; iLayer++ )
{
if( EQUAL(papoLayers[iLayer]->GetName(),
pszLayerName ))
{
DeleteLayer( iLayer );
break;
}
}
return NULL;
}
CPLDebug( "MSSQLSpatial", "ExecuteSQL(%s) called.", pszSQLCommand );
if( EQUALN(pszSQLCommand, "DROP SPATIAL INDEX ON ", 22) )
{
/* Handle command to drop a spatial index. */
OGRMSSQLSpatialTableLayer *poLayer = new OGRMSSQLSpatialTableLayer( this );
if (poLayer)
{
if( poLayer->Initialize( "dbo", pszSQLCommand + 22, NULL, 0, 0, NULL, wkbUnknown ) != CE_None )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Failed to initialize layer '%s'", pszSQLCommand + 22 );
}
poLayer->DropSpatialIndex();
delete poLayer;
}
return NULL;
}
else if( EQUALN(pszSQLCommand, "CREATE SPATIAL INDEX ON ", 24) )
{
/* Handle command to create a spatial index. */
OGRMSSQLSpatialTableLayer *poLayer = new OGRMSSQLSpatialTableLayer( this );
if (poLayer)
{
if( poLayer->Initialize( "dbo", pszSQLCommand + 24, NULL, 0, 0, NULL, wkbUnknown ) != CE_None )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Failed to initialize layer '%s'", pszSQLCommand + 24 );
}
poLayer->CreateSpatialIndex();
delete poLayer;
}
return NULL;
}
/* Execute the command natively */
CPLODBCStatement *poStmt = new CPLODBCStatement( &oSession );
poStmt->Append( pszSQLCommand );
if( !poStmt->ExecuteSQL() )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s", oSession.GetLastError() );
delete poStmt;
return NULL;
}
/* -------------------------------------------------------------------- */
/* Are there result columns for this statement? */
/* -------------------------------------------------------------------- */
if( poStmt->GetColCount() == 0 )
{
delete poStmt;
CPLErrorReset();
return NULL;
}
/* -------------------------------------------------------------------- */
/* Create a results layer. It will take ownership of the */
/* statement. */
/* -------------------------------------------------------------------- */
OGRMSSQLSpatialSelectLayer *poLayer = NULL;
poLayer = new OGRMSSQLSpatialSelectLayer( this, poStmt );
if( poSpatialFilter != NULL )
poLayer->SetSpatialFilter( poSpatialFilter );
return poLayer;
}
/************************************************************************/
/* ReleaseResultSet() */
/************************************************************************/
void OGRMSSQLSpatialDataSource::ReleaseResultSet( OGRLayer * poLayer )
{
delete poLayer;
}
/************************************************************************/
/* LaunderName() */
/************************************************************************/
char *OGRMSSQLSpatialDataSource::LaunderName( const char *pszSrcName )
{
char *pszSafeName = CPLStrdup( pszSrcName );
int i;
for( i = 0; pszSafeName[i] != '\0'; i++ )
{
pszSafeName[i] = (char) tolower( pszSafeName[i] );
if( pszSafeName[i] == '-' || pszSafeName[i] == '#' )
pszSafeName[i] = '_';
}
return pszSafeName;
}
/************************************************************************/
/* InitializeMetadataTables() */
/* */
/* Create the metadata tables (SPATIAL_REF_SYS and */
/* GEOMETRY_COLUMNS). */
/************************************************************************/
OGRErr OGRMSSQLSpatialDataSource::InitializeMetadataTables()
{
if (bUseGeometryColumns)
{
CPLODBCStatement oStmt( &oSession );
oStmt.Append( "IF NOT EXISTS (SELECT * FROM sys.objects WHERE "
"object_id = OBJECT_ID(N'[dbo].[geometry_columns]') AND type in (N'U')) "
"CREATE TABLE geometry_columns (f_table_catalog varchar(128) not null, "
"f_table_schema varchar(128) not null, f_table_name varchar(256) not null, "
"f_geometry_column varchar(256) not null, coord_dimension integer not null, "
"srid integer not null, geometry_type varchar(30) not null, "
"CONSTRAINT geometry_columns_pk PRIMARY KEY (f_table_catalog, "
"f_table_schema, f_table_name, f_geometry_column));\n" );
oStmt.Append( "IF NOT EXISTS (SELECT * FROM sys.objects "
"WHERE object_id = OBJECT_ID(N'[dbo].[spatial_ref_sys]') AND type in (N'U')) "
"CREATE TABLE spatial_ref_sys (srid integer not null "
"PRIMARY KEY, auth_name varchar(256), auth_srid integer, srtext varchar(2048), proj4text varchar(2048))" );
oSession.BeginTransaction();
if( !oStmt.ExecuteSQL() )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Error initializing the metadata tables : %s", GetSession()->GetLastError() );
return OGRERR_FAILURE;
}
oSession.CommitTransaction();
}
return OGRERR_NONE;
}
/************************************************************************/
/* FetchSRS() */
/* */
/* Return a SRS corresponding to a particular id. Note that */
/* reference counting should be honoured on the returned */
/* OGRSpatialReference, as handles may be cached. */
/************************************************************************/
OGRSpatialReference *OGRMSSQLSpatialDataSource::FetchSRS( int nId )
{
if( nId <= 0 )
return NULL;
/* -------------------------------------------------------------------- */
/* First, we look through our SRID cache, is it there? */
/* -------------------------------------------------------------------- */
int i;
for( i = 0; i < nKnownSRID; i++ )
{
if( panSRID[i] == nId )
return papoSRS[i];
}
OGRSpatialReference *poSRS = NULL;
/* -------------------------------------------------------------------- */
/* Try looking up in spatial_ref_sys table */
/* -------------------------------------------------------------------- */
if (bUseGeometryColumns)
{
CPLODBCStatement oStmt( GetSession() );
oStmt.Appendf( "SELECT srtext FROM spatial_ref_sys WHERE srid = %d", nId );
if( oStmt.ExecuteSQL() && oStmt.Fetch() )
{
if ( oStmt.GetColData( 0 ) )
{
poSRS = new OGRSpatialReference();
char* pszWKT = (char*)oStmt.GetColData( 0 );
if( poSRS->importFromWkt( &pszWKT ) != OGRERR_NONE )
{
delete poSRS;
poSRS = NULL;
}
}
}
}
/* -------------------------------------------------------------------- */
/* Try looking up the EPSG list */
/* -------------------------------------------------------------------- */
if (!poSRS)
{
poSRS = new OGRSpatialReference();
if( poSRS->importFromEPSG( nId ) != OGRERR_NONE )
{
delete poSRS;
poSRS = NULL;
}
}
/* -------------------------------------------------------------------- */
/* Add to the cache. */
/* -------------------------------------------------------------------- */
if (poSRS)
{
panSRID = (int *) CPLRealloc(panSRID,sizeof(int) * (nKnownSRID+1) );
papoSRS = (OGRSpatialReference **)
CPLRealloc(papoSRS, sizeof(void*) * (nKnownSRID + 1) );
panSRID[nKnownSRID] = nId;
papoSRS[nKnownSRID] = poSRS;
nKnownSRID++;
}
return poSRS;
}
/************************************************************************/
/* FetchSRSId() */
/* */
/* Fetch the id corresponding to an SRS, and if not found, add */
/* it to the table. */
/************************************************************************/
int OGRMSSQLSpatialDataSource::FetchSRSId( OGRSpatialReference * poSRS)
{
char *pszWKT = NULL;
int nSRSId = 0;
const char* pszAuthorityName;
if( poSRS == NULL )
return 0;
OGRSpatialReference oSRS(*poSRS);
poSRS = NULL;
pszAuthorityName = oSRS.GetAuthorityName(NULL);
if( pszAuthorityName == NULL || strlen(pszAuthorityName) == 0 )
{
/* -------------------------------------------------------------------- */
/* Try to identify an EPSG code */
/* -------------------------------------------------------------------- */
oSRS.AutoIdentifyEPSG();
pszAuthorityName = oSRS.GetAuthorityName(NULL);
if (pszAuthorityName != NULL && EQUAL(pszAuthorityName, "EPSG"))
{
const char* pszAuthorityCode = oSRS.GetAuthorityCode(NULL);
if ( pszAuthorityCode != NULL && strlen(pszAuthorityCode) > 0 )
{
/* Import 'clean' SRS */
oSRS.importFromEPSG( atoi(pszAuthorityCode) );
pszAuthorityName = oSRS.GetAuthorityName(NULL);
}
}
}
/* -------------------------------------------------------------------- */
/* Check whether the EPSG authority code is already mapped to a */
/* SRS ID. */
/* -------------------------------------------------------------------- */
int nAuthorityCode = 0;
if( pszAuthorityName != NULL && EQUAL( pszAuthorityName, "EPSG" ) )
{
/* For the root authority name 'EPSG', the authority code
* should always be integral
*/
nAuthorityCode = atoi( oSRS.GetAuthorityCode(NULL) );
CPLODBCStatement oStmt( &oSession );
oStmt.Appendf("SELECT srid FROM spatial_ref_sys WHERE "
"auth_name = '%s' AND auth_srid = %d",
pszAuthorityName,
nAuthorityCode );
if( oStmt.ExecuteSQL() && oStmt.Fetch() && oStmt.GetColData( 0 ) )
{
nSRSId = atoi(oStmt.GetColData( 0 ));
return nSRSId;
}
}
/* -------------------------------------------------------------------- */
/* Translate SRS to WKT. */
/* -------------------------------------------------------------------- */
if( oSRS.exportToWkt( &pszWKT ) != OGRERR_NONE )
{
CPLFree(pszWKT);
return 0;
}
/* -------------------------------------------------------------------- */
/* Try to find in the existing table. */
/* -------------------------------------------------------------------- */
CPLODBCStatement oStmt( &oSession );
oStmt.Append( "SELECT srid FROM spatial_ref_sys WHERE srtext = ");
OGRMSSQLAppendEscaped(&oStmt, pszWKT);
/* -------------------------------------------------------------------- */
/* We got it! Return it. */
/* -------------------------------------------------------------------- */
if( oStmt.ExecuteSQL() )
{
if ( oStmt.Fetch() && oStmt.GetColData( 0 ) )
{
nSRSId = atoi(oStmt.GetColData( 0 ));
CPLFree(pszWKT);
return nSRSId;
}
}
else
{
/* probably the table is missing at all */
if( InitializeMetadataTables() != OGRERR_NONE )
{
CPLFree(pszWKT);
return 0;
}
}
/* -------------------------------------------------------------------- */
/* Try adding the SRS to the SRS table. */
/* -------------------------------------------------------------------- */
char *pszProj4 = NULL;
if( oSRS.exportToProj4( &pszProj4 ) != OGRERR_NONE )
{
CPLFree( pszProj4 );
CPLFree(pszWKT);
return 0;
}
/* -------------------------------------------------------------------- */
/* Check whether the auth_code can be used as srid. */
/* -------------------------------------------------------------------- */
nSRSId = nAuthorityCode;
oStmt.Clear();
oSession.BeginTransaction();
if (nAuthorityCode > 0)
{
oStmt.Appendf("SELECT srid FROM spatial_ref_sys where srid = %d", nAuthorityCode);
if ( oStmt.ExecuteSQL() && oStmt.Fetch())
{
nSRSId = 0;
}
}
/* -------------------------------------------------------------------- */
/* Get the current maximum srid in the srs table. */
/* -------------------------------------------------------------------- */
if (nSRSId == 0)
{
oStmt.Clear();
oStmt.Append("SELECT COALESCE(MAX(srid) + 1, 32768) FROM spatial_ref_sys where srid between 32768 and 65536");
if ( oStmt.ExecuteSQL() && oStmt.Fetch() && oStmt.GetColData( 0 ) )
{
nSRSId = atoi(oStmt.GetColData( 0 ));
}
}
if (nSRSId == 0)
{
/* unable to allocate srid */
oSession.RollbackTransaction();
CPLFree( pszProj4 );
CPLFree(pszWKT);
return 0;
}
oStmt.Clear();
if( nAuthorityCode > 0 )
{
oStmt.Appendf(
"INSERT INTO spatial_ref_sys (srid, auth_srid, auth_name, srtext, proj4text) "
"VALUES (%d, %d, ", nSRSId, nAuthorityCode );
OGRMSSQLAppendEscaped(&oStmt, pszAuthorityName);
oStmt.Append(", ");
OGRMSSQLAppendEscaped(&oStmt, pszWKT);
oStmt.Append(", ");
OGRMSSQLAppendEscaped(&oStmt, pszProj4);
oStmt.Append(")");
}
else
{
oStmt.Appendf(
"INSERT INTO spatial_ref_sys (srid,srtext,proj4text) VALUES (%d, ", nSRSId);
OGRMSSQLAppendEscaped(&oStmt, pszWKT);
oStmt.Append(", ");
OGRMSSQLAppendEscaped(&oStmt, pszProj4);
oStmt.Append(")");
}
/* Free everything that was allocated. */
CPLFree( pszProj4 );
CPLFree( pszWKT);
if ( oStmt.ExecuteSQL() )
oSession.CommitTransaction();
else
oSession.RollbackTransaction();
return nSRSId;
}
|