Search in sources :

Example 1 with DBDValueHandler

use of org.jkiss.dbeaver.model.data.DBDValueHandler in project dbeaver by serge-rider.

the class JDBCTableColumn method getValueEnumeration.

@NotNull
@Override
public Collection<DBDLabelValuePair> getValueEnumeration(@NotNull DBCSession session, @Nullable Object valuePattern, int maxResults) throws DBException {
    DBDValueHandler valueHandler = DBUtils.findValueHandler(session, this);
    StringBuilder query = new StringBuilder();
    query.append("SELECT ").append(DBUtils.getQuotedIdentifier(this)).append(", count(*)");
    // Do not use description columns because they duplicate distinct value
    //        String descColumns = DBVUtils.getDictionaryDescriptionColumns(session.getProgressMonitor(), this);
    //        if (descColumns != null) {
    //            query.append(", ").append(descColumns);
    //        }
    query.append("\nFROM ").append(DBUtils.getObjectFullName(getTable(), DBPEvaluationContext.DML));
    if (valuePattern instanceof String) {
        query.append("\nWHERE ").append(DBUtils.getQuotedIdentifier(this)).append(" LIKE ?");
    }
    query.append("\nGROUP BY ").append(DBUtils.getQuotedIdentifier(this));
    try (DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, false)) {
        if (valuePattern instanceof String) {
            valueHandler.bindValueObject(session, dbStat, this, 0, "%" + valuePattern + "%");
        }
        dbStat.setLimit(0, maxResults);
        if (dbStat.executeStatement()) {
            try (DBCResultSet dbResult = dbStat.openResultSet()) {
                return DBVUtils.readDictionaryRows(session, this, valueHandler, dbResult);
            }
        } else {
            return Collections.emptyList();
        }
    }
}
Also used : DBDValueHandler(org.jkiss.dbeaver.model.data.DBDValueHandler) DBCResultSet(org.jkiss.dbeaver.model.exec.DBCResultSet) DBCStatement(org.jkiss.dbeaver.model.exec.DBCStatement) NotNull(org.jkiss.code.NotNull)

Example 2 with DBDValueHandler

use of org.jkiss.dbeaver.model.data.DBDValueHandler in project dbeaver by serge-rider.

the class JDBCTableConstraint method readKeyEnumeration.

