Search in sources :

Example 76 with DBDAttributeBinding

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

the class GenerateSQLContributor method makeResultSetContributions.

private void makeResultSetContributions(List<IContributionItem> menu, IResultSetSelection rss) {
    final IResultSetController rsv = rss.getController();
    DBSDataContainer dataContainer = rsv.getDataContainer();
    final List<DBDAttributeBinding> visibleAttributes = rsv.getModel().getVisibleAttributes();
    final DBSEntity entity = rsv.getModel().getSingleSource();
    if (dataContainer != null && !visibleAttributes.isEmpty() && entity != null) {
        final Collection<ResultSetRow> selectedRows = rss.getSelectedRows();
        if (!CommonUtils.isEmpty(selectedRows)) {
            menu.add(makeAction("SELECT by Unique Key", new ResultSetAnalysisRunner(dataContainer.getDataSource(), rsv.getModel()) {

                @Override
                public void generateSQL(DBRProgressMonitor monitor, StringBuilder sql, ResultSetModel object) throws DBException {
                    for (ResultSetRow firstRow : selectedRows) {
                        Collection<DBDAttributeBinding> keyAttributes = getKeyAttributes(monitor, object);
                        sql.append("SELECT ");
                        boolean hasAttr = false;
                        for (DBSAttributeBase attr : getValueAttributes(monitor, object, keyAttributes)) {
                            if (hasAttr)
                                sql.append(", ");
                            sql.append(DBUtils.getObjectFullName(attr, DBPEvaluationContext.DML));
                            hasAttr = true;
                        }
                        sql.append("\nFROM ").append(DBUtils.getObjectFullName(entity, DBPEvaluationContext.DML));
                        sql.append("\nWHERE ");
                        hasAttr = false;
                        for (DBDAttributeBinding binding : keyAttributes) {
                            if (hasAttr)
                                sql.append(" AND ");
                            sql.append(DBUtils.getObjectFullName(binding.getAttribute(), DBPEvaluationContext.DML)).append("=");
                            appendAttributeValue(rsv, sql, binding, firstRow);
                            hasAttr = true;
                        }
                        sql.append(";\n");
                    }
                }
            }));
            menu.add(makeAction("INSERT", new ResultSetAnalysisRunner(dataContainer.getDataSource(), rsv.getModel()) {

                @Override
                public void generateSQL(DBRProgressMonitor monitor, StringBuilder sql, ResultSetModel object) throws DBException {
                    for (ResultSetRow firstRow : selectedRows) {
                        Collection<? extends DBSAttributeBase> allAttributes = getAllAttributes(monitor, object);
                        sql.append("INSERT INTO ").append(DBUtils.getObjectFullName(entity, DBPEvaluationContext.DML));
                        sql.append("\n(");
                        boolean hasAttr = false;
                        for (DBSAttributeBase attr : allAttributes) {
                            if (DBUtils.isPseudoAttribute(attr) || DBUtils.isHiddenObject(attr)) {
                                continue;
                            }
                            if (hasAttr)
                                sql.append(", ");
                            sql.append(DBUtils.getObjectFullName(attr, DBPEvaluationContext.DML));
                            hasAttr = true;
                        }
                        sql.append(")\nVALUES(");
                        hasAttr = false;
                        for (DBSAttributeBase attr : allAttributes) {
                            if (DBUtils.isPseudoAttribute(attr) || DBUtils.isHiddenObject(attr)) {
                                continue;
                            }
                            if (hasAttr)
                                sql.append(", ");
                            DBDAttributeBinding binding = rsv.getModel().getAttributeBinding(attr);
                            if (binding == null) {
                                appendDefaultValue(sql, attr);
                            } else {
                                appendAttributeValue(rsv, sql, binding, firstRow);
                            }
                            hasAttr = true;
                        }
                        sql.append(");\n");
                    }
                }
            }));
            menu.add(makeAction("UPDATE", new ResultSetAnalysisRunner(dataContainer.getDataSource(), rsv.getModel()) {

                @Override
                public void generateSQL(DBRProgressMonitor monitor, StringBuilder sql, ResultSetModel object) throws DBException {
                    for (ResultSetRow firstRow : selectedRows) {
                        Collection<DBDAttributeBinding> keyAttributes = getKeyAttributes(monitor, object);
                        Collection<? extends DBSAttributeBase> valueAttributes = getValueAttributes(monitor, object, keyAttributes);
                        sql.append("UPDATE ").append(DBUtils.getObjectFullName(entity, DBPEvaluationContext.DML));
                        sql.append("\nSET ");
                        boolean hasAttr = false;
                        for (DBSAttributeBase attr : valueAttributes) {
                            if (DBUtils.isPseudoAttribute(attr) || DBUtils.isHiddenObject(attr)) {
                                continue;
                            }
                            if (hasAttr)
                                sql.append(", ");
                            sql.append(DBUtils.getObjectFullName(attr, DBPEvaluationContext.DML)).append("=");
                            DBDAttributeBinding binding = rsv.getModel().getAttributeBinding(attr);
                            if (binding == null) {
                                appendDefaultValue(sql, attr);
                            } else {
                                appendAttributeValue(rsv, sql, binding, firstRow);
                            }
                            hasAttr = true;
                        }
                        sql.append("\nWHERE ");
                        hasAttr = false;
                        for (DBDAttributeBinding attr : keyAttributes) {
                            if (hasAttr)
                                sql.append(" AND ");
                            sql.append(DBUtils.getObjectFullName(attr, DBPEvaluationContext.DML)).append("=");
                            appendAttributeValue(rsv, sql, attr, firstRow);
                            hasAttr = true;
                        }
                        sql.append(";\n");
                    }
                }
            }));
            menu.add(makeAction("DELETE by Unique Key", new ResultSetAnalysisRunner(dataContainer.getDataSource(), rsv.getModel()) {

                @Override
                public void generateSQL(DBRProgressMonitor monitor, StringBuilder sql, ResultSetModel object) throws DBException {
                    for (ResultSetRow firstRow : selectedRows) {
                        Collection<DBDAttributeBinding> keyAttributes = getKeyAttributes(monitor, object);
                        sql.append("DELETE FROM ").append(DBUtils.getObjectFullName(entity, DBPEvaluationContext.DML));
                        sql.append("\nWHERE ");
                        boolean hasAttr = false;
                        for (DBDAttributeBinding binding : keyAttributes) {
                            if (hasAttr)
                                sql.append(" AND ");
                            sql.append(DBUtils.getObjectFullName(binding.getAttribute(), DBPEvaluationContext.DML)).append("=");
                            appendAttributeValue(rsv, sql, binding, firstRow);
                            hasAttr = true;
                        }
                        sql.append(";\n");
                    }
                }
            }));
        }
    }
}
Also used : ResultSetModel(org.jkiss.dbeaver.ui.controls.resultset.ResultSetModel) ResultSetRow(org.jkiss.dbeaver.ui.controls.resultset.ResultSetRow) IResultSetController(org.jkiss.dbeaver.ui.controls.resultset.IResultSetController) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Example 77 with DBDAttributeBinding

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

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());
                statistics.addStatementsCount();
            }
            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) {
                            try {
                                readKeys(statement.getSession(), statement, keysReceiver);
                            } catch (Exception e) {
                                log.warn("Error reading auto-generated keys", e);
                            }
                        }
                    }
                } 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 78 with DBDAttributeBinding

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

