File: FGdbDatasource.cpp

package info (click to toggle)
gdal 1.10.1+dfsg-8
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 84,320 kB
  • ctags: 74,726
  • sloc: cpp: 677,199; ansic: 162,820; python: 13,816; cs: 11,163; sh: 10,446; java: 5,279; perl: 4,429; php: 2,971; xml: 1,500; yacc: 934; makefile: 494; sql: 112
file content (498 lines) | stat: -rw-r--r-- 18,810 bytes parent folder | download
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
/******************************************************************************
 * $Id: FGdbDatasource.cpp 26310 2013-08-13 19:54:26Z rouault $
 *
 * Project:  OpenGIS Simple Features Reference Implementation
 * Purpose:  Implements FileGDB OGR Datasource.
 * Author:   Ragi Yaser Burhum, ragi@burhum.com
 *           Paul Ramsey, pramsey at cleverelephant.ca
 *
 ******************************************************************************
 * Copyright (c) 2010, Ragi Yaser Burhum
 * Copyright (c) 2011, Paul Ramsey <pramsey at cleverelephant.ca>
 *
 * 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_fgdb.h"
#include "cpl_conv.h"
#include "cpl_string.h"
#include "gdal.h"
#include "FGdbUtils.h"

CPL_CVSID("$Id: FGdbDatasource.cpp 26310 2013-08-13 19:54:26Z rouault $");

using std::vector;
using std::wstring;

/************************************************************************/
/*                          FGdbDataSource()                           */
/************************************************************************/

FGdbDataSource::FGdbDataSource(FGdbDriver* poDriver):
OGRDataSource(),
m_poDriver(poDriver), m_pszName(0), m_pGeodatabase(NULL)
{
}

/************************************************************************/
/*                          ~FGdbDataSource()                          */
/************************************************************************/

FGdbDataSource::~FGdbDataSource()
{
    size_t count = m_layers.size();
    for(size_t i = 0; i < count; ++i )
        delete m_layers[i];

    m_poDriver->Release( m_pszName );
    CPLFree( m_pszName );
}


/************************************************************************/
/*                                Open()                                */
/************************************************************************/

int FGdbDataSource::Open(Geodatabase* pGeodatabase, const char * pszNewName, int bUpdate )
{
    m_pszName = CPLStrdup( pszNewName );
    m_pGeodatabase = pGeodatabase;

    std::vector<std::wstring> typesRequested;

	// We're only interested in Tables, Feature Datasets and Feature Classes
	typesRequested.push_back(L"Feature Class");
	typesRequested.push_back(L"Table");
	typesRequested.push_back(L"Feature Dataset");
	
    bool rv = LoadLayers(L"\\");

    return rv;
}

/************************************************************************/
/*                          OpenFGDBTables()                            */
/************************************************************************/

bool FGdbDataSource::OpenFGDBTables(const std::wstring &type,
                                    const std::vector<std::wstring> &layers)
{
    fgdbError hr;
    for ( unsigned int i = 0; i < layers.size(); i++ )
    {
        Table* pTable = new Table;
        //CPLDebug("FGDB", "Opening %s", WStringToString(layers[i]).c_str());
        if (FAILED(hr = m_pGeodatabase->OpenTable(layers[i], *pTable)))
        {
            delete pTable;
            GDBDebug(hr, "Error opening " + WStringToString(layers[i]) + ". Skipping it");
            continue;
        }
        FGdbLayer* pLayer = new FGdbLayer;
        if (!pLayer->Initialize(this, pTable, layers[i], type))
        {
            delete pLayer;
            return GDBErr(hr, "Error initializing OGRLayer for " + WStringToString(layers[i]));
        }

        m_layers.push_back(pLayer);
    }
    return true;
}

/************************************************************************/
/*                            LoadLayers()                             */
/************************************************************************/