private Collection<DBDLabelValuePair> readKeyEnumeration(DBCSession session, DBSEntityAttribute keyColumn, Object keyPattern, List<DBDAttributeValue> preceedingKeys, int maxResults) throws DBException {
    final TABLE table = getParentObject();
    assert table != null;
    DBDValueHandler keyValueHandler = DBUtils.findValueHandler(session, keyColumn);
    if (keyPattern != null) {
        if (keyPattern instanceof CharSequence) {
            if (((CharSequence) keyPattern).length() > 0) {
                keyPattern = "%" + keyPattern.toString() + "%";
            } else {
                keyPattern = null;
            }
        } else if (keyPattern instanceof Number) {
            // Subtract gap value to see some values before specified
            int gapSize = maxResults / 2;
            if (keyPattern instanceof Integer) {
                keyPattern = (Integer) keyPattern - gapSize;
            } else if (keyPattern instanceof Short) {
                keyPattern = (Short) keyPattern - gapSize;
            } else if (keyPattern instanceof Long) {
                keyPattern = (Long) keyPattern - gapSize;
            } else if (keyPattern instanceof Float) {
                keyPattern = (Float) keyPattern - gapSize;
            } else if (keyPattern instanceof Double) {
                keyPattern = (Double) keyPattern - gapSize;
            } else if (keyPattern instanceof BigInteger) {
                keyPattern = ((BigInteger) keyPattern).subtract(BigInteger.valueOf(gapSize));
            } else if (keyPattern instanceof BigDecimal) {
                keyPattern = ((BigDecimal) keyPattern).subtract(new BigDecimal(gapSize));
            }
        } else {
            // not supported
            keyPattern = null;
        }
    }
    StringBuilder query = new StringBuilder();
    query.append("SELECT ").append(DBUtils.getQuotedIdentifier(keyColumn));
    String descColumns = DBVUtils.getDictionaryDescriptionColumns(session.getProgressMonitor(), keyColumn);
    Collection<DBSEntityAttribute> descAttributes = null;
    if (descColumns != null) {
        descAttributes = DBVEntity.getDescriptionColumns(session.getProgressMonitor(), table, descColumns);
        query.append(", ").append(descColumns);
    }
    query.append(" FROM ").append(DBUtils.getObjectFullName(table, DBPEvaluationContext.DML));
    if (!CommonUtils.isEmpty(preceedingKeys) || keyPattern != null) {
        query.append(" WHERE ");
    }
    boolean hasCond = false;
    // Preceeding keys
    if (preceedingKeys != null && !preceedingKeys.isEmpty()) {
        for (int i = 0; i < preceedingKeys.size(); i++) {
            if (hasCond)
                query.append(" AND ");
            query.append(DBUtils.getQuotedIdentifier(getDataSource(), preceedingKeys.get(i).getAttribute().getName())).append(" = ?");
            hasCond = true;
        }
    }
    if (keyPattern != null) {
        if (hasCond)
            query.append(" AND (");
        query.append(DBUtils.getQuotedIdentifier(keyColumn));
        if (keyPattern instanceof CharSequence) {
            query.append(" LIKE ?");
        } else {
            query.append(" >= ?");
        }
        // Add desc columns conditions
        if (keyPattern instanceof CharSequence && descAttributes != null) {
            for (DBSEntityAttribute descAttr : descAttributes) {
                if (descAttr.getDataKind() == DBPDataKind.STRING) {
                    query.append(" OR ").append(DBUtils.getQuotedIdentifier(descAttr)).append(" LIKE ?");
                }
            }
        }
        if (hasCond)
            query.append(")");
        query.append(" ORDER BY ").append(DBUtils.getQuotedIdentifier(keyColumn));
    }
    try (DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, false)) {
        int paramPos = 0;
        if (preceedingKeys != null && !preceedingKeys.isEmpty()) {
            for (DBDAttributeValue precAttribute : preceedingKeys) {
                DBDValueHandler precValueHandler = DBUtils.findValueHandler(session, precAttribute.getAttribute());
                precValueHandler.bindValueObject(session, dbStat, precAttribute.getAttribute(), paramPos++, precAttribute.getValue());
            }
        }
        if (keyPattern != null) {
            keyValueHandler.bindValueObject(session, dbStat, keyColumn, paramPos++, keyPattern);
        }
        if (keyPattern instanceof CharSequence && descAttributes != null) {
            for (DBSEntityAttribute descAttr : descAttributes) {
                if (descAttr.getDataKind() == DBPDataKind.STRING) {
                    final DBDValueHandler valueHandler = DBUtils.findValueHandler(session, descAttr);
                    valueHandler.bindValueObject(session, dbStat, keyColumn, paramPos++, keyPattern);
                }
            }
        }
        dbStat.setLimit(0, maxResults);
        if (dbStat.executeStatement()) {
            try (DBCResultSet dbResult = dbStat.openResultSet()) {
                return DBVUtils.readDictionaryRows(session, keyColumn, keyValueHandler, dbResult);
            }
        } else {
            return Collections.emptyList();
        }
    }
}
Also used : DBDAttributeValue(org.jkiss.dbeaver.model.data.DBDAttributeValue) DBDValueHandler(org.jkiss.dbeaver.model.data.DBDValueHandler) DBCStatement(org.jkiss.dbeaver.model.exec.DBCStatement) BigDecimal(java.math.BigDecimal) DBSEntityConstraint(org.jkiss.dbeaver.model.struct.DBSEntityConstraint) AbstractTableConstraint(org.jkiss.dbeaver.model.impl.struct.AbstractTableConstraint) BigInteger(java.math.BigInteger) DBSEntityAttribute(org.jkiss.dbeaver.model.struct.DBSEntityAttribute) BigInteger(java.math.BigInteger) DBCResultSet(org.jkiss.dbeaver.model.exec.DBCResultSet)

Example 3 with DBDValueHandler

