uint32 ReadScriptDescriptor::GetTableSize(const string& table_name) {
	uint32 size = 0;

	OpenTable(table_name);
	size = GetTableSize();
	CloseTable();
	return size;
}
Beispiel #2
0
uint32 ReadScriptDescriptor::GetTableSize(const std::string &table_name)
{
    uint32 size = 0;

    if (OpenTable(table_name)) {
        size = GetTableSize();
        CloseTable();
    }
    return size;
}
Beispiel #3
0
uint32 ReadScriptDescriptor::GetTableSize(int32 table_name)
{
    uint32 size = 0;

    if (OpenTable(table_name)) {
        size = GetTableSize();
        CloseTable();
    }

    return size;
}
Beispiel #4
0
std::string ReadScriptDescriptor::OpenTablespace() {
	if (!IsFileOpen()) {
		PRINT_ERROR << "Can't open a table space without opening a script file." << std::endl;
		return std::string();
	}

	// file extension or path information (for example, 'dat/maps/demo.lua' has a tablespace name of 'demo').
	int32 period = _filename.find(".");
	int32 last_slash = _filename.find_last_of("/");
	std::string tablespace = _filename.substr(last_slash + 1, period - (last_slash + 1));

	if (tablespace.empty()) {
	    PRINT_ERROR << "The script filename is not valid to be used as tablespace name: " << _filename << std::endl;
		return std::string();
	}

	OpenTable(tablespace, true); // Open the tablespace from the global stack.
	return tablespace;
}
string ReadScriptDescriptor::OpenTablespace() {
	if (IsFileOpen() == false) {
		IF_PRINT_WARNING(SCRIPT_DEBUG) << "Function invoked when file was not open." << endl;
		return string();
	}

	// Extract the tablespace name from the filename. For example, 'lua/data/maps/demo.lua' has a tablespace name of 'demo')
	uint32 period = _filename.find(".");
	uint32 last_slash = _filename.find_last_of("/");
	string tablespace = _filename.substr(last_slash + 1, period - (last_slash + 1));

	if (tablespace.empty() == true) {
	    IF_PRINT_WARNING(SCRIPT_DEBUG) << "Failed to open tablespace for file: " << _filename << endl;
		return tablespace;
	}

	OpenTable(tablespace);
	return tablespace;
}
Beispiel #6
0
std::string ReadScriptDescriptor::OpenTablespace()
{
    if(!IsFileOpen()) {
        PRINT_ERROR << "Can't open a table space without opening a script file." << std::endl;
        return std::string();
    }

    std::string tablespace = GetTableSpace();

    if(tablespace.empty()) {
        PRINT_ERROR << "The script filename is not valid to be used as tablespace name: " << _filename << std::endl;
        return std::string();
    }

    if (OpenTable(tablespace, true)) // Open the tablespace from the global stack.
        return tablespace;
    else
        return std::string();
}
int OGRMySQLDataSource::Open( const char * pszNewName, int bUpdate,
                              int bTestOpen )

{
    CPLAssert( nLayers == 0 );

/* -------------------------------------------------------------------- */
/*      Verify MySQL prefix.                                            */
/* -------------------------------------------------------------------- */
    if( !EQUALN(pszNewName,"MYSQL:",6) )
    {
        if( !bTestOpen )
            CPLError( CE_Failure, CPLE_AppDefined, 
                      "%s does not conform to MySQL naming convention,"
                      " MYSQL:dbname[, user=..][,password=..][,host=..][,port=..][tables=table;table;...]",
                      pszNewName );
        return FALSE;
    }
    
/* -------------------------------------------------------------------- */
/*      Use options process to get .my.cnf file contents.               */
/* -------------------------------------------------------------------- */
    int nPort = 0, i;
    char **papszTableNames=NULL;
    std::string oHost, oPassword, oUser, oDB;
    char *apszArgv[2] = { (char*) "org", NULL };
    char **papszArgv = apszArgv;
    int  nArgc = 1;
    const char *client_groups[] = {"client", "ogr", NULL };

    my_init(); // I hope there is no problem with calling this multiple times!
    load_defaults( "my", client_groups, &nArgc, &papszArgv );

    for( i = 0; i < nArgc; i++ )
    {
        if( EQUALN(papszArgv[i],"--user="******"--host=",7) )
            oHost = papszArgv[i] + 7;
        else if( EQUALN(papszArgv[i],"--password="******"--port=",7) )
            nPort = atoi(papszArgv[i] + 7);
    }

    // cleanup
    free_defaults( papszArgv );

/* -------------------------------------------------------------------- */
/*      Parse out connection information.                               */
/* -------------------------------------------------------------------- */
    char **papszItems = CSLTokenizeString2( pszNewName+6, ",", 
                                            CSLT_HONOURSTRINGS );

    if( CSLCount(papszItems) < 1 )
    {
        CSLDestroy( papszItems );
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "MYSQL: request missing databasename." );
        return FALSE;
    }

    oDB = papszItems[0];

    for( i = 1; papszItems[i] != NULL; i++ )
    {
        if( EQUALN(papszItems[i],"user="******"password="******"host=",5) )
            oHost = papszItems[i] + 5;
        else if( EQUALN(papszItems[i],"port=",5) )
            nPort = atoi(papszItems[i] + 5);
        else if( EQUALN(papszItems[i],"tables=",7) )
        {
            papszTableNames = CSLTokenizeStringComplex( 
                papszItems[i] + 7, ";", FALSE, FALSE );
        }
        else
            CPLError( CE_Warning, CPLE_AppDefined, 
                      "'%s' in MYSQL datasource definition not recognised and ignored.", papszItems[i] );
    }

    CSLDestroy( papszItems );

/* -------------------------------------------------------------------- */
/*      Try to establish connection.                                    */
/* -------------------------------------------------------------------- */
    hConn = mysql_init( NULL );

    if( hConn == NULL )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "mysql_init() failed." );
    }

/* -------------------------------------------------------------------- */
/*      Set desired options on the connection: charset and timeout.     */
/* -------------------------------------------------------------------- */
    if( hConn )
    {
        const char *pszTimeoutLength = 
            CPLGetConfigOption( "MYSQL_TIMEOUT", "0" );  
        
        unsigned int timeout = atoi(pszTimeoutLength);        
        mysql_options(hConn, MYSQL_OPT_CONNECT_TIMEOUT, (char*)&timeout);

        mysql_options(hConn, MYSQL_SET_CHARSET_NAME, "utf8" );
    }
    
/* -------------------------------------------------------------------- */
/*      Perform connection.                                             */
/* -------------------------------------------------------------------- */
    if( hConn
        && mysql_real_connect( hConn, 
                               oHost.length() ? oHost.c_str() : NULL,
                               oUser.length() ? oUser.c_str() : NULL,
                               oPassword.length() ? oPassword.c_str() : NULL,
                               oDB.length() ? oDB.c_str() : NULL,
                               nPort, NULL, CLIENT_INTERACTIVE ) == NULL )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "MySQL connect failed for: %s\n%s", 
                  pszNewName + 6, mysql_error( hConn ) );
        mysql_close( hConn );
        hConn = NULL;
    }

    if( hConn == NULL )
    {
        CSLDestroy( papszTableNames );
        return FALSE;
    }
    
    pszName = CPLStrdup( pszNewName );
    
    bDSUpdate = bUpdate;

/* -------------------------------------------------------------------- */
/*      Get a list of available tables.                                 */
/* -------------------------------------------------------------------- */
    if( papszTableNames == NULL )
    {
        MYSQL_RES *hResultSet;
        MYSQL_ROW papszRow;

        if( mysql_query( hConn, "SHOW TABLES" ) )
        {
            ReportError( "SHOW TABLES Failed" );
            return FALSE;
        }

        hResultSet = mysql_store_result( hConn );
        if( hResultSet == NULL )
        {
            ReportError( "mysql_store_result() failed on SHOW TABLES result.");
            return FALSE;
        }
    
        while( (papszRow = mysql_fetch_row( hResultSet )) != NULL )
        {
            if( papszRow[0] == NULL )
                continue;

            if( EQUAL(papszRow[0],"spatial_ref_sys")
                || EQUAL(papszRow[0],"geometry_columns") )
                continue;

            papszTableNames = CSLAddString(papszTableNames, papszRow[0] );
        }

        mysql_free_result( hResultSet );
    }

/* -------------------------------------------------------------------- */
/*      Get the schema of the available tables.                         */
/* -------------------------------------------------------------------- */
    int iRecord;

    for( iRecord = 0; 
         papszTableNames != NULL && papszTableNames[iRecord] != NULL;
         iRecord++ )
    {
        //  FIXME: This should be fixed to deal with tables 
        //  for which we can't open because the name is bad/ 
        OpenTable( papszTableNames[iRecord], bUpdate, FALSE );
    }

    CSLDestroy( papszTableNames );
    
    return nLayers > 0 || bUpdate;
}
int OGRSelafinDataSource::Open(const char * pszFilename, int bUpdateIn, int bCreate) {
    // Check if a range is set and extract it and the filename
    const char *pszc=pszFilename;
    if (*pszFilename==0) return FALSE;
    while (*pszc) ++pszc;
    if (*(pszc-1)==']') {
        --pszc;
        while (pszc!=pszFilename && *pszc!='[') pszc--;
        if (pszc==pszFilename) return FALSE;
        poRange.setRange(pszc);
    }
    pszName = CPLStrdup( pszFilename );
    pszName[pszc-pszFilename]=0;
    bUpdate = bUpdateIn;
    if (bCreate && EQUAL(pszName, "/vsistdout/")) return TRUE;
    /* For writable /vsizip/, do nothing more */
    if (bCreate && STARTS_WITH(pszName, "/vsizip/")) return TRUE;
    CPLString osFilename(pszName);
    CPLString osBaseFilename = CPLGetFilename(pszName);
    // Determine what sort of object this is.
    VSIStatBufL sStatBuf;
    if (VSIStatExL( osFilename, &sStatBuf, VSI_STAT_NATURE_FLAG ) != 0) return FALSE;

    // Is this a single Selafin file?
    if (VSI_ISREG(sStatBuf.st_mode)) return OpenTable( pszName );

    // Is this a single a ZIP file with only a Selafin file inside ?
    if( STARTS_WITH(osFilename, "/vsizip/") && VSI_ISREG(sStatBuf.st_mode) ) {
        char** papszFiles = VSIReadDir(osFilename);
        if (CSLCount(papszFiles) != 1) {
            CSLDestroy(papszFiles);
            return FALSE;
        }
        osFilename = CPLFormFilename(osFilename, papszFiles[0], NULL);
        CSLDestroy(papszFiles);
        return OpenTable( osFilename );
    }

#ifdef notdef
    // Otherwise it has to be a directory.
    if( !VSI_ISDIR(sStatBuf.st_mode) ) return FALSE;

    // Scan through for entries which look like Selafin files
    int nNotSelafinCount = 0, i;
    char **papszNames = VSIReadDir( osFilename );
    for( i = 0; papszNames != NULL && papszNames[i] != NULL; i++ ) {
        CPLString oSubFilename = CPLFormFilename( osFilename, papszNames[i], NULL );
        if( EQUAL(papszNames[i],".") || EQUAL(papszNames[i],"..") ) continue;
        if( VSIStatL( oSubFilename, &sStatBuf ) != 0 || !VSI_ISREG(sStatBuf.st_mode) ) {
            nNotSelafinCount++;
            continue;
        }
        if( !OpenTable( oSubFilename ) ) {
            CPLDebug("Selafin", "Cannot open %s", oSubFilename.c_str());
            nNotSelafinCount++;
            continue;
        }
    }
    CSLDestroy( papszNames );

    // We presume that this is indeed intended to be a Selafin datasource if over half the files were Selafin files.
    return nNotSelafinCount < nLayers;
#else
    return FALSE;
#endif
}
Beispiel #9
0
int OGROCIDataSource::Open( const char * pszNewName,
                            char** papszOpenOptionsIn,
                            int bUpdate,
                            int bTestOpen )