bool FGdbDataSource::LoadLayers(const std::wstring &root) 
{
    std::vector<wstring> tables;
    std::vector<wstring> featureclasses;
    std::vector<wstring> featuredatasets;
    fgdbError hr;

    /* Find all the Tables in the root */
    if ( FAILED(hr = m_pGeodatabase->GetChildDatasets(root, L"Table", tables)) )
    {
        return GDBErr(hr, "Error reading Tables in " + WStringToString(root));
    }
    /* Open the tables we found */
    if ( tables.size() > 0 && ! OpenFGDBTables(L"Table", tables) )
        return false;

    /* Find all the Feature Classes in the root */
    if ( FAILED(hr = m_pGeodatabase->GetChildDatasets(root, L"Feature Class", featureclasses)) )
    {
        return GDBErr(hr, "Error reading Feature Classes in " + WStringToString(root));
    }
    /* Open the tables we found */
    if ( featureclasses.size() > 0 && ! OpenFGDBTables(L"Feature Class", featureclasses) )
        return false;

    /* Find all the Feature Datasets in the root */
    if ( FAILED(hr = m_pGeodatabase->GetChildDatasets(root, L"Feature Dataset", featuredatasets)) )
    {
        return GDBErr(hr, "Error reading Feature Datasets in " + WStringToString(root));
    }
    /* Look for Feature Classes inside the Feature Dataset */
    for ( unsigned int i = 0; i < featuredatasets.size(); i++ )
    {
        if ( FAILED(hr = m_pGeodatabase->GetChildDatasets(featuredatasets[i], L"Feature Class", featureclasses)) )
        {
            return GDBErr(hr, "Error reading Feature Classes in " + WStringToString(featuredatasets[i]));
        }
        if ( featureclasses.size() > 0 && ! OpenFGDBTables(L"Feature Class", featureclasses) )
            return false;
    }
    return true;
}


#if 0
/************************************************************************/
/*                            LoadLayersOld()                              */
/************************************************************************/

/* Old recursive LoadLayers. Removed in favor of simple one that only
   looks at FeatureClasses and Tables. */

// Flattens out hierarchichal GDB structure
bool FGdbDataSource::LoadLayersOld(const std::vector<wstring> & datasetTypes,
                                const wstring & parent)
{
    long hr = S_OK;

    // I didn't find an API to give me the type of the dataset based on name - I am *not*
    // parsing XML for something like this - in the meantime I can use this hack to see
    // if the dataset had any children whatsoever - if so, then I won't attempt to open it
    // otherwise, do attempt to do that

    bool childrenFound = false;
    bool errorsEncountered = false;

    for (size_t dsTypeIndex = 0; dsTypeIndex < datasetTypes.size(); dsTypeIndex++)
    {
        std::vector<wstring> childDatasets;
        m_pGeodatabase->GetChildDatasets( parent, datasetTypes[dsTypeIndex], childDatasets);

        if (childDatasets.size() > 0)
        {
            //it is a container of other datasets

            for (size_t childDatasetIndex = 0;
                 childDatasetIndex < childDatasets.size();
                 childDatasetIndex++)
            {
                childrenFound = true;

                // do something with it
                // For now, we just ignore dataset containers and only open the children
                //std::wcout << datasetTypes[dsTypeIndex] << L" " << childDatasets[childDatasetIndex] << std::endl;

                if (!LoadLayersOld(datasetTypes, childDatasets[childDatasetIndex]))
                    errorsEncountered = true;
            }
        }
    }

    //it is a full fledged dataset itself without children - open it (except the root)

    if ((!childrenFound) && parent != L"\\")
    {
        //wcout << "Opening " << parent << "...";
        Table* pTable = new Table;
        if (FAILED(hr = m_pGeodatabase->OpenTable(parent,*pTable)))
        {
            delete pTable;
            return GDBErr(hr, "Error opening " + WStringToString(parent));
        }

        FGdbLayer* pLayer = new FGdbLayer;

        //pLayer has ownership of the table pointer as soon Initialize is called
        if (!pLayer->Initialize(this, pTable, parent))
        {
            delete pLayer;

            return GDBErr(hr, "Error initializing OGRLayer for " +
                          WStringToString(parent));
        }

        m_layers.push_back(pLayer);
    }

    return !errorsEncountered;
}
#endif


/************************************************************************/
/*                            DeleteLayer()                             */
/************************************************************************/