the class DataExporterJSON method exportRow.

@Override
public void exportRow(DBCSession session, Object[] row) throws DBException, IOException {
    if (rowNum > 0) {
        out.write(",\n");
    }
    rowNum++;
    out.write("\t{\n");
    for (int i = 0; i < row.length; i++) {
        DBDAttributeBinding column = columns.get(i);
        String columnName = column.getLabel();
        if (CommonUtils.isEmpty(columnName)) {
            columnName = column.getName();
        }
        out.write("\t\t\"" + JSONUtils.escapeJsonString(columnName) + "\" : ");
        Object cellValue = row[i];
        if (DBUtils.isNullValue(cellValue)) {
            writeTextCell(null);
        } else if (cellValue instanceof DBDContent) {
            // Content
            // Inline textual content and handle binaries in some special way
            DBDContent content = (DBDContent) cellValue;
            try {
                DBDContentStorage cs = content.getContents(session.getProgressMonitor());
                if (cs != null) {
                    if (ContentUtils.isTextContent(content)) {
                        try (Reader in = cs.getContentReader()) {
                            out.write("\"");
                            writeCellValue(in);
                            out.write("\"");
                        }
                    } else {
                        getSite().writeBinaryData(cs);
                    }
                }
            } finally {
                content.release();
            }
        } else {
            if (cellValue instanceof Number || cellValue instanceof Boolean) {
                out.write(cellValue.toString());
            } else if (cellValue instanceof Date && formatDateISO) {
                writeTextCell(JSONUtils.formatDate((Date) cellValue));
            } else {
                writeTextCell(super.getValueDisplayString(column, cellValue));
            }
        }
        if (i < row.length - 1) {
            out.write(",");
        }
        out.write("\n");
    }
    out.write("\t}");
}
Also used : DBDContent(org.jkiss.dbeaver.model.data.DBDContent) Reader(java.io.Reader) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) DBDContentStorage(org.jkiss.dbeaver.model.data.DBDContentStorage) Date(java.util.Date)