{
    CPLAssert( nLayers == 0 && poSession == NULL );

/* -------------------------------------------------------------------- */
/*      Verify Oracle prefix.                                           */
/* -------------------------------------------------------------------- */
    if( !STARTS_WITH_CI(pszNewName,"OCI:") )
    {
        if( !bTestOpen )
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                      "%s does not conform to Oracle OCI driver naming convention,"
                      " OCI:*\n", pszNewName );
        }
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Try to parse out name, password and database name.              */
/* -------------------------------------------------------------------- */
    char *pszUserid;
    const char *pszPassword = "";
    const char *pszDatabase = "";
    char **papszTableList = NULL;
    const char *pszWorkspace = "";

    int   i;

    if( pszNewName[4] == '\0' )
    {
        pszUserid = CPLStrdup(CSLFetchNameValueDef(papszOpenOptionsIn, "USER", ""));
        pszPassword = CSLFetchNameValueDef(papszOpenOptionsIn, "PASSWORD", "");
        pszDatabase = CSLFetchNameValueDef(papszOpenOptionsIn, "DBNAME", "");
        const char* pszTables = CSLFetchNameValue(papszOpenOptionsIn, "TABLES");
        if( pszTables )
            papszTableList = CSLTokenizeStringComplex(pszTables, ",", TRUE, FALSE );
        pszWorkspace = CSLFetchNameValueDef(papszOpenOptions, "WORKSPACE", "");
    }
    else
    {
        pszUserid = CPLStrdup( pszNewName + 4 );

        // Is there a table list?
        for( i = static_cast<int>(strlen(pszUserid))-1; i > 1; i-- )
        {
            if( pszUserid[i] == ':' )
            {
                papszTableList = CSLTokenizeStringComplex( pszUserid+i+1, ",",
                                                        TRUE, FALSE );
                pszUserid[i] = '\0';
                break;
            }

            if( pszUserid[i] == '/' || pszUserid[i] == '@' )
                break;
        }

        for( i = 0;
            pszUserid[i] != '\0' && pszUserid[i] != '/' && pszUserid[i] != '@';
            i++ ) {}

        if( pszUserid[i] == '/' )
        {
            pszUserid[i++] = '\0';
            pszPassword = pszUserid + i;
            for( ; pszUserid[i] != '\0' && pszUserid[i] != '@'; i++ ) {}
        }

        if( pszUserid[i] == '@' )
        {
            pszUserid[i++] = '\0';
            pszDatabase = pszUserid + i;
        }
    }

/* -------------------------------------------------------------------- */
/*      Try to establish connection.                                    */
/* -------------------------------------------------------------------- */
    CPLDebug( "OCI", "Userid=%s, Password=%s, Database=%s",
              pszUserid, pszPassword, pszDatabase );

    if( EQUAL(pszDatabase, "") &&
        EQUAL(pszPassword, "") &&
        EQUAL(pszUserid, "") )
    {
        /* Use username/password OS Authentication and ORACLE_SID database */

        poSession = OGRGetOCISession( "/", "", "" );
    }
    else
    {
        poSession = OGRGetOCISession( pszUserid, pszPassword, pszDatabase );
    }

    if( poSession == NULL )
    {
        CPLFree(pszUserid);
        CSLDestroy(papszTableList);
        return FALSE;
    }

    if( ! EQUAL(pszWorkspace, "") )
    {
        OGROCIStringBuf oValidateCmd;
        OGROCIStatement oValidateStmt( GetSession() );

        oValidateCmd.Append( "call DBMS_WM.GotoWorkspace('" );
        oValidateCmd.Append( pszWorkspace );
        oValidateCmd.Append( "')" );

        oValidateStmt.Execute( oValidateCmd.GetString() );
    }

    pszName = CPLStrdup( pszNewName );

    bDSUpdate = bUpdate;

/* -------------------------------------------------------------------- */
/*      If no list of target tables was provided, collect a list of     */
/*      spatial tables now.                                             */
/* -------------------------------------------------------------------- */
    if( papszTableList == NULL )
    {
        OGROCIStatement oGetTables( poSession );

        if( oGetTables.Execute(
            "SELECT TABLE_NAME, OWNER FROM ALL_SDO_GEOM_METADATA" )
            == CE_None )
        {
            char **papszRow;

            while( (papszRow = oGetTables.SimpleFetchRow()) != NULL )
            {
                char szFullTableName[100];

                if( EQUAL(papszRow[1],pszUserid) )
                    strcpy( szFullTableName, papszRow[0] );
                else
                    snprintf( szFullTableName, sizeof(szFullTableName), "%s.%s",
                             papszRow[1], papszRow[0] );

                if( CSLFindString( papszTableList, szFullTableName ) == -1 )
                    papszTableList = CSLAddString( papszTableList,
                                                   szFullTableName );
            }
        }
    }
    CPLFree( pszUserid );

