Search in sources :

Example 61 with JDBCStatement

use of org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement in project dbeaver by serge-rider.

the class JDBCCompositeCache method loadObjects.

protected void loadObjects(DBRProgressMonitor monitor, OWNER owner, PARENT forParent) throws DBException {
    synchronized (objectCache) {
        if ((forParent == null && isFullyCached()) || (forParent != null && (!forParent.isPersisted() || objectCache.containsKey(forParent)))) {
            return;
        }
    }
    // Load tables and columns first
    if (forParent == null) {
        parentCache.loadObjects(monitor, owner);
        parentCache.loadChildren(monitor, owner, null);
    }
    Map<PARENT, Map<String, ObjectInfo>> parentObjectMap = new LinkedHashMap<>();
    // Load index columns
    DBPDataSource dataSource = owner.getDataSource();
    assert (dataSource != null);
    monitor.beginTask("Load composite cache", 1);
    try (JDBCSession session = DBUtils.openMetaSession(monitor, owner, "Load composite objects")) {
        JDBCStatement dbStat = prepareObjectsStatement(session, owner, forParent);
        dbStat.setFetchSize(DBConstants.METADATA_FETCH_SIZE);
        try {
            dbStat.executeStatement();
            JDBCResultSet dbResult = dbStat.getResultSet();
            if (dbResult != null)
                try {
                    while (dbResult.next()) {
                        if (monitor.isCanceled()) {
                            return;
                        }
                        String parentName = forParent != null ? forParent.getName() : (parentColumnName instanceof Number ? JDBCUtils.safeGetString(dbResult, ((Number) parentColumnName).intValue()) : JDBCUtils.safeGetString(dbResult, parentColumnName.toString()));
                        String objectName = objectColumnName instanceof Number ? JDBCUtils.safeGetString(dbResult, ((Number) objectColumnName).intValue()) : JDBCUtils.safeGetString(dbResult, objectColumnName.toString());
                        if (CommonUtils.isEmpty(objectName)) {
                            // Use default name
                            objectName = getDefaultObjectName(dbResult, parentName);
                        }
                        if (forParent == null && CommonUtils.isEmpty(parentName)) {
                            // No parent - can't evaluate it
                            log.debug("Empty parent name in " + this);
                            continue;
                        }
                        PARENT parent = forParent;
                        if (parent == null) {
                            parent = parentCache.getObject(monitor, owner, parentName, parentType);
                            if (parent == null) {
                                log.debug("Object '" + objectName + "' owner '" + parentName + "' not found");
                                continue;
                            }
                        }
                        synchronized (objectCache) {
                            if (objectCache.containsKey(parent)) {
                                // Already cached
                                continue;
                            }
                        }
                        // Add to map
                        Map<String, ObjectInfo> objectMap = parentObjectMap.get(parent);
                        if (objectMap == null) {
                            objectMap = new TreeMap<>();
                            parentObjectMap.put(parent, objectMap);
                        }
                        ObjectInfo objectInfo = objectMap.get(objectName);
                        if (objectInfo == null) {
                            OBJECT object = fetchObject(session, owner, parent, objectName, dbResult);
                            if (object == null || !isValidObject(monitor, owner, object)) {
                                // Can't fetch object
                                continue;
                            }
                            objectName = object.getName();
                            objectInfo = new ObjectInfo(object);
                            objectMap.put(objectName, objectInfo);
                        }
                        ROW_REF[] rowRef = fetchObjectRow(session, parent, objectInfo.object, dbResult);
                        if (rowRef == null || rowRef.length == 0) {
                            // At least one of rows is broken.
                            // So entire object is broken, let's just skip it.
                            objectInfo.broken = true;
                            // log.debug("Object '" + objectName + "' metadata corrupted - NULL child returned");
                            continue;
                        }
                        for (ROW_REF row : rowRef) {
                            if (row != null) {
                                objectInfo.rows.add(row);
                            }
                        }
                    }
                } finally {
                    dbResult.close();
                }
        } finally {
            dbStat.close();
        }
    } catch (SQLException ex) {
        if (ex instanceof SQLFeatureNotSupportedException) {
            log.debug("Error reading cache: feature not supported", ex);
        } else {
            throw new DBException(ex, dataSource);
        }
    } finally {
        monitor.done();
    }
    if (monitor.isCanceled()) {
        return;
    }
    // Fill global cache
    synchronized (this) {
        synchronized (objectCache) {
            if (forParent != null || !parentObjectMap.isEmpty()) {
                if (forParent == null) {
                    // Cache global object list
                    List<OBJECT> globalCache = new ArrayList<>();
                    for (Map<String, ObjectInfo> objMap : parentObjectMap.values()) {
                        if (objMap != null) {
                            for (ObjectInfo info : objMap.values()) {
                                if (!info.broken) {
                                    globalCache.add(info.object);
                                }
                            }
                        }
                    }
                    // Save precached objects in global cache
                    for (List<OBJECT> objects : objectCache.values()) {
                        globalCache.addAll(objects);
                    }
                    // Add precached objects to global cache too
                    super.setCache(globalCache);
                    this.invalidateObjects(monitor, owner, new CacheIterator());
                }
            }
            // All objects are read. Now assign them to parents
            for (Map.Entry<PARENT, Map<String, ObjectInfo>> colEntry : parentObjectMap.entrySet()) {
                if (colEntry.getValue() == null || objectCache.containsKey(colEntry.getKey())) {
                    // Do not overwrite this object's cache
                    continue;
                }
                Collection<ObjectInfo> objectInfos = colEntry.getValue().values();
                ArrayList<OBJECT> objects = new ArrayList<>(objectInfos.size());
                for (ObjectInfo objectInfo : objectInfos) {
                    objectInfo.needsCaching = true;
                    objects.add(objectInfo.object);
                }
                objectCache.put(colEntry.getKey(), objects);
            }
            // Now set empty object list for other parents
            if (forParent == null) {
                for (PARENT tmpParent : parentCache.getTypedObjects(monitor, owner, parentType)) {
                    if (!parentObjectMap.containsKey(tmpParent) && !objectCache.containsKey(tmpParent)) {
                        objectCache.put(tmpParent, new ArrayList<OBJECT>());
                    }
                }
            } else if (!parentObjectMap.containsKey(forParent) && !objectCache.containsKey(forParent)) {
                objectCache.put(forParent, new ArrayList<OBJECT>());
            }
        }
        // Cache children lists (we do it in the end because children caching may operate with other model objects)
        for (Map.Entry<PARENT, Map<String, ObjectInfo>> colEntry : parentObjectMap.entrySet()) {
            for (ObjectInfo objectInfo : colEntry.getValue().values()) {
                if (objectInfo.needsCaching) {
                    cacheChildren(monitor, objectInfo.object, objectInfo.rows);
                }
            }
        }
        for (Map.Entry<PARENT, Map<String, ObjectInfo>> colEntry : parentObjectMap.entrySet()) {
            for (ObjectInfo objectInfo : colEntry.getValue().values()) {
                if (objectInfo.needsCaching) {
                    cacheChildren2(monitor, objectInfo.object, objectInfo.rows);
                }
            }
        }
    }
}
Also used : JDBCSession(org.jkiss.dbeaver.model.exec.jdbc.JDBCSession) DBException(org.jkiss.dbeaver.DBException) SQLException(java.sql.SQLException) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) JDBCStatement(org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement) JDBCResultSet(org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet)