Example 79 with DBDAttributeBinding

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

the class DataExporterMarkdownTable method printHeader.

private void printHeader(boolean separator) {
    if (confluenceFormat)
        writeDelimiter();
    writeDelimiter();
    for (int i = 0, columnsSize = columns.size(); i < columnsSize; i++) {
        DBDAttributeBinding column = columns.get(i);
        String colName = column.getLabel();
        if (CommonUtils.isEmpty(colName)) {
            colName = column.getName();
        }
        if (!separator) {
            writeCellValue(colName);
        } else {
            for (int k = 0; k < colName.length(); k++) {
                out.write('-');
            }
        }
        writeDelimiter();
        if (confluenceFormat)
            writeDelimiter();
    }
    writeRowLimit();
}
Also used : DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding)

Example 80 with DBDAttributeBinding

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

the class DataExporterMarkdownTable method exportRow.

@Override
public void exportRow(DBCSession session, Object[] row) throws DBException, IOException {
    writeDelimiter();
    for (int i = 0; i < row.length && i < columns.size(); i++) {
        DBDAttributeBinding column = columns.get(i);
        if (DBUtils.isNullValue(row[i])) {
            if (!CommonUtils.isEmpty(nullString)) {
                out.write(nullString);
            }
        } else if (row[i] instanceof DBDContent) {
            // Content
            // Inline textual content and handle binaries in some special way
            DBDContent content = (DBDContent) row[i];
            try {
                DBDContentStorage cs = content.getContents(session.getProgressMonitor());
                if (cs == null) {
                    writeCellValue(DBConstants.NULL_VALUE_LABEL);
                } else if (ContentUtils.isTextContent(content)) {
                    writeCellValue(cs.getContentReader());
                } else {
                    getSite().writeBinaryData(cs);
                }
            } finally {
                content.release();
            }
        } else {
            writeCellValue(super.getValueDisplayString(column, row[i]));
        }
        writeDelimiter();
    }
    writeRowLimit();
}
Also used : DBDContent(org.jkiss.dbeaver.model.data.DBDContent) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) DBDContentStorage(org.jkiss.dbeaver.model.data.DBDContentStorage)

Aggregations

DBDAttributeBinding (org.jkiss.dbeaver.model.data.DBDAttributeBinding)147 ArrayList (java.util.ArrayList)32 DBException (org.jkiss.dbeaver.DBException)29 ResultSetRow (org.jkiss.dbeaver.ui.controls.resultset.ResultSetRow)24 DBDContent (org.jkiss.dbeaver.model.data.DBDContent)23 DBDContentStorage (org.jkiss.dbeaver.model.data.DBDContentStorage)23 List (java.util.List)18 DBRProgressMonitor (org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)16 DBSAttributeBase (org.jkiss.dbeaver.model.struct.DBSAttributeBase)14 Reader (java.io.Reader)13 PrintWriter (java.io.PrintWriter)12 GridData (org.eclipse.swt.layout.GridData)12 Nullable (org.jkiss.code.Nullable)12 AbstractJob (org.jkiss.dbeaver.model.runtime.AbstractJob)12 Date (java.util.Date)10 SWT (org.eclipse.swt.SWT)10 NotNull (org.jkiss.code.NotNull)10 DBDDataFilter (org.jkiss.dbeaver.model.data.DBDDataFilter)10 DBPPreferenceStore (org.jkiss.dbeaver.model.preferences.DBPPreferenceStore)10 DBSEntityAttribute (org.jkiss.dbeaver.model.struct.DBSEntityAttribute)10