Search in sources :

Example 41 with DBException

use of org.jkiss.dbeaver.DBException in project dbeaver by serge-rider.

the class JDBCObjectLookupCache method reloadObject.

protected OBJECT reloadObject(@NotNull DBRProgressMonitor monitor, @NotNull OWNER owner, @Nullable OBJECT object, @Nullable String objectName) throws DBException {
    DBPDataSource dataSource = owner.getDataSource();
    if (dataSource == null) {
        throw new DBException("Not connected to database");
    }
    try (JDBCSession session = DBUtils.openMetaSession(monitor, dataSource, object == null ? "Load object '" + objectName + "' from " + owner.getName() : "Reload object '" + object + "' from " + owner.getName())) {
        try (JDBCStatement dbStat = prepareLookupStatement(session, owner, object, objectName)) {
            dbStat.setFetchSize(1);
            dbStat.executeStatement();
            JDBCResultSet dbResult = dbStat.getResultSet();
            if (dbResult != null) {
                try {
                    if (dbResult.next()) {
                        return fetchObject(session, owner, dbResult);
                    }
                } finally {
                    dbResult.close();
                }
            }
            return null;
        }
    } catch (SQLException ex) {
        throw new DBException(ex, dataSource);
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) JDBCSession(org.jkiss.dbeaver.model.exec.jdbc.JDBCSession) JDBCStatement(org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement) SQLException(java.sql.SQLException) JDBCResultSet(org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource)

Example 42 with DBException

use of org.jkiss.dbeaver.DBException in project dbeaver by serge-rider.

the class JDBCStructCache method loadChildren.

/**
     * Reads children objects from database
     * 
     * @param monitor
     *            monitor
     * @param forObject
     *            object for which to read children. If null then reads children for all objects in this container.
     * @throws org.jkiss.dbeaver.DBException
     *             on error
     */
public synchronized void loadChildren(DBRProgressMonitor monitor, OWNER owner, @Nullable final OBJECT forObject) throws DBException {
    if ((forObject == null && this.childrenCached) || (forObject != null && (!forObject.isPersisted() || isChildrenCached(forObject))) || monitor.isCanceled()) {
        return;
    }
    if (forObject == null) {
        // If we have some child objects read before that - do not clear them.
        // We have to reuse them because there could be some references in cached model
        //clearChildrenCache(null);
        super.loadObjects(monitor, owner);
    }
    DBPDataSource dataSource = owner.getDataSource();
    if (dataSource == null) {
        throw new DBException("Not connected to database");
    }
    try (JDBCSession session = DBUtils.openMetaSession(monitor, dataSource, "Load child objects")) {
        Map<OBJECT, List<CHILD>> objectMap = new HashMap<>();
        // Load columns
        try (JDBCStatement dbStat = prepareChildrenStatement(session, owner, forObject)) {
            dbStat.setFetchSize(DBConstants.METADATA_FETCH_SIZE);
            dbStat.executeStatement();
            JDBCResultSet dbResult = dbStat.getResultSet();
            if (dbResult != null) {
                try {
                    while (dbResult.next()) {
                        if (monitor.isCanceled()) {
                            break;
                        }
                        String objectName;
                        if (objectNameColumn instanceof Number) {
                            objectName = JDBCUtils.safeGetString(dbResult, ((Number) objectNameColumn).intValue());
                        } else {
                            objectName = JDBCUtils.safeGetStringTrimmed(dbResult, objectNameColumn.toString());
                        }
                        if (objectName == null) {
                            log.debug("NULL object name in " + this);
                            continue;
                        }
                        OBJECT object = forObject;
                        if (object == null) {
                            object = super.getCachedObject(objectName);
                            if (object == null) {
                                log.debug("Object '" + objectName + "' not found");
                                continue;
                            }
                        }
                        if (isChildrenCached(object)) {
                            // Already read
                            continue;
                        }
                        CHILD child = fetchChild(session, owner, object, dbResult);
                        if (child == null) {
                            continue;
                        }
                        // Add to map
                        List<CHILD> children = objectMap.get(object);
                        if (children == null) {
                            children = new ArrayList<>();
                            objectMap.put(object, children);
                        }
                        children.add(child);
                    }
                    if (monitor.isCanceled()) {
                        return;
                    }
                    // All children are read. Now assign them to parents
                    for (Map.Entry<OBJECT, List<CHILD>> colEntry : objectMap.entrySet()) {
                        if (!isChildrenCached(colEntry.getKey())) {
                            // isChildrenCached may return true if the same cache was read in other thread
                            // just skip
                            cacheChildren(colEntry.getKey(), colEntry.getValue());
                        }
                    }
                    if (forObject == null) {
                        if (objectMap.isEmpty()) {
                        // Nothing was read. May be it means empty list of children
                        // but possibly this feature is not supported [JDBC: SQLite]
                        } else {
                            // Now set empty column list for other tables
                            for (OBJECT tmpObject : getAllObjects(monitor, owner)) {
                                if (!isChildrenCached(tmpObject) && !objectMap.containsKey(tmpObject)) {
                                    cacheChildren(tmpObject, new ArrayList<CHILD>());
                                }
                            }
                            this.childrenCached = true;
                        }
                    } else if (!objectMap.containsKey(forObject)) {
                        cacheChildren(forObject, new ArrayList<CHILD>());
                    }
                } finally {
                    dbResult.close();
                }
            }
        }
    } catch (SQLException ex) {
        throw new DBException(ex, dataSource);
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) JDBCSession(org.jkiss.dbeaver.model.exec.jdbc.JDBCSession) SQLException(java.sql.SQLException) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) JDBCStatement(org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement) JDBCResultSet(org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet)

Example 43 with DBException

use of org.jkiss.dbeaver.DBException in project dbeaver by serge-rider.

the class DefaultCertificateStorage method deleteCertificate.

@Override
public void deleteCertificate(DBPDataSourceContainer dataSource, String certType) throws DBException {
    final KeyStore keyStore = getKeyStore(dataSource, certType);
    try {
        keyStore.deleteEntry("ca-cert");
        keyStore.deleteEntry("client-cert");
        keyStore.deleteEntry("key-cert");
        saveKeyStore(dataSource, certType, keyStore);
    } catch (Exception e) {
        throw new DBException("Error deleting certificate from keystore", e);
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) KeyStore(java.security.KeyStore) GeneralSecurityException(java.security.GeneralSecurityException) DBException(org.jkiss.dbeaver.DBException)

Example 44 with DBException

use of org.jkiss.dbeaver.DBException in project dbeaver by serge-rider.

the class SQLQueryJob method executeSingleQuery.

private boolean executeSingleQuery(@NotNull DBCSession session, @NotNull SQLQuery sqlQuery, final boolean fireEvents) {
    lastError = null;
    final DBCExecutionContext executionContext = getExecutionContext();
    final DBPDataSource dataSource = executionContext.getDataSource();
    final SQLQuery originalQuery = sqlQuery;
    long startTime = System.currentTimeMillis();
    boolean startQueryAlerted = false;
    if (!prepareStatementParameters(sqlQuery)) {
        return false;
    }
    // Modify query (filters + parameters)
    if (dataFilter != null && dataFilter.hasFilters() && dataSource instanceof SQLDataSource) {
        String filteredQueryText = ((SQLDataSource) dataSource).getSQLDialect().addFiltersToQuery(dataSource, originalQuery.getQuery(), dataFilter);
        sqlQuery = new SQLQuery(executionContext.getDataSource(), filteredQueryText, sqlQuery);
    }
    final SQLQueryResult curResult = new SQLQueryResult(sqlQuery);
    if (rsOffset > 0) {
        curResult.setRowOffset(rsOffset);
    }
    try {
        // Prepare statement
        closeStatement();
        // Check and invalidate connection
        if (!connectionInvalidated && dataSource.getContainer().getPreferenceStore().getBoolean(DBeaverPreferences.STATEMENT_INVALIDATE_BEFORE_EXECUTE)) {
            executionContext.invalidateContext(session.getProgressMonitor());
            connectionInvalidated = true;
        }
        statistics.setQueryText(originalQuery.getQuery());
        // Notify query start
        if (fireEvents && listener != null) {
            // Notify query start
            try {
                listener.onStartQuery(session, sqlQuery);
            } catch (Exception e) {
                log.error(e);
            }
            startQueryAlerted = true;
        }
        startTime = System.currentTimeMillis();
        DBCExecutionSource source = new AbstractExecutionSource(dataContainer, executionContext, partSite.getPart(), sqlQuery);
        final DBCStatement dbcStatement = DBUtils.makeStatement(source, session, DBCStatementType.SCRIPT, sqlQuery, rsOffset, rsMaxRows);
        curStatement = dbcStatement;
        int statementTimeout = getDataSourceContainer().getPreferenceStore().getInt(DBeaverPreferences.STATEMENT_TIMEOUT);
        if (statementTimeout > 0) {
            try {
                dbcStatement.setStatementTimeout(statementTimeout);
            } catch (Throwable e) {
                log.debug("Can't set statement timeout:" + e.getMessage());
            }
        }
        // Execute statement
        try {
            boolean hasResultSet = dbcStatement.executeStatement();
            curResult.setHasResultSet(hasResultSet);
            statistics.addExecuteTime(System.currentTimeMillis() - startTime);
            statistics.addStatementsCount();
            long updateCount = -1;
            while (hasResultSet || resultSetNumber == 0 || updateCount >= 0) {
                // Fetch data only if we have to fetch all results or if it is rs requested
                if (fetchResultSetNumber < 0 || fetchResultSetNumber == resultSetNumber) {
                    if (hasResultSet && fetchResultSets) {
                        DBDDataReceiver dataReceiver = resultsConsumer.getDataReceiver(sqlQuery, resultSetNumber);
                        if (dataReceiver != null) {
                            hasResultSet = fetchQueryData(session, dbcStatement.openResultSet(), curResult, dataReceiver, true);
                        }
                    }
                }
                if (!hasResultSet) {
                    try {
                        updateCount = dbcStatement.getUpdateRowCount();
                        if (updateCount >= 0) {
                            curResult.setUpdateCount(updateCount);
                            statistics.addRowsUpdated(updateCount);
                        }
                    } catch (DBCException e) {
                        // In some cases we can't read update count
                        // This is bad but we can live with it
                        // Just print a warning
                        log.warn("Can't obtain update count", e);
                    }
                }
                if (hasResultSet && fetchResultSets) {
                    resultSetNumber++;
                    fetchResultSetNumber = resultSetNumber;
                }
                if (!hasResultSet && updateCount < 0) {
                    // Nothing else to fetch
                    break;
                }
                if (dataSource.getInfo().supportsMultipleResults()) {
                    hasResultSet = dbcStatement.nextResults();
                    updateCount = hasResultSet ? -1 : 0;
                } else {
                    break;
                }
            }
            try {
                curResult.setWarnings(dbcStatement.getStatementWarnings());
            } catch (Throwable e) {
                log.warn("Can't read execution warnings", e);
            }
        } finally {
            //monitor.subTask("Close query");
            if (!keepStatementOpen()) {
                closeStatement();
            }
        }
    } catch (Throwable ex) {
        if (!(ex instanceof DBException)) {
            log.error("Unexpected error while processing SQL", ex);
        }
        curResult.setError(ex);
        lastError = ex;
    } finally {
        curResult.setQueryTime(System.currentTimeMillis() - startTime);
        if (fireEvents && listener != null && startQueryAlerted) {
            // Notify query end
            try {
                listener.onEndQuery(session, curResult);
            } catch (Exception e) {
                log.error(e);
            }
        }
    }
    if (curResult.getError() != null && errorHandling != SQLScriptErrorHandling.IGNORE) {
        return false;
    }
    // Success
    lastGoodQuery = originalQuery;
    return true;
}
Also used : DBException(org.jkiss.dbeaver.DBException) SQLQueryResult(org.jkiss.dbeaver.model.sql.SQLQueryResult) DBDDataReceiver(org.jkiss.dbeaver.model.data.DBDDataReceiver) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) SQLQuery(org.jkiss.dbeaver.model.sql.SQLQuery) SQLDataSource(org.jkiss.dbeaver.model.sql.SQLDataSource) DBException(org.jkiss.dbeaver.DBException) AbstractExecutionSource(org.jkiss.dbeaver.model.impl.AbstractExecutionSource)

Example 45 with DBException

use of org.jkiss.dbeaver.DBException in project dbeaver by serge-rider.

the class DataSourceDescriptor method connect.

public boolean connect(DBRProgressMonitor monitor, boolean initialize, boolean reflect) throws DBException {
    if (connecting) {
        log.debug("Can't connect - connect/disconnect is in progress");
        return false;
    }
    if (this.isConnected()) {
        log.debug("Can't connect - already connected");
        return false;
    }
    log.debug("Connect with '" + getName() + "' (" + getId() + ")");
    //final String oldPassword = getConnectionConfiguration().getUserPassword();
    if (!isSavePassword()) {
        // Ask for password
        if (!DataSourceHandler.askForPassword(this, null)) {
            DataSourceHandler.updateDataSourceObject(this);
            return false;
        }
    }
    processEvents(monitor, DBPConnectionEventType.BEFORE_CONNECT);
    connecting = true;
    tunnelConnectionInfo = null;
    try {
        // Handle tunnel
        // Open tunnel and replace connection info with new one
        this.tunnel = null;
        DBWHandlerConfiguration tunnelConfiguration = null;
        for (DBWHandlerConfiguration handler : connectionInfo.getDeclaredHandlers()) {
            if (handler.isEnabled() && handler.getType() == DBWHandlerType.TUNNEL) {
                tunnelConfiguration = handler;
                break;
            }
        }
        monitor.beginTask("Connect to " + getName(), tunnelConfiguration != null ? 3 : 2);
        if (tunnelConfiguration != null) {
            monitor.subTask("Initialize tunnel");
            tunnel = tunnelConfiguration.createHandler(DBWTunnel.class);
            try {
                if (!tunnelConfiguration.isSavePassword() && tunnel.needsPassword(tunnelConfiguration)) {
                    if (!DataSourceHandler.askForPassword(this, tunnelConfiguration)) {
                        DataSourceHandler.updateDataSourceObject(this);
                        tunnel = null;
                        return false;
                    }
                }
                /*
                    for (DBWHandlerConfiguration handler : getConnectionConfiguration().getDeclaredHandlers()) {
                        if (handler.isEnabled() && handler.isSecured() && !handler.isSavePassword()) {
                            if (!DataSourceHandler.askForPassword(this, handler)) {
                                DataSourceHandler.updateDataSourceObject(this);
                                return false;
                            }
                        }
                    }
*/
                tunnelConnectionInfo = tunnel.initializeTunnel(monitor, registry.getPlatform(), tunnelConfiguration, connectionInfo);
            } catch (Exception e) {
                throw new DBCException("Can't initialize tunnel", e);
            }
            monitor.worked(1);
        }
        monitor.subTask("Connect to data source");
        dataSource = getDriver().getDataSourceProvider().openDataSource(monitor, this);
        monitor.worked(1);
        if (initialize) {
            monitor.subTask("Initialize data source");
            try {
                dataSource.initialize(monitor);
            } catch (Throwable e) {
                log.error("Error initializing datasource", e);
            }
            // Change connection properties
            initConnectionState(monitor);
        }
        connectFailed = false;
        connectTime = new Date();
        processEvents(monitor, DBPConnectionEventType.AFTER_CONNECT);
        if (reflect) {
            getRegistry().notifyDataSourceListeners(new DBPEvent(DBPEvent.Action.OBJECT_UPDATE, DataSourceDescriptor.this, true));
        }
        log.debug("Connected (" + getId() + ")");
        return true;
    } catch (Exception e) {
        log.debug("Connection failed (" + getId() + ")");
        if (tunnel != null) {
            try {
                tunnel.closeTunnel(monitor);
            } catch (IOException e1) {
                log.error("Error closing tunnel", e);
            } finally {
                tunnel = null;
                tunnelConnectionInfo = null;
            }
        }
        // Failed
        connectFailed = true;
        //if (reflect) {
        getRegistry().notifyDataSourceListeners(new DBPEvent(DBPEvent.Action.OBJECT_UPDATE, DataSourceDescriptor.this, false));
        //}
        if (e instanceof DBException) {
            throw (DBException) e;
        } else {
            throw new DBException("Internal error connecting to " + getName(), e);
        }
    } finally {
        monitor.done();
        connecting = false;
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBWHandlerConfiguration(org.jkiss.dbeaver.model.net.DBWHandlerConfiguration) DBWTunnel(org.jkiss.dbeaver.model.net.DBWTunnel) DBCException(org.jkiss.dbeaver.model.exec.DBCException) IOException(java.io.IOException) DBCException(org.jkiss.dbeaver.model.exec.DBCException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) DBException(org.jkiss.dbeaver.DBException)

Aggregations

DBException (org.jkiss.dbeaver.DBException)232 SQLException (java.sql.SQLException)58 JDBCSession (org.jkiss.dbeaver.model.exec.jdbc.JDBCSession)51 JDBCResultSet (org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet)50 DBRProgressMonitor (org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)43 JDBCPreparedStatement (org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement)42 ArrayList (java.util.ArrayList)37 InvocationTargetException (java.lang.reflect.InvocationTargetException)23 DBSObject (org.jkiss.dbeaver.model.struct.DBSObject)23 DBNDatabaseNode (org.jkiss.dbeaver.model.navigator.DBNDatabaseNode)16 DBRRunnableWithProgress (org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress)14 DBPDataSource (org.jkiss.dbeaver.model.DBPDataSource)13 DBNNode (org.jkiss.dbeaver.model.navigator.DBNNode)13 GridData (org.eclipse.swt.layout.GridData)12 DBCException (org.jkiss.dbeaver.model.exec.DBCException)12 CoreException (org.eclipse.core.runtime.CoreException)11 AbstractObjectReference (org.jkiss.dbeaver.model.impl.struct.AbstractObjectReference)10 IStatus (org.eclipse.core.runtime.IStatus)9 DBSEntityAttribute (org.jkiss.dbeaver.model.struct.DBSEntityAttribute)8 XMLException (org.jkiss.utils.xml.XMLException)8