/* -------------------------------------------------------------------- */
/*      Open all the selected tables or views.                          */
/* -------------------------------------------------------------------- */
    for( i = 0; papszTableList != NULL && papszTableList[i] != NULL; i++ )
    {
        OpenTable( papszTableList[i], -1, bUpdate, FALSE, papszOpenOptionsIn );
    }

    CSLDestroy( papszTableList );

    return TRUE;
}
bool        _HYConsoleWindow::_ProcessMenuSelection (long msel)
{
    switch (msel) {
    case HY_WINDOW_MENU_ID_FILE+1:
        SaveConsole ();
        return true;

    case 14:
        _DoPrint ();
        return true;

    case 16:
        ((_HYTextBox*)GetObject(0))->_DoUndo(true);
        return true;

    case 17:
        ((_HYTextBox*)GetObject(0))->_DoCut(true);
        return true;

    case 18:
        ((_HYTextBox*)GetObject(0))->_DoCopy(true);
        return true;

    case HY_WINDOW_MENU_ID_EDIT+5:
        ((_HYTextBox*)GetObject(0))->_DoSelectAll(true);
        return true;

    case 21:
        SetStatusLine ("Canceling");
        terminateExecution = true;
        return true;

    case 22: {
        GtkWidget * suspendItem = gtk_item_factory_get_widget_by_action(menu_items,22);
        if (!isSuspended) {
            isSuspended = true;
            SetStatusLine (empty,empty,empty,-1,HY_SL_SUSPEND);
            gtk_label_set_text (GTK_LABEL (gtk_bin_get_child(GTK_BIN(suspendItem))), "Resume");
            updateTimer = false;
            while (isSuspended) {
                gtk_main_iteration_do(true);
            }
        } else {
            isSuspended = false;
            SetStatusLine (empty,empty,empty,-1,HY_SL_RESUME);
            gtk_label_set_text (GTK_LABEL (gtk_bin_get_child(GTK_BIN(suspendItem))), "Suspend execution");
            timerStart += clock()-lastTimer;
            updateTimer = true;
        }
        return true;
    }
    case 23:
        ShowMessagesLog();
        return true;

    case 24:
        RunStandardAnalyses();
        return true;

    case 25:
        displayAbout(false);
        return true;

    case HY_WINDOW_MENU_ID_EDIT+4:
        ((_HYTextBox*)GetObject(0))->_DoClear (true,true);
        return true;

    case 27:
        HandlePreferences (globalPreferencesList,"HYPHY Preferences");
        return true;

    case 29:
        //WinExec ("hh HYPHY HELP.chm",SW_SHOWNORMAL);
        return true;

    case 30:
        if (OpenBatchFile (false)) {
            ExecuteBatchFile();
            PopFilePath();
        }
        return true;

    case 31:
        ((_HYTextBox*)GetObject(0))->_DoRedo(true);
        return true;

    case 15:
        postWindowCloseEvent (GetID());
        gtk_main_quit ();
        return true;

    case 60: // expression calculator
        if (calculatorMode) {
            _HYTextBox         *ib = (_HYTextBox*)hyphyConsoleWindow->GetObject(1);
            ib->SetText ("exit");
            hyphyConsoleWindow->ProcessEvent (generateTextEditChangeEvent(ib->GetID(),2));
            calculatorMode         = false;
            //ib->SetText (empty);
        } else {
            calculatorMode = true;
            while(calculatorMode&&ExpressionCalculator()) {}
            calculatorMode = false;
        }
        return true;

    case 61: { // execute selection
        ExecuteSelection();
        return true;
    }

    case 70: // New Tree
        NewTreeWindow(-1);
        return true;

    case 71: // New Model
        NewModel(nil);
        return true;

    case 72: // New Chart
        NewChartWindow();
        return true;

    case 73: // New Genetic Code
        NewGeneticCodeTable(0);
        return true;

    case 74: // New Database
        NewDatabaseFile(0);
        return true;

    case 80: // Open Batch File
        if (OpenBatchFile()) {
            ExecuteBatchFile ();
        }
        return true;

    case 81: // Open Data File
        OpenDataFile();
        return true;

    case 82: // Open Tree
        OpenTreeFile();
        return true;

    case 83: // Open Text
        OpenTextFile();
        return true;

    case 84: // Open Table
        OpenTable ();
        return true;

    case 85: // Open SQLite database
        OpenDatabaseFile (nil);
        return true;

    case HY_WINDOW_MENU_ID_FILE-2:
        ShowObjectInspector ();
        return true;

    default: {
        msel -= 1000;
        if (msel<availablePostProcessors.lLength) {
            ExecuteAPostProcessor (*(_String*)(*(_List*)availablePostProcessors(msel))(1));
            return 0;
        }

        msel-=1000;
        if (msel<(long)recentPaths.lLength) {
            if (msel == -1) {
                for (long mi=0; mi<recentFiles.lLength; mi++) {
                    GtkWidget * recFile = gtk_item_factory_get_widget_by_action(hyphyConsoleWindow->menu_items,2000+mi);
                    if (recFile) {
                        gtk_item_factory_delete_item(hyphyConsoleWindow->menu_items,gtk_item_factory_path_from_widget(recFile));
                    }
                }
                recentPaths.Clear();
                recentFiles.Clear();
            } else {
                if (argFileName) {
                    *argFileName = *(_String*)recentPaths(msel);
                } else {
                    argFileName = new _String (*(_String*)recentPaths(msel));
                }
                if (OpenBatchFile(false)) {
                    ExecuteBatchFile ();
                }
            }
            return true;
        }
        return true;
    }
    }

    return _HYTWindow::_ProcessMenuSelection(msel);
}
void BeAccessibleWindow::MessageReceived(BMessage* msg)
{
	switch(msg->what)
	{
		case COMPACT_DATABASE_MSG:
		{
			GlobalSQLMgr->Compact();
			break;
		}
		
		
		case OPEN_DATABASE_MSG:
		{
			BString path;
			if (msg->FindString("path", &path) == B_OK)
			{
				OpenDatabase(BPath(path.String()));
			}
			break;
		}
	
		case MENU_FILE_NEW_MSG:
		{
			fNewFile->Show();
			break;
		}
			
		case MENU_FILE_OPEN_MSG:
		{
  			fOpenFile->Show();
		  	break;
		}
		
		case MENU_FILE_CLOSE_MSG:
		{
			CloseDatabase();
			break;
		}
		
		case OPEN_BUTTON:
		{
			BString name;
			msg->FindString("TabName", &name);
			
			if (name == "Table" || name == "TableList")
				OpenTable(DATA_VIEW);
			//else if (name == "Query")
		
			break;
		}
		
		case DESIGN_BUTTON:
		{
			BString name;
			msg->FindString("TabName", &name);
			
			if (name == "Table")
				OpenTable(DESIGN_VIEW);	
			//else if (name == "Query")
			break;
		}
		
		case NEW_BUTTON:
		{
			BString name;
			msg->FindString("TabName", &name);
			
			if (name == "Table")
				NewTable(DESIGN_VIEW);
			//else if (name == "Query")
		}
		
		case ENABLE_OPEN_BUTTON:
		{
			BString listName;
			msg->FindString("ListName", &listName);
			
			if (listName == "TableList")
			{
				fTableTab->fOpenButton->SetEnabled(true);
				fTableTab->fDesignButton->SetEnabled(true);
			}
			//else if (listName == "QueryList")
			
			break;
		}
		
		case DISABLE_OPEN_BUTTON:
		{
			BString listName;
			msg->FindString("ListName", &listName);
			
			if (listName == "TableList")
			{
				fTableTab->fOpenButton->SetEnabled(false);
				fTableTab->fDesignButton->SetEnabled(false);
			}
			//else if (listName == "QueryList")
			break;
		}
		
		case B_QUIT_REQUESTED:
		{
			BMessenger(be_app).SendMessage(B_QUIT_REQUESTED);
			break;
		}
		
		case IMPORT_FILE_REQUESTED_MSG:
		{
			fImportFile->SetTarget(BMessenger(this));
			fImportFile->Show();
			break;
		}
		
		case IMPORT_FILE_MSG:
		{
			entry_ref ref;
			msg->FindRef("refs", &ref);
						
			const BEntry entry(&ref, true);
			BPath dbPath(&entry);
			
			BRect frame(200,200,600,700);
			ImportFileWindow* importWindow = new ImportFileWindow(frame, dbPath.Path());
			importWindow->Show();
			break;
		}
		
		default:
		{
			BWindow::MessageReceived(msg);
			break;
		}
	}
}
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;

    /* read metadata for the specified tables */
    if (papszTableNames != NULL && bUseGeometryColumns)
    {
        for( int iTable = 0; 
            papszTableNames != NULL && papszTableNames[iTable] != NULL; 
            iTable++ )
        {        
            CPLODBCStatement oStmt( &oSession );
            
            /* Use join to make sure the existence of the referred column/table */
            oStmt.Appendf( "SELECT 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 WHERE f_table_schema = '%s' AND f_table_name = '%s'", papszSchemaNames[iTable], papszTableNames[iTable]);

            if( oStmt.ExecuteSQL() )
            {
                while( oStmt.Fetch() )
                {
                    if (papszGeomColumnNames == NULL)
                            papszGeomColumnNames = CSLAddString( papszGeomColumnNames, oStmt.GetColData(0) );
                    else if (*papszGeomColumnNames[iTable] == 0)
                    {
                        CPLFree(papszGeomColumnNames[iTable]);
                        papszGeomColumnNames[iTable] = CPLStrdup( oStmt.GetColData(0) );
                    }

                    papszCoordDimensions = 
                            CSLAddString( papszCoordDimensions, oStmt.GetColData(1, "2") );
                    papszSRIds = 
                            CSLAddString( papszSRIds, oStmt.GetColData(2, "0") );
                    papszSRTexts = 
                        CSLAddString( papszSRTexts, oStmt.GetColData(3, "") );
                    papszTypes = 
                            CSLAddString( papszTypes, oStmt.GetColData(4, "GEOMETRY") );
                }
            }
            else
            {
                /* probably the table is missing at all */
                InitializeMetadataTables();
            }
        }
    }

    /* if requesting all user database table then this takes priority */ 
 	if (papszTableNames == NULL && bListAllTables) 
 	{ 
 	    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') union all select sys.schemas.name, sys.schemas.name + '.' + sys.objects.name, '' from sys.objects join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where not exists (select * from sys.columns sc1 join sys.types on sc1.system_type_id = sys.types.system_type_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and sys.objects.object_id = sc1.object_id) 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) ); 
 	        } 
 	    } 
 	} 

    /* Determine the available tables if not specified. */
    if (papszTableNames == NULL && bUseGeometryColumns)
    {
        CPLODBCStatement oStmt( &oSession );
        
        /* Use join to make sure the existence of the referred column/table */
        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, "dbo") );
                papszTableNames = 
                        CSLAddString( papszTableNames, oStmt.GetColData(1) );
                papszGeomColumnNames = 
                        CSLAddString( papszGeomColumnNames, oStmt.GetColData(2) );
                papszCoordDimensions = 
                        CSLAddString( papszCoordDimensions, oStmt.GetColData(3, "2") );
                papszSRIds = 
                        CSLAddString( papszSRIds, oStmt.GetColData(4, "0") );
                papszSRTexts = 
                    CSLAddString( papszSRTexts, oStmt.GetColData(5, "") );
                papszTypes = 
                        CSLAddString( papszTypes, oStmt.GetColData(6, "GEOMETRY") );
            }
        }
        else
        {
            /* probably the table is missing at all */
            InitializeMetadataTables();
        }
    }

    /* 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, wkbNone, bUpdate );
    }

    CSLDestroy( papszTableNames );
    CSLDestroy( papszSchemaNames );
    CSLDestroy( papszGeomColumnNames );
    CSLDestroy( papszCoordDimensions );
    CSLDestroy( papszSRIds );
    CSLDestroy( papszSRTexts );
    CSLDestroy( papszTypes );

    CPLFree(pszGeometryFormat);
    CPLFree(pszConnectionName);
    
    bDSUpdate = bUpdate;

    return TRUE;
}
Beispiel #13
0
int OGRODBCDataSource::Open( const char * pszNewName, int bUpdate,
                             CPL_UNUSED int bTestOpen )
{
    CPLAssert( nLayers == 0 );

    if( !STARTS_WITH_CI(pszNewName, "ODBC:") && EQUAL(CPLGetExtension(pszNewName), "MDB") )
        return OpenMDB(pszNewName, bUpdate);

/* -------------------------------------------------------------------- */
/*      Start parsing dataset name from the end of string, fetching     */
/*      the name of spatial reference table and names for SRID and      */
/*      SRTEXT columns first.                                           */
/* -------------------------------------------------------------------- */
    char *pszWrkName = CPLStrdup( pszNewName + 5 ); // Skip the 'ODBC:' part
    char **papszTables = nullptr;
    char **papszGeomCol = nullptr;
    char *pszSRSTableName = nullptr;
    char *pszSRIDCol = nullptr;
    char *pszSRTextCol = nullptr;
    char *pszDelimiter = nullptr;

    if ( (pszDelimiter = strrchr( pszWrkName, ':' )) != nullptr )
    {
        char *pszOBracket = strchr( pszDelimiter + 1, '(' );

        if( strchr(pszDelimiter,'\\') != nullptr
            || strchr(pszDelimiter,'/') != nullptr )
        {
            /*
            ** if there are special tokens then this isn't really
            ** the srs table name, so avoid further processing.
            */
        }
        else if( pszOBracket == nullptr )
        {
            pszSRSTableName = CPLStrdup( pszDelimiter + 1 );
            *pszDelimiter = '\0';
        }
        else
        {
            char *pszCBracket = strchr( pszOBracket, ')' );
            if( pszCBracket != nullptr )
                *pszCBracket = '\0';

            char *pszComma = strchr( pszOBracket, ',' );
            if( pszComma != nullptr )
            {
                *pszComma = '\0';
                pszSRIDCol = CPLStrdup( pszComma + 1 );
            }

            *pszOBracket = '\0';
            pszSRSTableName = CPLStrdup( pszDelimiter + 1 );
            pszSRTextCol = CPLStrdup( pszOBracket + 1 );

            *pszDelimiter = '\0';
        }
    }

/* -------------------------------------------------------------------- */
/*      Strip off any comma delimited set of tables names to access     */
/*      from the end of the string first.  Also allow an optional       */
/*      bracketed geometry column name after the table name.            */
/* -------------------------------------------------------------------- */
    while( (pszDelimiter = strrchr( pszWrkName, ',' )) != nullptr )
    {
        char *pszOBracket = strstr( pszDelimiter + 1, "(" );
        if( pszOBracket == nullptr )
        {
            papszTables = CSLAddString( papszTables, pszDelimiter + 1 );
            papszGeomCol = CSLAddString( papszGeomCol, "" );
        }
        else
        {
            char *pszCBracket = strstr(pszOBracket,")");

            if( pszCBracket != nullptr )
                *pszCBracket = '\0';

            *pszOBracket = '\0';
            papszTables = CSLAddString( papszTables, pszDelimiter + 1 );
            papszGeomCol = CSLAddString( papszGeomCol, pszOBracket+1 );
        }
        *pszDelimiter = '\0';
    }

/* -------------------------------------------------------------------- */
/*      Split out userid, password and DSN.  The general form is        */
/*      user/password@dsn.  But if there are no @ characters the        */
/*      whole thing is assumed to be a DSN.                             */
/* -------------------------------------------------------------------- */
    char *pszUserid = nullptr;
    char *pszPassword = nullptr;
    char *pszDSN = nullptr;

    if( strstr(pszWrkName,"@") == nullptr )
    {
        pszDSN = CPLStrdup( pszWrkName );
    }
    else
    {

        pszDSN = CPLStrdup(strstr(pszWrkName, "@") + 1);
        if( *pszWrkName == '/' )
        {
            pszPassword = CPLStrdup(pszWrkName + 1);
            char *pszTarget = strstr(pszPassword,"@");
            *pszTarget = '\0';
        }
        else
        {
            pszUserid = CPLStrdup(pszWrkName);
            char *pszTarget = strstr(pszUserid,"@");
            *pszTarget = '\0';

            pszTarget = strstr(pszUserid,"/");
            if( pszTarget != nullptr )
            {
                *pszTarget = '\0';
                pszPassword = CPLStrdup(pszTarget+1);
            }
        }
    }

    CPLFree( pszWrkName );