use of org.jkiss.dbeaver.model.data.DBDValueHandler in project dbeaver by serge-rider.

the class ExecuteBatchImpl method processBatch.

/**
     * Execute batch OR generate batch script.
     * @param session    session
     * @param actions    script actions. If not null then no execution will be done
     * @return execution statistics
     * @throws DBCException
     */
@NotNull
private DBCStatistics processBatch(@NotNull DBCSession session, @Nullable List<DBEPersistAction> actions) throws DBCException {
    DBDValueHandler[] handlers = new DBDValueHandler[attributes.length];
    for (int i = 0; i < attributes.length; i++) {
        if (attributes[i] instanceof DBDAttributeBinding) {
            handlers[i] = ((DBDAttributeBinding) attributes[i]).getValueHandler();
        } else {
            handlers[i] = DBUtils.findValueHandler(session, attributes[i]);
        }
    }
    boolean useBatch = session.getDataSource().getInfo().supportsBatchUpdates() && reuseStatement;
    if (values.size() <= 1) {
        useBatch = false;
    }
    DBCStatistics statistics = new DBCStatistics();
    DBCStatement statement = null;
    try {
        // Here we'll try to reuse prepared statement.
        // It makes a great sense in case of data transfer where we need millions of inserts.
        // We must be aware of nulls because actual insert statements may differ depending on null values.
        // So if row nulls aren't the same as in previous row we need to prepare new statement and restart batch.
        // Quite complicated but works.
        boolean[] prevNulls = new boolean[attributes.length];
        boolean[] nulls = new boolean[attributes.length];
        int statementsInBatch = 0;
        for (Object[] rowValues : values) {
            boolean reuse = reuseStatement;
            if (reuse) {
                for (int i = 0; i < rowValues.length; i++) {
                    nulls[i] = DBUtils.isNullValue(rowValues[i]);
                }
                if (!Arrays.equals(prevNulls, nulls) && statementsInBatch > 0) {
                    reuse = false;
                }
                System.arraycopy(nulls, 0, prevNulls, 0, nulls.length);
                if (!reuse && statementsInBatch > 0) {
                    // Flush batch
                    if (actions == null) {
                        flushBatch(statistics, statement);
                    }
                    statement.close();
                    statement = null;
                    statementsInBatch = 0;
                    reuse = true;
                }
            }
            if (statement == null || !reuse) {
                statement = prepareStatement(session, rowValues);
                statistics.setQueryText(statement.getQueryString());
            }
            try {
                bindStatement(handlers, statement, rowValues);
                if (actions == null) {
                    if (useBatch) {
                        statement.addToBatch();
                        statementsInBatch++;
                    } else {
                        // Execute each row separately
                        long startTime = System.currentTimeMillis();
                        executeStatement(statement);
                        statistics.addExecuteTime(System.currentTimeMillis() - startTime);
                        long rowCount = statement.getUpdateRowCount();
                        if (rowCount > 0) {
                            statistics.addRowsUpdated(rowCount);
                        }
                        // Read keys
                        if (keysReceiver != null) {
                            readKeys(statement.getSession(), statement, keysReceiver);
                        }
                    }
                } else {
                    String queryString;
                    if (statement instanceof DBCParameterizedStatement) {
                        queryString = ((DBCParameterizedStatement) statement).getFormattedQuery();
                    } else {
                        queryString = statement.getQueryString();
                    }
                    actions.add(new SQLDatabasePersistAction("Execute statement", queryString));
                }
            } finally {
                if (!reuse) {
                    statement.close();
                }
            }
        }
        values.clear();
        if (statementsInBatch > 0) {
            if (actions == null) {
                flushBatch(statistics, statement);
            }
            statement.close();
            statement = null;
        }
    } finally {
        if (reuseStatement && statement != null) {
            statement.close();
        }
    }
    return statistics;
}
Also used : DBDValueHandler(org.jkiss.dbeaver.model.data.DBDValueHandler) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) SQLDatabasePersistAction(org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction) NotNull(org.jkiss.code.NotNull)

Example 4 with DBDValueHandler