Example 62 with JDBCStatement

use of org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement in project dbeaver by serge-rider.

the class SQLServerExecutionContext method refreshDefaults.

@Override
public boolean refreshDefaults(DBRProgressMonitor monitor, boolean useBootstrapSettings) throws DBException {
    // Check default active schema
    try (JDBCSession session = openSession(monitor, DBCExecutionPurpose.META, "Query active schema and database")) {
        String currentDatabase = null;
        try {
            try (JDBCStatement dbStat = session.createStatement()) {
                try (JDBCResultSet dbResult = dbStat.executeQuery("SELECT db_name(), schema_name(), original_login()")) {
                    dbResult.next();
                    currentDatabase = dbResult.getString(1);
                    activeSchemaName = dbResult.getString(2);
                    currentUser = dbResult.getString(3);
                }
            }
        } catch (Throwable e) {
            log.debug("Error getting current user: " + e.getMessage());
        }
        if (CommonUtils.isEmpty(activeSchemaName)) {
            activeSchemaName = SQLServerConstants.DEFAULT_SCHEMA_NAME;
        }
        if (useBootstrapSettings) {
            DBPConnectionBootstrap bootstrap = getBootstrapSettings();
            if (!CommonUtils.isEmpty(bootstrap.getDefaultCatalogName()) && supportsCatalogChange()) {
                setCurrentDatabase(monitor, bootstrap.getDefaultCatalogName());
            }
        /*
                if (!CommonUtils.isEmpty(bootstrap.getDefaultSchemaName()) && supportsSchemaChange()) {
                    setCurrentSchema(monitor, bootstrap.getDefaultSchemaName());
                }
*/
        }
        if (!CommonUtils.isEmpty(currentDatabase) && !CommonUtils.equalObjects(currentDatabase, activeDatabaseName)) {
            activeDatabaseName = currentDatabase;
            return true;
        }
    }
    return false;
}
Also used : JDBCSession(org.jkiss.dbeaver.model.exec.jdbc.JDBCSession) DBPConnectionBootstrap(org.jkiss.dbeaver.model.connection.DBPConnectionBootstrap) JDBCStatement(org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement) JDBCResultSet(org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet)

Example 63 with JDBCStatement

use of org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement in project dbeaver by serge-rider.

the class MySQLCatalog method collectObjectStatistics.