OGRErr FGdbDataSource::DeleteLayer( int iLayer )
{
    if( iLayer < 0 || iLayer >= static_cast<int>(m_layers.size()) )
        return OGRERR_FAILURE;

    // Fetch FGDBAPI Table before deleting OGR layer object

    Table* pTable = m_layers[iLayer]->GetTable();

    std::string name = m_layers[iLayer]->GetLayerDefn()->GetName();
    std::wstring strPath = m_layers[iLayer]->GetTablePath();
    std::wstring strType = m_layers[iLayer]->GetType();

    // delete OGR layer
    delete m_layers[iLayer];

    pTable = NULL; // OGR Layer had ownership of FGDB Table

    m_layers.erase(m_layers.begin() + iLayer);

    long hr;
  
    if (FAILED(hr = m_pGeodatabase->Delete(strPath, strType)))
    {
        CPLError( CE_Warning, CPLE_AppDefined,
                 "%s was not deleted however it has been closed", name.c_str());
        GDBErr(hr, "Failed deleting dataset");
        return OGRERR_FAILURE;
    }

    return OGRERR_NONE;
}

/************************************************************************/
/*                           TestCapability()                           */
/************************************************************************/

int FGdbDataSource::TestCapability( const char * pszCap )
{
    if( EQUAL(pszCap,ODsCCreateLayer) )
        return TRUE;

    else if( EQUAL(pszCap,ODsCDeleteLayer) )
        return TRUE;

    return FALSE;
}


/************************************************************************/
/*                              GetLayer()                              */
/************************************************************************/

OGRLayer *FGdbDataSource::GetLayer( int iLayer )
{ 
    int count = static_cast<int>(m_layers.size());

    if( iLayer < 0 || iLayer >= count )
        return NULL;
    else
        return m_layers[iLayer];
}

/************************************************************************/
/*                              CreateLayer()                           */
/*                                                                      */
/* See FGdbLayer::Create for creation options                           */
/************************************************************************/

OGRLayer *
FGdbDataSource::CreateLayer( const char * pszLayerName,
                              OGRSpatialReference *poSRS,
                              OGRwkbGeometryType eType,
                              char ** papszOptions )
{
    FGdbLayer* pLayer = new FGdbLayer;
    if (!pLayer->Create(this, pszLayerName, poSRS, eType, papszOptions))
    {
        delete pLayer;
        return NULL;
    }

    m_layers.push_back(pLayer);

    return pLayer;  
}


/************************************************************************/
/*                   OGRFGdbSingleFeatureLayer                          */
/************************************************************************/

class OGRFGdbSingleFeatureLayer : public OGRLayer
{
  private:
    char               *pszVal;
    OGRFeatureDefn     *poFeatureDefn;
    int                 iNextShapeId;

  public:
                        OGRFGdbSingleFeatureLayer( const char* pszLayerName,
                                                   const char *pszVal );
                        ~OGRFGdbSingleFeatureLayer();

    virtual void        ResetReading() { iNextShapeId = 0; }
    virtual OGRFeature *GetNextFeature();
    virtual OGRFeatureDefn *GetLayerDefn() { return poFeatureDefn; }
    virtual int         TestCapability( const char * ) { return FALSE; }
};

/************************************************************************/
/*                    OGRFGdbSingleFeatureLayer()                       */
/************************************************************************/

OGRFGdbSingleFeatureLayer::OGRFGdbSingleFeatureLayer(const char* pszLayerName,
                                                     const char *pszVal )
{
    poFeatureDefn = new OGRFeatureDefn( pszLayerName );
    poFeatureDefn->Reference();
    OGRFieldDefn oField( "FIELD_1", OFTString );
    poFeatureDefn->AddFieldDefn( &oField );

    iNextShapeId = 0;
    this->pszVal = pszVal ? CPLStrdup(pszVal) : NULL;
}

/************************************************************************/
/*                   ~OGRFGdbSingleFeatureLayer()                       */
/************************************************************************/