use of org.jkiss.dbeaver.model.data.DBDValueHandler in project dbeaver by serge-rider.

the class PostgreArrayValueHandler method getValueDisplayString.

@NotNull
@Override
public String getValueDisplayString(@NotNull DBSTypedObject column, Object value, @NotNull DBDDisplayFormat format) {
    DBDCollection collection = (DBDCollection) value;
    if (!DBUtils.isNullValue(value)) {
        DBDValueHandler valueHandler = collection.getComponentValueHandler();
        StringBuilder str = new StringBuilder();
        str.append("{");
        for (int i = 0; i < collection.getItemCount(); i++) {
            if (i > 0) {
                //$NON-NLS-1$
                str.append(',');
            }
            final Object item = collection.getItem(i);
            String itemString;
            if (item instanceof JDBCCollection) {
                // Multi-dimensional arrays case
                itemString = getValueDisplayString(column, item, format);
            } else {
                itemString = valueHandler.getValueDisplayString(collection.getComponentType(), item, DBDDisplayFormat.NATIVE);
            }
            str.append(itemString);
        }
        str.append("}");
        return str.toString();
    }
    return super.getValueDisplayString(column, value, format);
}
Also used : JDBCCollection(org.jkiss.dbeaver.model.impl.jdbc.data.JDBCCollection) DBDCollection(org.jkiss.dbeaver.model.data.DBDCollection) DBDValueHandler(org.jkiss.dbeaver.model.data.DBDValueHandler) DBSTypedObject(org.jkiss.dbeaver.model.struct.DBSTypedObject) NotNull(org.jkiss.code.NotNull)

Example 5 with DBDValueHandler

use of org.jkiss.dbeaver.model.data.DBDValueHandler in project dbeaver by dbeaver.

the class JDBCReference method getReferencedObject.

@Override
public Object getReferencedObject(DBCSession session) throws DBCException {
    if (refObject == null) {
        try {
            session.getProgressMonitor().beginTask("Retrieve references object", 3);
            try {
                session.getProgressMonitor().worked(1);
                Object refValue = value.getObject();
                session.getProgressMonitor().worked(1);
                DBDValueHandler valueHandler = DBUtils.findValueHandler(session, type);
                refObject = valueHandler.getValueFromObject(session, type, refValue, false);
                session.getProgressMonitor().worked(1);
            } finally {
                session.getProgressMonitor().done();
            }
        } catch (SQLException e) {
            throw new DBCException("Can't obtain object reference");
        }
    }
    return refObject;
}
Also used : SQLException(java.sql.SQLException) DBDValueHandler(org.jkiss.dbeaver.model.data.DBDValueHandler) DBCException(org.jkiss.dbeaver.model.exec.DBCException)

Aggregations

DBDValueHandler (org.jkiss.dbeaver.model.data.DBDValueHandler)16 NotNull (org.jkiss.code.NotNull)8 DBDAttributeBinding (org.jkiss.dbeaver.model.data.DBDAttributeBinding)5 DBCResultSet (org.jkiss.dbeaver.model.exec.DBCResultSet)5 DBCStatement (org.jkiss.dbeaver.model.exec.DBCStatement)5 DBDCollection (org.jkiss.dbeaver.model.data.DBDCollection)3 JDBCCollection (org.jkiss.dbeaver.model.impl.jdbc.data.JDBCCollection)3 DBSTypedObject (org.jkiss.dbeaver.model.struct.DBSTypedObject)3 BigDecimal (java.math.BigDecimal)2 BigInteger (java.math.BigInteger)2 SQLException (java.sql.SQLException)2 IWorkbenchPart (org.eclipse.ui.IWorkbenchPart)2 DBCException (org.jkiss.dbeaver.model.exec.DBCException)2 SQLDatabasePersistAction (org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction)2 ArrayList (java.util.ArrayList)1 Collections (java.util.Collections)1 List (java.util.List)1 AbstractHandler (org.eclipse.core.commands.AbstractHandler)1 ExecutionEvent (org.eclipse.core.commands.ExecutionEvent)1 ExecutionException (org.eclipse.core.commands.ExecutionException)1