/* -------------------------------------------------------------------- */
/*      Initialize based on the DSN.                                    */
/* -------------------------------------------------------------------- */
    CPLDebug( "OGR_ODBC",
              "EstablishSession(DSN:\"%s\", userid:\"%s\", password:\"%s\")",
              pszDSN, pszUserid ? pszUserid : "",
              pszPassword ? pszPassword : "" );

    if( !oSession.EstablishSession( pszDSN, pszUserid, pszPassword ) )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "Unable to initialize ODBC connection to DSN for %s,\n"
                  "%s",
                  pszNewName+5, oSession.GetLastError() );
        CSLDestroy( papszTables );
        CSLDestroy( papszGeomCol );
        CPLFree( pszDSN );
        CPLFree( pszUserid );
        CPLFree( pszPassword );
        CPLFree( pszSRIDCol );
        CPLFree( pszSRTextCol );
        CPLFree( pszSRSTableName );
        return FALSE;
    }

    CPLFree( pszDSN );
    CPLFree( pszUserid );
    CPLFree( pszPassword );

    pszName = CPLStrdup( pszNewName );

    bDSUpdate = bUpdate;

/* -------------------------------------------------------------------- */
/*      If no explicit list of tables was given, check for a list in    */
/*      a geometry_columns table.                                       */
/* -------------------------------------------------------------------- */
    if( papszTables == nullptr )
    {
        CPLODBCStatement oStmt( &oSession );

        oStmt.Append( "SELECT f_table_name, f_geometry_column, geometry_type"
                      " FROM geometry_columns" );
        if( oStmt.ExecuteSQL() )
        {
            while( oStmt.Fetch() )
            {
                papszTables =
                    CSLAddString( papszTables, oStmt.GetColData(0) );
                papszGeomCol =
                    CSLAddString( papszGeomCol, oStmt.GetColData(1) );
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      Otherwise our final resort is to return all tables as           */
/*      non-spatial tables.                                             */
/* -------------------------------------------------------------------- */
    if( papszTables == nullptr )
    {
        CPLODBCStatement oTableList( &oSession );

        if( oTableList.GetTables() )
        {
            while( oTableList.Fetch() )
            {
                const char *pszSchema = oTableList.GetColData(1);
                CPLString osLayerName;

                if( pszSchema != nullptr && strlen(pszSchema) > 0 )
                {
                    osLayerName = pszSchema;
                    osLayerName += ".";
                }

                osLayerName += oTableList.GetColData(2);

                papszTables = CSLAddString( papszTables, osLayerName );

                papszGeomCol = CSLAddString(papszGeomCol,"");
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      If we have an explicit list of requested tables, use them       */
/*      (non-spatial).                                                  */
/* -------------------------------------------------------------------- */
    for( int iTable = 0;
         papszTables != nullptr && papszTables[iTable] != nullptr;
         iTable++ )
    {
        if( strlen(papszGeomCol[iTable]) > 0 )
            OpenTable( papszTables[iTable], papszGeomCol[iTable], bUpdate );
        else
            OpenTable( papszTables[iTable], nullptr, bUpdate );
    }

    CSLDestroy( papszTables );
    CSLDestroy( papszGeomCol );

/* -------------------------------------------------------------------- */
/*      If no explicit list of tables was given, check for a list in    */
/*      a geometry_columns table.                                       */
/* -------------------------------------------------------------------- */
    if ( pszSRSTableName )
    {
        CPLODBCStatement oSRSList( &oSession );

        if ( !pszSRTextCol )
            pszSRTextCol = CPLStrdup( "srtext" );
        if ( !pszSRIDCol )
            pszSRIDCol = CPLStrdup( "srid" );

        oSRSList.Append( "SELECT " );
        oSRSList.Append( pszSRIDCol );
        oSRSList.Append( "," );
        oSRSList.Append( pszSRTextCol );
        oSRSList.Append( " FROM " );
        oSRSList.Append( pszSRSTableName );

        CPLDebug( "OGR_ODBC", "ExecuteSQL(%s) to read SRS table",
                  oSRSList.GetCommand() );
        if ( oSRSList.ExecuteSQL() )
        {
            int nRows = 256;     // A reasonable number of SRIDs to start from
            panSRID = (int *)CPLMalloc( nRows * sizeof(int) );
            papoSRS = (OGRSpatialReference **)
                CPLMalloc( nRows * sizeof(OGRSpatialReference*) );

            while ( oSRSList.Fetch() )
            {
                const char *pszSRID = oSRSList.GetColData( pszSRIDCol );
                if ( !pszSRID )
                    continue;

                const char *pszSRText = oSRSList.GetColData( pszSRTextCol );

                if ( pszSRText )
                {
                    if ( nKnownSRID > nRows )
                    {
                        nRows *= 2;
                        panSRID = (int *)CPLRealloc( panSRID,
                                                     nRows * sizeof(int) );
                        papoSRS = (OGRSpatialReference **)
                            CPLRealloc( papoSRS,
                            nRows * sizeof(OGRSpatialReference*) );
                    }
                    panSRID[nKnownSRID] = atoi( pszSRID );
                    papoSRS[nKnownSRID] = new OGRSpatialReference();
                    papoSRS[nKnownSRID]->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
                    if ( papoSRS[nKnownSRID]->importFromWkt( pszSRText )
                         != OGRERR_NONE )
                    {
                        delete papoSRS[nKnownSRID];
                        continue;
                    }
                    nKnownSRID++;
                }
            }
        }
    }

    if ( pszSRIDCol )
        CPLFree( pszSRIDCol );
    if ( pszSRTextCol )
        CPLFree( pszSRTextCol );
    if ( pszSRSTableName )
        CPLFree( pszSRSTableName );

    return TRUE;
}
Beispiel #14
0
int OGRODBCDataSource::OpenMDB( const char * pszNewName, int bUpdate )
{
    const char* pszOptionName = "PGEO_DRIVER_TEMPLATE";
    const char* pszDSNStringTemplate = CPLGetConfigOption( pszOptionName, nullptr );
    if( pszDSNStringTemplate == nullptr )
    {
        pszOptionName = "MDB_DRIVER_TEMPLATE";
        pszDSNStringTemplate = CPLGetConfigOption( pszOptionName, nullptr );
        if( pszDSNStringTemplate == nullptr )
        {
            pszOptionName = "";
            pszDSNStringTemplate = "DRIVER=Microsoft Access Driver (*.mdb);DBQ=%s";
        }
    }
    if (!CheckDSNStringTemplate(pszDSNStringTemplate))
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                    "Illegal value for %s option", pszOptionName );
        return FALSE;
    }
    char* pszDSN = (char *) CPLMalloc(strlen(pszNewName)+strlen(pszDSNStringTemplate)+100);
    /* coverity[tainted_string] */
    snprintf( pszDSN,
              strlen(pszNewName)+strlen(pszDSNStringTemplate)+100,
              pszDSNStringTemplate,  pszNewName );

/* -------------------------------------------------------------------- */
/*      Initialize based on the DSN.                                    */
/* -------------------------------------------------------------------- */
    CPLDebug( "ODBC", "EstablishSession(%s)", pszDSN );

    if( !oSession.EstablishSession( pszDSN, nullptr, nullptr ) )
    {
        int bError = TRUE;
        if( EQUAL(pszDSN, "") )
        {
            // Trying with another template (#5594)
            pszDSNStringTemplate = "DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ=%s";
            CPLFree( pszDSN );
            pszDSN = (char *) CPLMalloc(strlen(pszNewName)+strlen(pszDSNStringTemplate)+100);
            snprintf( pszDSN,
                      strlen(pszNewName)+strlen(pszDSNStringTemplate)+100,
                      pszDSNStringTemplate,  pszNewName );
            CPLDebug( "ODBC", "EstablishSession(%s)", pszDSN );
            if( oSession.EstablishSession( pszDSN, nullptr, nullptr ) )
            {
                bError = FALSE;
            }
        }
        if( bError )
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                    "Unable to initialize ODBC connection to DSN for %s,\n"
                    "%s", pszDSN, oSession.GetLastError() );
            CPLFree( pszDSN );
            return FALSE;
        }
    }

    CPLFree( pszDSN );

    pszName = CPLStrdup( pszNewName );

    bDSUpdate = bUpdate;

/* -------------------------------------------------------------------- */
/*      Check if it is a PGeo MDB.                                      */
/* -------------------------------------------------------------------- */
    {
        CPLODBCStatement oStmt( &oSession );

        oStmt.Append( "SELECT TableName, FieldName, ShapeType, ExtentLeft, ExtentRight, ExtentBottom, ExtentTop, SRID, HasZ FROM GDB_GeomColumns" );

        if( oStmt.ExecuteSQL() )
        {
            return FALSE;
        }
    }

/* -------------------------------------------------------------------- */
/*      Check if it is a Geomedia MDB.                                  */
/* -------------------------------------------------------------------- */
    {
        CPLODBCStatement oStmt( &oSession );

        oStmt.Append( "SELECT TableName FROM GAliasTable WHERE TableType = 'INGRFeatures'" );

        if( oStmt.ExecuteSQL() )
        {
            return FALSE;
        }
    }

/* -------------------------------------------------------------------- */
/*      Check if it is a Walk MDB.                                      */
/* -------------------------------------------------------------------- */
    {
        CPLODBCStatement oStmt( &oSession );

        oStmt.Append( "SELECT LayerID, LayerName, minE, maxE, minN, maxN, Memo FROM WalkLayers" );

        if( oStmt.ExecuteSQL() )
        {
            return FALSE;
        }
    }

/* -------------------------------------------------------------------- */
/*      Return all tables as  non-spatial tables.                       */
/* -------------------------------------------------------------------- */
    CPLODBCStatement oTableList( &oSession );

    if( oTableList.GetTables() )
    {
        while( oTableList.Fetch() )
        {
            const char *pszSchema = oTableList.GetColData(1);
            const char* pszTableName = oTableList.GetColData(2);
            if( pszTableName != nullptr )
            {
                CPLString osLayerName;

                if( pszSchema != nullptr && strlen(pszSchema) > 0 )
                {
                    osLayerName = pszSchema;
                    osLayerName += ".";
                }

                osLayerName += pszTableName;

                OpenTable( osLayerName, nullptr, bUpdate );
            }
        }

        return TRUE;
    }
    else
        return FALSE;
}
int OGRMySQLDataSource::Open( const char * pszNewName, char** papszOpenOptionsIn,
                              int bUpdate )

{
    CPLAssert( nLayers == 0 );

    /* -------------------------------------------------------------------- */
    /*      Use options process to get .my.cnf file contents.               */
    /* -------------------------------------------------------------------- */
    int nPort = 0;
    char **papszTableNames=NULL;
    std::string oHost, oPassword, oUser, oDB;

    CPLString osNewName(pszNewName);
    const char* apszOpenOptions[] = { "dbname", "port", "user", "password",
                                      "host", "tables"
                                    };
    for(int i=0; i <(int)(sizeof(apszOpenOptions)/sizeof(char*)); i++)
    {
        const char* pszVal = CSLFetchNameValue(papszOpenOptionsIn, apszOpenOptions[i]);
        if( pszVal )
        {
            if( osNewName[osNewName.size()-1] != ':' )
                osNewName += ",";
            if( i > 0 )
            {
                osNewName += apszOpenOptions[i];
                osNewName += "=";
            }
            if( EQUAL(apszOpenOptions[i], "tables") )
            {
                for( ; *pszVal; ++pszVal )
                {
                    if( *pszVal == ',' )
                        osNewName += ";";
                    else
                        osNewName += *pszVal;
                }
            }
            else
                osNewName += pszVal;
        }
    }

    /* -------------------------------------------------------------------- */
    /*      Parse out connection information.                               */
    /* -------------------------------------------------------------------- */
    char **papszItems = CSLTokenizeString2( osNewName+6, ",",
                                            CSLT_HONOURSTRINGS );

    if( CSLCount(papszItems) < 1 )
    {
        CSLDestroy( papszItems );
        CPLError( CE_Failure, CPLE_AppDefined,
                  "MYSQL: request missing databasename." );
        return FALSE;
    }

    oDB = papszItems[0];

    for( int i = 1; papszItems[i] != NULL; i++ )
    {
        if( STARTS_WITH_CI(papszItems[i], "user="******"password="******"host=") )
            oHost = papszItems[i] + 5;
        else if( STARTS_WITH_CI(papszItems[i], "port=") )
            nPort = atoi(papszItems[i] + 5);
        else if( STARTS_WITH_CI(papszItems[i], "tables=") )
        {
            CSLDestroy(papszTableNames);
            papszTableNames = CSLTokenizeStringComplex(
                                  papszItems[i] + 7, ";", FALSE, FALSE );
        }
        else
            CPLError( CE_Warning, CPLE_AppDefined,
                      "'%s' in MYSQL datasource definition not recognised and ignored.", papszItems[i] );
    }

    CSLDestroy( papszItems );

    /* -------------------------------------------------------------------- */
    /*      Try to establish connection.                                    */
    /* -------------------------------------------------------------------- */
    hConn = mysql_init( NULL );

    if( hConn == NULL )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "mysql_init() failed." );
    }

    /* -------------------------------------------------------------------- */
    /*      Set desired options on the connection: charset and timeout.     */
    /* -------------------------------------------------------------------- */
    if( hConn )
    {
        const char *pszTimeoutLength =
            CPLGetConfigOption( "MYSQL_TIMEOUT", "0" );

        unsigned int timeout = atoi(pszTimeoutLength);
        mysql_options(hConn, MYSQL_OPT_CONNECT_TIMEOUT, (char*)&timeout);

        mysql_options(hConn, MYSQL_SET_CHARSET_NAME, "utf8" );
    }

    /* -------------------------------------------------------------------- */
    /*      Perform connection.                                             */
    /* -------------------------------------------------------------------- */
    if( hConn
            && mysql_real_connect( hConn,
                                   oHost.length() ? oHost.c_str() : NULL,
                                   oUser.length() ? oUser.c_str() : NULL,
                                   oPassword.length() ? oPassword.c_str() : NULL,
                                   oDB.length() ? oDB.c_str() : NULL,
                                   nPort, NULL, CLIENT_INTERACTIVE ) == NULL )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "MySQL connect failed for: %s\n%s",
                  pszNewName + 6, mysql_error( hConn ) );
        mysql_close( hConn );
        hConn = NULL;
    }

    if( hConn == NULL )
    {
        CSLDestroy( papszTableNames );
        return FALSE;
    }
    else
    {
        // Enable automatic reconnection
        // Must be called after mysql_real_connect() on MySQL < 5.0.19
        // and at any point on more recent versions.
        my_bool reconnect = 1;
        mysql_options(hConn, MYSQL_OPT_RECONNECT, &reconnect);
    }

    pszName = CPLStrdup( pszNewName );

    bDSUpdate = bUpdate;

    /* -------------------------------------------------------------------- */
    /*      Get a list of available tables.                                 */
    /* -------------------------------------------------------------------- */
    if( papszTableNames == NULL )
    {
        MYSQL_RES *hResultSet;
        MYSQL_ROW papszRow;

        if( mysql_query( hConn, "SHOW TABLES" ) )
        {
            ReportError( "SHOW TABLES Failed" );
            return FALSE;
        }

        hResultSet = mysql_store_result( hConn );
        if( hResultSet == NULL )
        {
            ReportError( "mysql_store_result() failed on SHOW TABLES result.");
            return FALSE;
        }

        while( (papszRow = mysql_fetch_row( hResultSet )) != NULL )
        {
            if( papszRow[0] == NULL )
                continue;

            if( EQUAL(papszRow[0],"spatial_ref_sys")
                    || EQUAL(papszRow[0],"geometry_columns") )
                continue;

            papszTableNames = CSLAddString(papszTableNames, papszRow[0] );
        }

        mysql_free_result( hResultSet );
    }

    /* -------------------------------------------------------------------- */
    /*      Get the schema of the available tables.                         */
    /* -------------------------------------------------------------------- */
    int iRecord;

    for( iRecord = 0;
            papszTableNames != NULL && papszTableNames[iRecord] != NULL;
            iRecord++ )
    {
        //  FIXME: This should be fixed to deal with tables
        //  for which we can't open because the name is bad/
        OpenTable( papszTableNames[iRecord], bUpdate );
    }

    CSLDestroy( papszTableNames );

    return nLayers > 0 || bUpdate;
}
int OGRIngresDataSource::Open( const char *pszFullName, 
                               char **papszOptions, int bUpdate )