OGRFGdbSingleFeatureLayer::~OGRFGdbSingleFeatureLayer()
{
    if( poFeatureDefn != NULL )
        poFeatureDefn->Release();
    CPLFree(pszVal);
}


/************************************************************************/
/*                           GetNextFeature()                           */
/************************************************************************/

OGRFeature * OGRFGdbSingleFeatureLayer::GetNextFeature()
{
    if (iNextShapeId != 0)
        return NULL;

    OGRFeature* poFeature = new OGRFeature(poFeatureDefn);
    if (pszVal)
        poFeature->SetField(0, pszVal);
    poFeature->SetFID(iNextShapeId ++);
    return poFeature;
}

/************************************************************************/
/*                              ExecuteSQL()                            */
/************************************************************************/

OGRLayer * FGdbDataSource::ExecuteSQL( const char *pszSQLCommand,
                                       OGRGeometry *poSpatialFilter,
                                       const char *pszDialect )

{
    if ( pszDialect != NULL && EQUAL(pszDialect, "OGRSQL") )
        return OGRDataSource::ExecuteSQL( pszSQLCommand,
                                          poSpatialFilter,
                                          pszDialect );

/* -------------------------------------------------------------------- */
/*      Special case GetLayerDefinition                                 */
/* -------------------------------------------------------------------- */
    if (EQUALN(pszSQLCommand, "GetLayerDefinition ", strlen("GetLayerDefinition ")))
    {
        FGdbLayer* poLayer = (FGdbLayer*) GetLayerByName(pszSQLCommand + strlen("GetLayerDefinition "));
        if (poLayer)
        {
            char* pszVal = NULL;
            poLayer->GetLayerXML(&pszVal);
            OGRLayer* poRet = new OGRFGdbSingleFeatureLayer( "LayerDefinition", pszVal );
            CPLFree(pszVal);
            return poRet;
        }
        else
            return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Special case GetLayerMetadata                                   */
/* -------------------------------------------------------------------- */
    if (EQUALN(pszSQLCommand, "GetLayerMetadata ", strlen("GetLayerMetadata ")))
    {
        FGdbLayer* poLayer = (FGdbLayer*) GetLayerByName(pszSQLCommand + strlen("GetLayerMetadata "));
        if (poLayer)
        {
            char* pszVal = NULL;
            poLayer->GetLayerMetadataXML(&pszVal);
            OGRLayer* poRet = new OGRFGdbSingleFeatureLayer( "LayerMetadata", pszVal );
            CPLFree(pszVal);
            return poRet;
        }
        else
            return NULL;
    }

    /* TODO: remove that workaround when the SDK has finally a decent */
    /* SQL support ! */
    if( EQUALN(pszSQLCommand, "SELECT ", 7) && pszDialect == NULL )
    {
        CPLDebug("FGDB", "Support for SELECT is known to be partially "
                         "non-compliant with FileGDB SDK API v1.2.\n"
                         "So for now, we use default OGR SQL engine. "
                         "Explicitly specify -dialect FileGDB\n"
                         "to use the SQL engine from the FileGDB SDK API");
        return OGRDataSource::ExecuteSQL( pszSQLCommand,
                                        poSpatialFilter,
                                        pszDialect );
    }

/* -------------------------------------------------------------------- */
/*      Run the SQL                                                     */
/* -------------------------------------------------------------------- */
    EnumRows* pEnumRows = new EnumRows;
    long hr;
    if (FAILED(hr = m_pGeodatabase->ExecuteSQL(
                                StringToWString(pszSQLCommand), true, *pEnumRows)))
    {
        GDBErr(hr, CPLSPrintf("Failed at executing '%s'", pszSQLCommand));
        delete pEnumRows;
        return NULL;
    }

    if( EQUALN(pszSQLCommand, "SELECT ", 7) )
    {
        return new FGdbResultLayer(this, pszSQLCommand, pEnumRows);
    }
    else
    {
        delete pEnumRows;
        return NULL;
    }
}

/************************************************************************/
/*                           ReleaseResultSet()                         */
/************************************************************************/

void FGdbDataSource::ReleaseResultSet( OGRLayer * poResultsSet )
{
    delete poResultsSet;
}