@Override
public void collectObjectStatistics(DBRProgressMonitor monitor, boolean totalSizeOnly, boolean forceRefresh) throws DBException {
    if (hasStatistics && !forceRefresh) {
        return;
    }
    try (JDBCSession session = DBUtils.openMetaSession(monitor, this, "Load table status")) {
        try (JDBCStatement dbStat = session.createStatement()) {
            try (JDBCResultSet dbResult = dbStat.executeQuery("SHOW TABLE STATUS FROM " + DBUtils.getQuotedIdentifier(this))) {
                while (dbResult.next()) {
                    String tableName = dbResult.getString("Name");
                    MySQLTableBase table = tableCache.getObject(monitor, this, tableName);
                    if (table instanceof MySQLTable) {
                        ((MySQLTable) table).fetchAdditionalInfo(dbResult);
                    }
                }
            }
        } catch (SQLException e) {
            throw new DBCException(e, session.getExecutionContext());
        }
    } finally {
        hasStatistics = true;
    }
}
Also used : 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) DBCException(org.jkiss.dbeaver.model.exec.DBCException)

Example 64 with JDBCStatement

use of org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement in project dbeaver by dbeaver.

the class PostgreToolWithStatus method getExecuteStatistics.

@Override
public List<ToolStatus> getExecuteStatistics(OBJECT_TYPE object, SETTINGS settings, DBEPersistAction action, DBCSession session, DBCStatement dbStat) throws DBCException {
    List<ToolStatus> statusList = new ArrayList<>();
    try {
        int warnNum = 0;
        SQLWarning warning = ((JDBCStatement) dbStat).getWarnings();
        while (warning != null) {
            statusList.add(new ToolStatus(object, warning.getMessage()));
            warnNum++;
            warning = warning.getNextWarning();
        }
        if (warnNum == 0) {
            statusList.add(new ToolStatus(object, "Done"));
        }
    } catch (SQLException e) {
    // ignore
    }
    return statusList;
}
Also used : SQLWarning(java.sql.SQLWarning) JDBCStatement(org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList)

Example 65 with JDBCStatement

use of org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement in project dbeaver by dbeaver.

the class PostgreExecutionPlan method explain.

public void explain(DBCSession session) throws DBCException {
    JDBCSession connection = (JDBCSession) session;
    boolean oldAutoCommit = false;
    try {
        oldAutoCommit = connection.getAutoCommit();
        if (oldAutoCommit) {
            connection.setAutoCommit(false);
        }
        try (JDBCStatement dbStat = connection.createStatement()) {
            try (JDBCResultSet dbResult = dbStat.executeQuery(getPlanQueryString())) {
                if (oldQuery) {
                    List<String> planLines = new ArrayList<>();
                    while (dbResult.next()) {
                        String planLine = dbResult.getString(1);
                        if (!CommonUtils.isEmpty(planLine)) {
                            planLines.add(planLine);
                        }
                    }
                    parsePlanText(session, planLines);
                } else {
                    if (dbResult.next()) {
                        SQLXML planXML = dbResult.getSQLXML(1);
                        parsePlanXML(session, planXML);
                    }
                }
            } catch (XMLException e) {
                throw new DBCException("Can't parse plan XML", e);
            }
        }
    } catch (SQLException e) {
        throw new DBCException(e, session.getExecutionContext());
    } finally {
        // Rollback changes because EXPLAIN actually executes query and it could be INSERT/UPDATE
        try {
            connection.rollback();
            if (oldAutoCommit) {
                connection.setAutoCommit(true);
            }
        } catch (SQLException e) {
            log.error("Error closing plan analyser", e);
        }
    }
}
Also used : JDBCSession(org.jkiss.dbeaver.model.exec.jdbc.JDBCSession) SQLXML(java.sql.SQLXML) XMLException(org.jkiss.utils.xml.XMLException) JDBCStatement(org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement) SQLException(java.sql.SQLException) JDBCResultSet(org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet) ArrayList(java.util.ArrayList) DBCException(org.jkiss.dbeaver.model.exec.DBCException)

Aggregations

JDBCStatement (org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement)70 JDBCResultSet (org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet)40 SQLException (java.sql.SQLException)32 JDBCSession (org.jkiss.dbeaver.model.exec.jdbc.JDBCSession)26 DBException (org.jkiss.dbeaver.DBException)24 NotNull (org.jkiss.code.NotNull)18 ArrayList (java.util.ArrayList)16 DBPDataSource (org.jkiss.dbeaver.model.DBPDataSource)12 DBRProgressMonitor (org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)12 DBCException (org.jkiss.dbeaver.model.exec.DBCException)10 SQLWarning (java.sql.SQLWarning)8 AbstractObjectReference (org.jkiss.dbeaver.model.impl.struct.AbstractObjectReference)8 DBSObject (org.jkiss.dbeaver.model.struct.DBSObject)8 JDBCStatementImpl (org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl)6 VoidProgressMonitor (org.jkiss.dbeaver.model.runtime.VoidProgressMonitor)4 BigDecimal (java.math.BigDecimal)2 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)2 SQLXML (java.sql.SQLXML)2 Tree (org.eclipse.swt.widgets.Tree)2 TreeColumn (org.eclipse.swt.widgets.TreeColumn)2