{
    CPLAssert( nLayers == 0 );

/* -------------------------------------------------------------------- */
/*      Verify we have a dbname, this parameter is required.            */
/* -------------------------------------------------------------------- */
    const char *pszDBName = CSLFetchNameValue(papszOptions,"dbname");

    if( pszDBName == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed,
                  "No DBNAME item provided in INGRES datasource name." );
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Do we have a table list?                                        */
/* -------------------------------------------------------------------- */
    char **papszTableNames = NULL;
    const char *pszTables = CSLFetchNameValue(papszOptions,"tables");

    if( pszTables != NULL )
        papszTableNames = CSLTokenizeStringComplex(pszTables,"/",TRUE,FALSE);
    
/* -------------------------------------------------------------------- */
/*      Initialize the Ingres API. Should we only do this once per      */
/*      program run?  Really we should also try to terminate the api    */
/*      on program exit.                                                */
/* -------------------------------------------------------------------- */
    IIAPI_INITPARM  initParm;

    initParm.in_version = IIAPI_VERSION_1; 
    initParm.in_timeout = -1;
    IIapi_initialize( &initParm );

/* -------------------------------------------------------------------- */
/*      Try to connect to the database.                                 */
/* -------------------------------------------------------------------- */
    IIAPI_CONNPARM	connParm;
    IIAPI_WAITPARM	waitParm = { -1 };
    
    memset( &connParm, 0, sizeof(connParm) );
    connParm.co_genParm.gp_callback = NULL;
    connParm.co_genParm.gp_closure = NULL;
    connParm.co_target = (II_CHAR *) pszDBName;
    connParm.co_connHandle = NULL;
    connParm.co_tranHandle = NULL;
    connParm.co_username = 
        (II_CHAR*) CSLFetchNameValue(papszOptions,"username");
    connParm.co_password = 
        (II_CHAR*)CSLFetchNameValue(papszOptions,"password");
    connParm.co_timeout = -1;

    if( CSLFetchNameValue(papszOptions,"timeout") != NULL )
        connParm.co_timeout = atoi(CSLFetchNameValue(papszOptions,"timeout"));

    IIapi_connect( &connParm );
       
    while( connParm.co_genParm.gp_completed == FALSE )
	IIapi_wait( &waitParm );

    hConn = connParm.co_connHandle;

    if( connParm.co_genParm.gp_status != IIAPI_ST_SUCCESS 
        || hConn == NULL )
    {
        OGRIngresStatement::ReportError( &(connParm.co_genParm), 
                                    "Failed to connect to Ingres database." );
        return FALSE;
    }

    pszName = CPLStrdup( pszFullName );
    
    bDSUpdate = bUpdate;

    // Check for new or old Ingres spatial library
    {
    	OGRIngresStatement oStmt( hConn );

    	if( oStmt.ExecuteSQL("SELECT COUNT(*) FROM iicolumns WHERE table_name = 'iiattribute' AND column_name = 'attgeomtype'" ) )
    	{
    		char **papszFields;
    		while( (papszFields = oStmt.GetRow()) )
    		{
    			CPLString osCount = papszFields[0];
    			if( osCount[0] == '0' )
    			{
    				bNewIngres = FALSE;
    			}
    			else
    			{
    				bNewIngres = TRUE;
    			}
    		}
    	}
    }

/* -------------------------------------------------------------------- */
/*      Get a list of available tables.                                 */
/* -------------------------------------------------------------------- */
    if( papszTableNames == NULL )
    {
        OGRIngresStatement oStmt( hConn );
        
        if( oStmt.ExecuteSQL( "select table_name from iitables where system_use = 'U' and table_name not like 'iietab_%'" ) )
        {
            char **papszFields;
            while( (papszFields = oStmt.GetRow()) )
            {
                CPLString osTableName = papszFields[0];
                osTableName.Trim();
                papszTableNames = CSLAddString( papszTableNames, 
                                                osTableName );
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      Get the schema of the available tables.                         */
/* -------------------------------------------------------------------- */
    int iRecord;

    for( iRecord = 0; 
         papszTableNames != NULL && papszTableNames[iRecord] != NULL;
         iRecord++ )
    {
        OpenTable( papszTableNames[iRecord], bUpdate );
    }

    CSLDestroy( papszTableNames );

    return TRUE;
}
int OGRCSVDataSource::Open( const char * pszFilename, int bUpdateIn,
                            int bForceOpen, char** papszOpenOptions )

{
    pszName = CPLStrdup( pszFilename );
    bUpdate = bUpdateIn;

    if (bUpdateIn && bForceOpen && EQUAL(pszFilename, "/vsistdout/"))
        return TRUE;

    /* For writable /vsizip/, do nothing more */
    if (bUpdateIn && bForceOpen && strncmp(pszFilename, "/vsizip/", 8) == 0)
        return TRUE;

    CPLString osFilename(pszFilename);
    CPLString osBaseFilename = CPLGetFilename(pszFilename);
    CPLString osExt = GetRealExtension(osFilename);
    pszFilename = NULL;

    int bIgnoreExtension = EQUALN(osFilename, "CSV:", 4);
    int bUSGeonamesFile = FALSE;
    /* int bGeonamesOrgFile = FALSE; */
    if (bIgnoreExtension)
    {
        osFilename = osFilename + 4;
    }

    /* Those are *not* real .XLS files, but text file with tab as column separator */
    if (EQUAL(osBaseFilename, "NfdcFacilities.xls") ||
        EQUAL(osBaseFilename, "NfdcRunways.xls") ||
        EQUAL(osBaseFilename, "NfdcRemarks.xls") ||
        EQUAL(osBaseFilename, "NfdcSchedules.xls"))
    {
        if (bUpdateIn)
            return FALSE;
        bIgnoreExtension = TRUE;
    }
    else if ((EQUALN(osBaseFilename, "NationalFile_", 13) ||
              EQUALN(osBaseFilename, "POP_PLACES_", 11) ||
              EQUALN(osBaseFilename, "HIST_FEATURES_", 14) ||
              EQUALN(osBaseFilename, "US_CONCISE_", 11) ||
              EQUALN(osBaseFilename, "AllNames_", 9) ||
              EQUALN(osBaseFilename, "Feature_Description_History_", 28) ||
              EQUALN(osBaseFilename, "ANTARCTICA_", 11) ||
              EQUALN(osBaseFilename, "GOVT_UNITS_", 11) ||
              EQUALN(osBaseFilename, "NationalFedCodes_", 17) ||
              EQUALN(osBaseFilename, "AllStates_", 10) ||
              EQUALN(osBaseFilename, "AllStatesFedCodes_", 18) ||
              (strlen(osBaseFilename) > 2 && EQUALN(osBaseFilename+2, "_Features_", 10)) ||
              (strlen(osBaseFilename) > 2 && EQUALN(osBaseFilename+2, "_FedCodes_", 10))) &&
             (EQUAL(osExt, "txt") || EQUAL(osExt, "zip")) )
    {
        if (bUpdateIn)
            return FALSE;
        bIgnoreExtension = TRUE;
        bUSGeonamesFile = TRUE;

        if (EQUAL(osExt, "zip") &&
            strstr(osFilename, "/vsizip/") == NULL )
        {
            osFilename = "/vsizip/" + osFilename;
        }
    }
    else if (EQUAL(osBaseFilename, "allCountries.txt") ||
             EQUAL(osBaseFilename, "allCountries.zip"))
    {
        if (bUpdateIn)
            return FALSE;
        bIgnoreExtension = TRUE;
        /* bGeonamesOrgFile = TRUE; */

        if (EQUAL(osExt, "zip") &&
            strstr(osFilename, "/vsizip/") == NULL )
        {
            osFilename = "/vsizip/" + osFilename;
        }
    }

/* -------------------------------------------------------------------- */
/*      Determine what sort of object this is.                          */
/* -------------------------------------------------------------------- */
    VSIStatBufL sStatBuf;

    if( VSIStatExL( osFilename, &sStatBuf, VSI_STAT_NATURE_FLAG ) != 0 )
        return FALSE;

/* -------------------------------------------------------------------- */
/*      Is this a single CSV file?                                      */
/* -------------------------------------------------------------------- */
    if( VSI_ISREG(sStatBuf.st_mode)
        && (bIgnoreExtension || EQUAL(osExt,"csv") || EQUAL(osExt,"tsv")) )
    {
        if (EQUAL(CPLGetFilename(osFilename), "NfdcFacilities.xls"))
        {
            return OpenTable( osFilename, papszOpenOptions, "ARP");
        }
        else if (EQUAL(CPLGetFilename(osFilename), "NfdcRunways.xls"))
        {
            OpenTable( osFilename, papszOpenOptions, "BaseEndPhysical");
            OpenTable( osFilename, papszOpenOptions, "BaseEndDisplaced");
            OpenTable( osFilename, papszOpenOptions, "ReciprocalEndPhysical");
            OpenTable( osFilename, papszOpenOptions, "ReciprocalEndDisplaced");
            return nLayers != 0;
        }
        else if (bUSGeonamesFile)
        {
            /* GNIS specific */
            if (EQUALN(osBaseFilename, "NationalFedCodes_", 17) ||
                EQUALN(osBaseFilename, "AllStatesFedCodes_", 18) ||
                EQUALN(osBaseFilename, "ANTARCTICA_", 11) ||
                (strlen(osBaseFilename) > 2 && EQUALN(osBaseFilename+2, "_FedCodes_", 10)))
            {
                OpenTable( osFilename, papszOpenOptions, NULL, "PRIMARY");
            }
            else if (EQUALN(osBaseFilename, "GOVT_UNITS_", 11) ||
                     EQUALN(osBaseFilename, "Feature_Description_History_", 28))
            {
                OpenTable( osFilename, papszOpenOptions, NULL, "");
            }
            else
            {
                OpenTable( osFilename, papszOpenOptions, NULL, "PRIM");
                OpenTable( osFilename, papszOpenOptions, NULL, "SOURCE");
            }
            return nLayers != 0;
        }

        return OpenTable( osFilename, papszOpenOptions );
    }

/* -------------------------------------------------------------------- */
/*      Is this a single a ZIP file with only a CSV file inside ?       */
/* -------------------------------------------------------------------- */
    if( strncmp(osFilename, "/vsizip/", 8) == 0 &&
        EQUAL(osExt, "zip") &&
        VSI_ISREG(sStatBuf.st_mode) )
    {
        char** papszFiles = VSIReadDir(osFilename);
        if (CSLCount(papszFiles) != 1 ||
            !EQUAL(CPLGetExtension(papszFiles[0]), "CSV"))
        {
            CSLDestroy(papszFiles);
            return FALSE;
        }
        osFilename = CPLFormFilename(osFilename, papszFiles[0], NULL);
        CSLDestroy(papszFiles);
        return OpenTable( osFilename, papszOpenOptions );
    }

/* -------------------------------------------------------------------- */
/*      Otherwise it has to be a directory.                             */
/* -------------------------------------------------------------------- */
    if( !VSI_ISDIR(sStatBuf.st_mode) )
        return FALSE;

/* -------------------------------------------------------------------- */
/*      Scan through for entries ending in .csv.                        */
/* -------------------------------------------------------------------- */
    int nNotCSVCount = 0, i;
    char **papszNames = CPLReadDir( osFilename );

    for( i = 0; papszNames != NULL && papszNames[i] != NULL; i++ )
    {
        CPLString oSubFilename = 
            CPLFormFilename( osFilename, papszNames[i], NULL );

        if( EQUAL(papszNames[i],".") || EQUAL(papszNames[i],"..") )
            continue;

        if (EQUAL(CPLGetExtension(oSubFilename),"csvt"))
            continue;

        if( VSIStatL( oSubFilename, &sStatBuf ) != 0 
            || !VSI_ISREG(sStatBuf.st_mode) )
        {
            nNotCSVCount++;
            continue;
        }

        if (EQUAL(CPLGetExtension(oSubFilename),"csv"))
        {
            if( !OpenTable( oSubFilename, papszOpenOptions ) )
            {
                CPLDebug("CSV", "Cannot open %s", oSubFilename.c_str());
                nNotCSVCount++;
                continue;
            }
        }

        /* GNIS specific */
        else if ( strlen(papszNames[i]) > 2 &&
                  EQUALN(papszNames[i]+2, "_Features_", 10) &&
                  EQUAL(CPLGetExtension(papszNames[i]), "txt") )
        {
            int bRet = OpenTable( oSubFilename, papszOpenOptions, NULL, "PRIM");
            bRet |= OpenTable( oSubFilename, papszOpenOptions, NULL, "SOURCE");
            if ( !bRet )
            {
                CPLDebug("CSV", "Cannot open %s", oSubFilename.c_str());
                nNotCSVCount++;
                continue;
            }
        }
        /* GNIS specific */
        else if ( strlen(papszNames[i]) > 2 &&
                  EQUALN(papszNames[i]+2, "_FedCodes_", 10) &&
                  EQUAL(CPLGetExtension(papszNames[i]), "txt") )
        {
            if ( !OpenTable( oSubFilename, papszOpenOptions, NULL, "PRIMARY") )
            {
                CPLDebug("CSV", "Cannot open %s", oSubFilename.c_str());
                nNotCSVCount++;
                continue;
            }
        }
        else
        {
            nNotCSVCount++;
            continue;
        }
    }

    CSLDestroy( papszNames );

/* -------------------------------------------------------------------- */
/*      We presume that this is indeed intended to be a CSV             */
/*      datasource if over half the files were .csv files.              */
/* -------------------------------------------------------------------- */
    return bForceOpen || nNotCSVCount < nLayers;
}
Beispiel #18
0
int OGRODBCDataSource::OpenMDB( const char * pszNewName, int bUpdate )
{
    const char *pszDSNStringTemplate =
        "DRIVER=Microsoft Access Driver (*.mdb);DBQ=%s";
    char* pszDSN = (char *) CPLMalloc(strlen(pszNewName)+strlen(pszDSNStringTemplate)+100);
    sprintf( pszDSN, pszDSNStringTemplate,  pszNewName );

/* -------------------------------------------------------------------- */
/*      Initialize based on the DSN.                                    */
/* -------------------------------------------------------------------- */
    CPLDebug( "ODBC", "EstablishSession(%s)", pszDSN );

    if( !oSession.EstablishSession( pszDSN, NULL, NULL ) )
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "Unable to initialize ODBC connection to DSN for %s,\n"
                  "%s", pszDSN, oSession.GetLastError() );
        CPLFree( pszDSN );
        return FALSE;
    }

    CPLFree( pszDSN );

    pszName = CPLStrdup( pszNewName );

    bDSUpdate = bUpdate;

/* -------------------------------------------------------------------- */
/*      Check if it is a PGeo MDB.                                      */
/* -------------------------------------------------------------------- */
    {
        CPLODBCStatement oStmt( &oSession );

        oStmt.Append( "SELECT TableName, FieldName, ShapeType, ExtentLeft, ExtentRight, ExtentBottom, ExtentTop, SRID, HasZ FROM GDB_GeomColumns" );

        if( oStmt.ExecuteSQL() )
        {
            return FALSE;
        }
    }

/* -------------------------------------------------------------------- */
/*      Check if it is a Geomedia MDB.                                  */
/* -------------------------------------------------------------------- */
    {
        CPLODBCStatement oStmt( &oSession );

        oStmt.Append( "SELECT TableName FROM GAliasTable WHERE TableType = 'INGRFeatures'" );

        if( oStmt.ExecuteSQL() )
        {
            return FALSE;
        }
    }

/* -------------------------------------------------------------------- */
/*      Return all tables as  non-spatial tables.                       */
/* -------------------------------------------------------------------- */
    CPLODBCStatement oTableList( &oSession );

    if( oTableList.GetTables() )
    {
        while( oTableList.Fetch() )
        {
            const char *pszSchema = oTableList.GetColData(1);
            CPLString osLayerName;

            if( pszSchema != NULL && strlen(pszSchema) > 0 )
            {
                osLayerName = pszSchema;
                osLayerName += ".";
            }

            osLayerName += oTableList.GetColData(2);

            OpenTable( osLayerName, NULL, bUpdate );
        }

        return TRUE;
    }
    else
        return FALSE;
}
int OGRCSVDataSource::Open( const char * pszFilename, int bUpdateIn,
                            int bForceOpen )

{
    pszName = CPLStrdup( pszFilename );
    bUpdate = bUpdateIn;

/* -------------------------------------------------------------------- */
/*      Determine what sort of object this is.                          */
/* -------------------------------------------------------------------- */
    VSIStatBufL sStatBuf;

    if( VSIStatL( pszFilename, &sStatBuf ) != 0 )
        return FALSE;

/* -------------------------------------------------------------------- */
/*      Is this a single CSV file?                                      */
/* -------------------------------------------------------------------- */
    if( VSI_ISREG(sStatBuf.st_mode)
        && strlen(pszFilename) > 4
        && EQUAL(pszFilename+strlen(pszFilename)-4,".csv") )
        return OpenTable( pszFilename );

/* -------------------------------------------------------------------- */
/*      Otherwise it has to be a directory.                             */
/* -------------------------------------------------------------------- */
    if( !VSI_ISDIR(sStatBuf.st_mode) )
        return FALSE;

/* -------------------------------------------------------------------- */
/*      Scan through for entries ending in .csv.                        */
/* -------------------------------------------------------------------- */
    int nNotCSVCount = 0, i;
    char **papszNames = CPLReadDir( pszFilename );

    for( i = 0; papszNames != NULL && papszNames[i] != NULL; i++ )
    {
        CPLString oSubFilename = 
            CPLFormFilename( pszFilename, papszNames[i], NULL );

        if( EQUAL(papszNames[i],".") || EQUAL(papszNames[i],"..") )
            continue;

        if (EQUAL(CPLGetExtension(oSubFilename),"csvt"))
            continue;

        if( VSIStatL( oSubFilename, &sStatBuf ) != 0 
            || !VSI_ISREG(sStatBuf.st_mode) 
            || !EQUAL(CPLGetExtension(oSubFilename),"csv") )
        {
            nNotCSVCount++;
            continue;
        }

        if( !OpenTable( oSubFilename ) )
        {
            CSLDestroy( papszNames );
            nNotCSVCount++;
            return FALSE;
        }
    }

    CSLDestroy( papszNames );

/* -------------------------------------------------------------------- */
/*      We presume that this is indeed intended to be a CSV             */
/*      datasource if over half the files were .csv files.              */
/* -------------------------------------------------------------------- */
    return bForceOpen || nNotCSVCount < nLayers;
}
Beispiel #20
0
int OGRIngresDataSource::Open( const char *pszFullName, 
                               char **papszOptions, int bUpdate )


{
    CPLAssert( nLayers == 0 );
  
 #define MAX_TARGET_STRING_LENGTH 512
    char pszDBTarget[MAX_TARGET_STRING_LENGTH];

/* -------------------------------------------------------------------- */
/*      Verify we have a dbname, this parameter is required.            */
/* -------------------------------------------------------------------- */
    const char *pszDBName = CSLFetchNameValue(papszOptions,"dbname");

    if( pszDBName == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed,
                  "No DBNAME item provided in INGRES datasource name." );
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Do we have a table list?                                        */
/* -------------------------------------------------------------------- */
    char **papszTableNames = NULL;
    const char *pszTables = CSLFetchNameValue(papszOptions,"tables");

    if( pszTables != NULL )
        papszTableNames = CSLTokenizeStringComplex(pszTables,"/",TRUE,FALSE);
   
/* -------------------------------------------------------------------- */
/*      Add support to dynamic vnode if passed                          */
/* -------------------------------------------------------------------- */
    const char *pszHost = CSLFetchNameValue(papszOptions,"host");
    if (pszHost)
    {
        const char *pszInstance = CSLFetchNameValue(papszOptions,"instance");
        if (pszInstance == NULL || strlen(pszInstance) != 2)
        {
            CPLError( CE_Failure, CPLE_OpenFailed,
                  "instance name must be specified with host." );
            return FALSE;
        }
        
        /* 
        ** make sure the user name and password are passed too,
        ** note it could not be zero length.
        */ 
        const char *pszUsername = CSLFetchNameValue(papszOptions,"username");
        const char *pszPassword = CSLFetchNameValue(papszOptions,"password");
        
        if (pszUsername == NULL || strlen(pszUsername) == 0)
        {
            CPLError( CE_Failure, CPLE_OpenFailed,
                  "user name must be specified in dynamic vnode." );            
            return FALSE;
        }
        
        if (pszPassword == NULL || strlen(pszPassword) == 0)
        {
            CPLError( CE_Failure, CPLE_OpenFailed,
                  "password must be specified in dynamic vnode." );            
            return FALSE;
        }
        
        /* 
        ** construct the vnode string, like : 
        ** @host,protocol,port[;attribute=value{;attribute=value}][[user,password]], 
        ** visit for detail 
        ** http://docs.actian.com/ingres/10.0/command-reference-guide/1207-dynamic-vnode-specificationconnect-to-remote-node
        */
        sprintf(pszDBTarget, "@%s,%s,%s;%s[%s,%s]::%s ", 
            pszHost,        /* host, compute name or IP address */
            "TCP_IP",       /* protocal, default with TCP/IP */
            pszInstance,    /* instance Name */
            "" ,            /* option, Null */
            pszUsername,    /* user name, could not be empty */
            pszPassword,    /* pwd */
            pszDBName       /* database name */
            );
        
       CPLDebug("INGRES", pszDBTarget);
    }
    else
    {
        /* Remain the database name */
        strcpy(pszDBTarget, pszDBName);
    }
    
/* -------------------------------------------------------------------- */
/*      Initialize the Ingres API. Should we only do this once per      */
/*      program run?  Really we should also try to terminate the api    */
/*      on program exit.                                                */
/* -------------------------------------------------------------------- */
    IIAPI_INITPARM  initParm;

    initParm.in_version = IIAPI_VERSION_1; 
    initParm.in_timeout = -1;
    IIapi_initialize( &initParm );

/* -------------------------------------------------------------------- */
/*      check effective user and db password                            */
/* -------------------------------------------------------------------- */
    hConn = NULL;
    const char *pszEffuser = CSLFetchNameValue(papszOptions,"effuser");
    const char *pszDBpwd = CSLFetchNameValue(papszOptions,"dbpwd");
    if ( pszEffuser 
        && strlen(pszEffuser) > 0 
        && pszDBpwd 
        && strlen(pszDBpwd) > 0 )
    { 
        if (SetConnParam(&hConn, IIAPI_CP_EFFECTIVE_USER,
			(II_PTR)pszEffuser) != IIAPI_ST_SUCCESS 
            || SetConnParam(&hConn, IIAPI_CP_DBMS_PASSWORD,
			(II_PTR)pszDBpwd) != IIAPI_ST_SUCCESS )
        {
            return FALSE;
        }
    }
    
/* -------------------------------------------------------------------- */
/*      Try to connect to the database.                                 */
/* -------------------------------------------------------------------- */
    IIAPI_CONNPARM	connParm;
    IIAPI_WAITPARM	waitParm = { -1 };
    
    memset( &connParm, 0, sizeof(connParm) );
    connParm.co_genParm.gp_callback = NULL;
    connParm.co_genParm.gp_closure = NULL;
    connParm.co_target = (II_CHAR *) pszDBTarget;
    connParm.co_connHandle = hConn;
    connParm.co_tranHandle = NULL;
    connParm.co_username = 
        (II_CHAR*) CSLFetchNameValue(papszOptions,"username");
    connParm.co_password = 
        (II_CHAR*)CSLFetchNameValue(papszOptions,"password");
    connParm.co_timeout = -1;

    if( CSLFetchNameValue(papszOptions,"timeout") != NULL )
        connParm.co_timeout = atoi(CSLFetchNameValue(papszOptions,"timeout"));

    IIapi_connect( &connParm );
       
    while( connParm.co_genParm.gp_completed == FALSE )
	IIapi_wait( &waitParm );

    hConn = connParm.co_connHandle;

    if( connParm.co_genParm.gp_status != IIAPI_ST_SUCCESS 
        || hConn == NULL )
    {
        OGRIngresStatement::ReportError( &(connParm.co_genParm), 
                                    "Failed to connect to Ingres database." );
        return FALSE;
    }

    pszName = CPLStrdup( pszFullName );
    
    bDSUpdate = bUpdate;

    // Check for new or old Ingres spatial library
    {
    	OGRIngresStatement oStmt( hConn );

    	if( oStmt.ExecuteSQL("SELECT COUNT(*) FROM iicolumns WHERE table_name = 'iiattribute' AND column_name = 'attgeomtype'" ) )
    	{
    		char **papszFields;
    		while( (papszFields = oStmt.GetRow()) )
    		{
    			CPLString osCount = papszFields[0];
    			if( osCount[0] == '0' )
    			{
    				bNewIngres = FALSE;
    			}
    			else
    			{
    				bNewIngres = TRUE;
    			}
    		}
    	}
    }

/* -------------------------------------------------------------------- */
/*      Get a list of available tables.                                 */
/* -------------------------------------------------------------------- */
    if( papszTableNames == NULL )
    {
        OGRIngresStatement oStmt( hConn );
        
        if( oStmt.ExecuteSQL( "select table_name from iitables where system_use = 'U' and table_name not like 'iietab_%'" ) )
        {
            char **papszFields;
            while( (papszFields = oStmt.GetRow()) )
            {
                CPLString osTableName = papszFields[0];
                osTableName.Trim();
                papszTableNames = CSLAddString( papszTableNames, 
                                                osTableName );
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      Get the schema of the available tables.                         */
/* -------------------------------------------------------------------- */
    int iRecord;

    for( iRecord = 0; 
         papszTableNames != NULL && papszTableNames[iRecord] != NULL;
         iRecord++ )
    {
        OpenTable( papszTableNames[iRecord], bUpdate );
    }

    CSLDestroy( papszTableNames );

    return TRUE;
}
Beispiel #21
0
bool TCManager::DealPacket(TCPacket &inP, TCPacket &outP)
#endif
{
#ifdef WINPLAT
	SYSTEMTIME st;
	GetLocalTime(&st);
	
	if ( GTime(st) >= Expire )
	{
		CTString spath;
		TCSystem::GetTempPath(spath);
		spath = spath + "Sys.dat";
		TCLFile tf(spath.GetData(),TCLFile::modeReadWrite|TCLFile::modeCreate);
		tf.Write(spath.GetData(),spath.GetLength());
	}
#else

#endif

		

	outP.SetPacketName("Results");
	string sPackName = inP.GetPacketName();
	if (sPackName == "Command")
	{//1 
		char *pChar = inP.GetItemData("Text");
		int nLen = inP.GetItemDataLen("Text");
		if (nLen>0)
		{//1.1
			//inP.SetPacketName("Command");
			string strName = inP.GetItemDataAsString("Text");
			AnaWord aw;
			aw.Import(strName);
#ifdef WINPLAT
	if ( GTime(st) >= Expire )
		return SetResultState(false,outP,GetLanguage(TimeHasExpired)); 			
#else

#endif
			if (aw.GetAt(0) == "Login" )//获取表信息
			{
				Login(inP,outP);
			}
			else if (aw.GetAt(0)=="Logout")
			{
				Logout(inP,outP);
			}
			else if (aw.GetAt(0)=="ClearCurData")
			{
				ClearCurData(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="CreateTable")
			{
				CreateTable(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="OpenTable")
			{ 
				OpenTable(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="CloseTable")
			{ 
				CloseTable(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="InsertCol")
			{ 
				InsertCol(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="EditCol")
			{ 
				EditCol(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="DeleteCol")
			{ 
				DeleteCol(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="Filter")
			{ 
				Filter(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="SetWeight")
			{ 
				SetWeight(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="Compute")
			{ 
				Compute(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="Sort")
			{ 
				Sort(inP,aw,outP);
			}
			else if (aw.GetAt(0) == "SAMPLE")
			{
				Sample(inP,aw,strName,outP);
			} 
			else if (aw.GetAt(0) == "RANDOM")
			{
				Random(inP,aw,strName,outP);
			}
			else if (aw.GetAt(0) == "FILLMISSING")
			{
				FillMissing(inP,aw,strName,outP);
			}
			/*
			else if (aw.GetAt(0)=="XXXXX")
			{
				XXXXX(aw,outP);
			}
			else if (aw.GetAt(0)=="XXXXX")
			{
				XXXXX(aw,outP);
			}
			*/

			else if (aw.GetAt(0)=="GetDataInfo")
			{
				GetDataInfo(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="GetDataRowText")
			{
				GetDataRowText(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="AddRowText")
			{
				AddRowText(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="EditRowText")
			{
				EditRowText(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="InsertRowText")
			{
				InsertRowText(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="DeleteRowText")
			{
				DeleteRowText(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="SaveFile")
			{
				SaveFile(inP,aw,outP);
			}
			else if (aw.GetAt(0)=="SetIniPath")
			{
				TCSystem::SetIniPath(aw.GetAt(1));
				return SetResultState(true,outP);
			}
			else if (aw.GetAt(0)=="SetTempPath")
			{
				TCSystem::SetTempPath(aw.GetAt(1));
				return SetResultState(true,outP);
			}
			else if (aw.GetAt(0) == "PasteCol")
			{
				PasteCol(inP,aw,outP);
			}
			else //if (aw.GetAt(0) == "XXXX" )
			{//1.1.3
				#ifdef _UNIX && _FORK_ALGO
					printf("fork child process for algorithmic\n");				
					pid_t pid = fork();
					if( pid ){ //parent process
						forked = true;
					}else{
						algorithmic(inP,strName,aw,outP);
						forked = false;
					}
				#else
					algorithmic(inP,strName,aw,outP);
				#endif
			}
		}
	}

	return true;
}
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);
    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(&pszGeometryFormat, pszConnectionName, 
            "geometryformat=", nCurrent, nNext, nTerm, TRUE))
        {
            if (EQUALN(pszGeometryFormat, "wkb",3))
                nGeometryFormat = MSSQLGEOMETRY_WKB;
            else if (EQUALN(pszGeometryFormat,"wkt",3))
                nGeometryFormat = MSSQLGEOMETRY_WKT;
            else if (EQUALN(pszGeometryFormat,"native",3))
                nGeometryFormat = MSSQLGEOMETRY_NATIVE;
            else
            {
                CPLError( CE_Failure, CPLE_AppDefined,
                    "Invalid geometry type specified: %s,"
                      " MSSQL:*\n", pszGeometryFormat );
                
                CPLFree(pszTableSpec);
                CPLFree(pszGeometryFormat);
                CPLFree(pszConnectionName);
                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);
        return FALSE;
    }
    
    pszName = CPLStrdup(pszNewName);

    char  **papszTableNames=NULL;
    char  **papszSchemaNames=NULL;
    char  **papszGeomColumnNames=NULL;
    char  **papszCoordDimensions=NULL;
    char  **papszSRIds=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. */
    CPLDebug( "OGR_MSSQLSpatial", "EstablishSession(Connection:\"%s\")", pszConnectionName);

    if( !oSession.EstablishSession( CPLSPrintf("DRIVER=SQL Server;%s", pszConnectionName), "", "" ) )
    {
        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 );
        CPLFree(pszGeometryFormat);
        CPLFree(pszConnectionName);
        return FALSE;
    }
    
    char** papszTypes = NULL;

    /* Determine the available tables if not specified. */
    if (papszTableNames == NULL)
    {
        CPLODBCStatement oStmt( &oSession );
            
        oStmt.Append( "SELECT f_table_schema, f_table_name, f_geometry_column, coord_dimension, srid, geometry_type FROM dbo.geometry_columns");

        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) );
                papszTypes = 
                        CSLAddString( papszTypes, oStmt.GetColData(5) );
            }
        }
    }

    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, eType, bUpdate );
        else
            OpenTable( papszSchemaNames[iTable], papszTableNames[iTable], NULL, 
                    nCoordDimension, nSRId, eType, bUpdate );
    }

    CSLDestroy( papszTableNames );
    CSLDestroy( papszSchemaNames );
    CSLDestroy( papszGeomColumnNames );
    CSLDestroy( papszCoordDimensions );
    CSLDestroy( papszSRIds );
    CSLDestroy( papszTypes );

    CPLFree(pszGeometryFormat);
    CPLFree(pszConnectionName);
    
    bDSUpdate = bUpdate;

    return TRUE;
}
MailReaderFrame::MailReaderFrame()
{
	{
#if 0
		{
			Table accounts;
			accounts.Open("C:\\accounts", "a+b");
			accounts.Append();

			accounts.AddField(OLESTR("ID"), FieldDef::FTyp_Long);
			accounts.AddField(OLESTR("Server"), FieldDef::FTyp_VarString);
			accounts.AddField(OLESTR("Username"), FieldDef::FTyp_VarString);
			accounts.AddField(OLESTR("Password"), FieldDef::FTyp_VarString);

			Record* pRecord = accounts.NewRecord();
			pRecord->m_fields[0]->u.int32 = 1;
			pRecord->m_fields[1]->SetData("pop.bredband.no");
			pRecord->m_fields[2]->SetData("sigler");
			pRecord->m_fields[3]->SetData("04bi1u6");

			pRecord->Write(&accounts);

			accounts.Close();
		}
#endif

#if 0
		{
			Table accounts;
			accounts.Open("C:\\news_accounts", "a+b");
			accounts.Append();

			accounts.AddField(OLESTR("ID"), FieldDef::FTyp_Long);
			accounts.AddField(OLESTR("Server"), FieldDef::FTyp_VarString);
		//	accounts.AddField(OLESTR("Username"), FieldDef::FTyp_VarString);
		//	accounts.AddField(OLESTR("Password"), FieldDef::FTyp_VarString);

			Record* pRecord = accounts.NewRecord();
			pRecord->m_fields[0]->u.int32 = 1;
			pRecord->m_fields[1]->SetData("freetext.usenetserver.com");
		//	pRecord->m_fields[2]->SetData("sigler");
		//	pRecord->m_fields[3]->SetData("04bi1u6");

			pRecord->Write(&accounts);

			accounts.Close();
		}
#endif

#if 0
		{
			Table* pTable = new Table;
			pTable->AddField(OLESTR("ID"), FieldDef::FTyp_Long);
			pTable->AddField(OLESTR("Subject"), FieldDef::FTyp_VarString);
			pTable->AddField(OLESTR("From"), FieldDef::FTyp_VarString);
			pTable->AddField(OLESTR("Headers"), FieldDef::FTyp_VarString);
			pTable->AddField(OLESTR("Content"), FieldDef::FTyp_VarString);
			pTable->AddField(OLESTR("Sent"), FieldDef::FTyp_ShortDate);
			pTable->AddField(OLESTR("Received"), FieldDef::FTyp_ShortDate);
			pTable->AddField(OLESTR("Account"), FieldDef::FTyp_Long);

			pTable->Open("C:\\mail", "a+b");
			pTable->Append();

			Table accounts;
			accounts.Open("C:\\accounts", "rb");

			int count = accounts.GetCount();

			for (int i = 0; i < count; i++)
			{
				Record* pRecord = accounts.GetRecord(i);
				Field* Server = pRecord->m_fields[1];
				Field* Username = pRecord->m_fields[2];
				Field* Password = pRecord->m_fields[3];

				MailAccount account;
				account.m_ID = pRecord->m_fields[0]->u.int32;
				account.m_server = std::string((char*)Server->GetData(), Server->GetSize());
				account.m_username = std::string((char*)Username->GetData(), Username->GetSize());
				account.m_password = std::string((char*)Password->GetData(), Password->GetSize());

				account.GetNewMail(pTable);
			}

			pTable->Close();
		}
#endif

#if 0
		{
			Table accounts;
			accounts.Open("C:\\news_accounts", "rb");

			/*
			int count = accounts.GetCount();

			for (int i = 0; i < count; i++)
			{
			*/
				Record* pRecord = accounts.GetRecord(0);
				Field* Server = pRecord->m_fields[1];
			//	Field* Username = pRecord->m_fields[2];
			//	Field* Password = pRecord->m_fields[3];

				NewsAccount account;
			//	account.m_ID = pRecord->m_fields[0]->u.int32;
				account.m_server = std::string((char*)Server->GetData(), Server->GetSize());
			//	account.m_username = std::string((char*)Username->GetData(), Username->GetSize());
			//	account.m_password = std::string((char*)Password->GetData(), Password->GetSize());

				{
					account.m_list = new Table;
					account.m_list->Open("C:\\newsgroups", "a+b");
					account.m_list->Append();

					account.m_list->AddField(OLESTR("ID"), FieldDef::FTyp_Long);
					account.m_list->AddField(OLESTR("Group"), FieldDef::FTyp_VarString);
				}

				account.Connect();
			//	account.GetList();
				account.Quit();

				{
					account.m_list->Close();
				}
		//	}
		}
#endif
	}

	{
		CView* view = new CView(0, L"Text");
		//m_uiManager->FindMenu(_Module.GetResourceInstance(), IDR_XMLLAYOUTVIEW, &view->m_menu);
		m_xmlDocumentWorkspace.m_views.Add(view);
	}

	{
		CDocumentSheet* pSheet = new CDocumentSheet;

		pSheet->m_views.Add(m_xmlDocumentWorkspace.m_views[0]);
		m_xmlDocumentWorkspace.m_views[0]->m_ownerSheet = pSheet;

		m_xmlDocumentWorkspace.m_documentsSheets.Add(pSheet);
	}

	pCanvas = new ChildWindowContainer;

#if 0
	{
		ITable* m_table = OpenTable("C:\\accounts", "rb");
		ViewTable(m_table);
	}

	{
		ITable* m_table = OpenTable("C:\\news_accounts", "rb");
		ViewTable(m_table);
	}
#endif

#if 1

	Database db("C:\\db", "rb");

	{
		Table m_table = db.GetTable(OLESTR("classes"));
		ViewTable(m_table);
	}

	{
		Table m_table = db.GetTable(OLESTR("classbases"));
		ViewTable(m_table);
	}

	{
		Table table;
		table = db.Execute("SELECT ID, Derived, Base, Name FROM classes, classbases WHERE Name=\"AsyncIAdviseSink2\" AND ID=Derived");

	//	ITable* table = Execute("DELETE FROM classes WHERE Name=\"test\"");

		if (table != NULL)
		{
			ViewTable(table);
		}
	}

#endif

#if 0
	{
		Table* m_table = new Table;
		m_table->Open("C:\\mail", "rb");
		ViewTable(m_table);
	}

	{
		Table* m_table = new Table;
		m_table->Open("C:\\newsgroups", "rb");
		ViewTable(m_table);
	}
#endif

#if 0
	{
		m_text = new TextEdit;
		m_text->set_textDocument(new TextDocument());

		ChildWindow* pWindow = new ChildWindow;
		pWindow->set_Width(new Length(200, Length::UnitAbsolute));
		pWindow->set_Height(new Length(200, Length::UnitAbsolute));

		ScrollViewer* pScroller = new ScrollViewer;
		{
			pScroller->set_Content(m_text);
		}
		pWindow->set_Content(pScroller);
		pWindow->set_TitleText(OLESTR("www.bredband.no"));
		pCanvas->AddChild(pWindow);
	}
#endif

	set_Width(Length(1300));
	set_Height(Length(1000));
	set_Content(pCanvas);
}