Search in sources :

Example 51 with DBDAttributeBinding

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

the class GeometryDataUtils method extractGeometryAttributes.

public static List<GeomAttrs> extractGeometryAttributes(IResultSetController controller) {
    List<GeomAttrs> result = new ArrayList<>();
    ResultSetModel model = controller.getModel();
    List<DBDAttributeBinding> attributes = model.getVisibleAttributes();
    List<DBDAttributeBinding> descAttrs = new ArrayList<>();
    for (DBDAttributeBinding attr : attributes) {
        if (attr.getValueHandler().getValueObjectType(attr.getAttribute()) == DBGeometry.class) {
            GeomAttrs geomAttrs = new GeomAttrs(attr, descAttrs);
            result.add(geomAttrs);
        } else {
            descAttrs.add(attr);
        }
    }
    // }
    return result;
}
Also used : ResultSetModel(org.jkiss.dbeaver.ui.controls.resultset.ResultSetModel) ArrayList(java.util.ArrayList) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding)

Example 52 with DBDAttributeBinding

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

the class DataExporterDbUnit method exportRow.

@Override
public void exportRow(DBCSession session, DBCResultSet resultSet, Object[] row) throws DBException, IOException {
    PrintWriter out = getWriter();
    out.write("    <" + tableName);
    for (int i = 0; i < row.length; i++) {
        if (DBUtils.isNullValue(row[i]) && !includeNullValues) {
            continue;
        }
        DBDAttributeBinding column = columns[i];
        String columnName = escapeXmlElementName(column.getName());
        if (columnName != null && upperCaseColumnNames) {
            columnName = columnName.toUpperCase();
        }
        out.write(" " + columnName + "=\"");
        Object columnValue = row[i];
        if (DBUtils.isNullValue(columnValue)) {
            writeTextCell("" + getSite().getProperties().get(PROP_NULL_VALUE_STRING));
        } else if (columnValue instanceof Float || columnValue instanceof Double || columnValue instanceof BigDecimal) {
            int scale = column.getMetaAttribute().getScale() != null && column.getMetaAttribute().getScale() > 0 ? column.getMetaAttribute().getScale() : 1;
            try {
                out.write(String.format(Locale.ROOT, "%." + scale + "f", columnValue));
            } catch (Exception e) {
                out.write(columnValue.toString());
            }
        } else if (columnValue instanceof Boolean) {
            out.write(columnValue.toString());
        } else if (columnValue instanceof Number) {
            out.write(columnValue.toString());
        } else if (columnValue instanceof Timestamp) {
            try {
                int nanoseconds = ((Timestamp) columnValue).getNanos();
                out.write(String.format(Locale.ROOT, "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%2$d", columnValue, nanoseconds));
            } catch (Exception e) {
                out.write(columnValue.toString());
            }
        } else if (columnValue instanceof Time) {
            try {
                out.write(String.format(Locale.ROOT, "%1$tH:%1$tM:%1$tS", columnValue));
            } catch (Exception e) {
                out.write(columnValue.toString());
            }
        } else if (columnValue instanceof Date) {
            try {
                out.write(String.format(Locale.ROOT, "%1$tY-%1$tm-%1$td", columnValue));
            } catch (Exception e) {
                out.write(columnValue.toString());
            }
        } else if (columnValue instanceof DBDContent) {
            // Content
            // Inline textual content and handle binaries in some special way
            DBDContent content = (DBDContent) columnValue;
            try {
                DBDContentStorage cs = content.getContents(session.getProgressMonitor());
                if (cs != null) {
                    if (ContentUtils.isTextContent(content)) {
                        try (Reader reader = cs.getContentReader()) {
                            writeCellValue(reader);
                        }
                    } else {
                        try (final InputStream stream = cs.getContentStream()) {
                            Base64.encode(stream, cs.getContentLength(), getSite().getWriter());
                        }
                    }
                }
            } finally {
                content.release();
            }
        } else {
            writeTextCell(super.getValueDisplayString(column, columnValue));
        }
        out.write("\"");
    }
    out.write("/>" + CommonUtils.getLineSeparator());
}
Also used : InputStream(java.io.InputStream) Reader(java.io.Reader) Time(java.sql.Time) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) IOException(java.io.IOException) DBException(org.jkiss.dbeaver.DBException) Date(java.sql.Date) DBDContentStorage(org.jkiss.dbeaver.model.data.DBDContentStorage) DBDContent(org.jkiss.dbeaver.model.data.DBDContent) DBPNamedObject(org.jkiss.dbeaver.model.DBPNamedObject) PrintWriter(java.io.PrintWriter)

Example 53 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, DBCResultSet resultSet, Object[] row) throws DBException, IOException {
    PrintWriter out = getWriter();
    if (rowNum > 0) {
        out.write(",\n");
    }
    rowNum++;
    if (isJsonDocumentResults(session.getProgressMonitor(), row)) {
        DBDDocument document = (DBDDocument) row[0];
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        document.serializeDocument(session.getProgressMonitor(), buffer, StandardCharsets.UTF_8);
        String jsonText = buffer.toString(StandardCharsets.UTF_8.name());
        out.write(jsonText);
    } else {
        out.write("\t{\n");
        for (int i = 0; i < columns.length; i++) {
            DBDAttributeBinding column = columns[i];
            String columnName = column.getLabel();
            if (CommonUtils.isEmpty(columnName)) {
                columnName = column.getName();
            }
            out.write("\t\t\"" + JSONUtils.escapeJsonString(columnName) + "\" : ");
            Object cellValue = row[column.getOrdinalPosition()];
            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 < columns.length - 1) {
                out.write(",");
            }
            out.write("\n");
        }
        out.write("\t}");
    }
}
Also used : Reader(java.io.Reader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) DBDContentStorage(org.jkiss.dbeaver.model.data.DBDContentStorage) Date(java.util.Date) DBDDocument(org.jkiss.dbeaver.model.data.DBDDocument) DBDContent(org.jkiss.dbeaver.model.data.DBDContent) PrintWriter(java.io.PrintWriter)

Example 54 with DBDAttributeBinding

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

the class DatabaseTransferConsumer method fetchStart.

@Override
public void fetchStart(DBCSession session, DBCResultSet resultSet, long offset, long maxRows) throws DBCException {
    try {
        initExporter(session.getProgressMonitor());
    } catch (DBException e) {
        throw new DBCException("Error initializing exporter", e);
    }
    if (containerMapping == null) {
        throw new DBCException("Internal error: consumer mappings not set");
    }
    AbstractExecutionSource executionSource = new AbstractExecutionSource(containerMapping.getSource(), targetContext, this);
    DBSDataManipulator targetObject = getTargetObject();
    if (!isPreview && offset <= 0 && settings.isTruncateBeforeLoad() && (containerMapping == null || containerMapping.getMappingType() == DatabaseMappingType.existing)) {
        // Truncate target tables
        if ((targetObject.getSupportedFeatures() & DBSDataManipulator.DATA_TRUNCATE) != 0) {
            targetObject.truncateData(targetSession, executionSource);
        } else {
            log.error("Table '" + targetObject.getName() + "' doesn't support truncate operation");
        }
    }
    DBDAttributeBinding[] rsAttributes;
    boolean dynamicTarget = targetContext.getDataSource().getInfo().isDynamicMetadata();
    DBSDataContainer sourceObject = getSourceObject();
    if (dynamicTarget) {
        // Document-based datasource
        rsAttributes = DBUtils.getAttributeBindings(session, sourceObject, resultSet.getMeta());
    } else {
        rsAttributes = DBUtils.makeLeafAttributeBindings(session, sourceObject, resultSet);
    }
    columnMappings = new ColumnMapping[rsAttributes.length];
    sourceBindings = rsAttributes;
    targetAttributes = new ArrayList<>(columnMappings.length);
    for (int i = 0; i < rsAttributes.length; i++) {
        if (isSkipColumn(rsAttributes[i])) {
            continue;
        }
        ColumnMapping columnMapping = new ColumnMapping(rsAttributes[i]);
        if (containerMapping == null) {
            // Map all attributes directly.
            if (targetObject instanceof DBSEntity) {
                try {
                    DBSEntityAttribute attribute = ((DBSEntity) targetObject).getAttribute(session.getProgressMonitor(), columnMapping.sourceAttr.getName());
                    if (attribute != null) {
                        columnMapping.targetAttr = new DatabaseMappingAttribute(null, columnMapping.sourceAttr);
                        columnMapping.targetAttr.setTarget(attribute);
                        columnMapping.targetAttr.setMappingType(DatabaseMappingType.existing);
                    }
                } catch (DBException e) {
                    log.error("Error getting target attribute");
                }
            }
            if (columnMapping.targetAttr == null) {
                throw new DBCException("Can't resolve target attribute for [" + columnMapping.sourceAttr.getName() + "]");
            }
        } else if (sourceObject instanceof DBSDocumentContainer && dynamicTarget) {
            try {
                DBSDocumentContainer docContainer = (DBSDocumentContainer) (targetObject instanceof DBSDocumentContainer ? targetObject : sourceObject);
                DBSEntityAttribute docAttribute = docContainer.getDocumentAttribute(session.getProgressMonitor());
                if (docAttribute != null) {
                    columnMapping.targetAttr = new DatabaseMappingAttribute(containerMapping, columnMapping.sourceAttr);
                    columnMapping.targetAttr.setTarget(docAttribute);
                    columnMapping.targetAttr.setMappingType(DatabaseMappingType.existing);
                }
            } catch (DBException e) {
                throw new DBCException("Error getting document attribute", e);
            }
        } else {
            columnMapping.targetAttr = containerMapping.getAttributeMapping(columnMapping.sourceAttr);
            if (columnMapping.targetAttr == null) {
                throw new DBCException("Can't find target attribute [" + columnMapping.sourceAttr.getName() + "]");
            }
        }
        if (columnMapping.targetAttr.getMappingType() == DatabaseMappingType.skip) {
            continue;
        }
        DBSEntityAttribute targetAttr = columnMapping.targetAttr.getTarget();
        if (targetAttr == null) {
            if (isPreview) {
                targetAttr = new PreviewColumnInfo(null, columnMapping.sourceAttr, columnMapping.targetIndex);
            } else if (columnMapping.targetAttr.getSource() instanceof DBSEntityAttribute) {
                // Use source attr. Some datasource (e.g. document oriented do not have strict set of attributes)
                targetAttr = (DBSEntityAttribute) columnMapping.targetAttr.getSource();
            } else {
                throw new DBCException("Target attribute for [" + columnMapping.sourceAttr.getName() + "] wasn't resolved");
            }
        }
        columnMapping.sourceValueHandler = columnMapping.sourceAttr.getValueHandler();
        columnMapping.targetValueHandler = DBUtils.findValueHandler(targetContext.getDataSource(), targetAttr);
        columnMapping.targetIndex = targetAttributes.size();
        columnMappings[i] = columnMapping;
        targetAttributes.add(targetAttr);
    }
    DBSAttributeBase[] attributes = targetAttributes.toArray(new DBSAttributeBase[0]);
    if (!isPreview) {
        if (targetObject instanceof DBSDataManipulatorExt) {
            ((DBSDataManipulatorExt) targetObject).beforeDataChange(targetSession, DBSManipulationType.INSERT, attributes, executionSource);
        }
        executeBatch = targetObject.insertData(targetSession, attributes, null, executionSource);
    } else {
        previewRows = new ArrayList<>();
        executeBatch = new PreviewBatch();
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) AbstractExecutionSource(org.jkiss.dbeaver.model.impl.AbstractExecutionSource)

Example 55 with DBDAttributeBinding

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

the class DataExporterCSV method printHeader.

private void printHeader() {
    for (int i = 0, columnsSize = columns.length; i < columnsSize; i++) {
        DBDAttributeBinding column = columns[i];
        String colLabel = column.getLabel();
        String colName = column.getName();
        if (CommonUtils.equalObjects(colLabel, colName)) {
            colName = column.getParentObject() == null ? column.getName() : DBUtils.getObjectFullName(column, DBPEvaluationContext.UI);
        } else if (!CommonUtils.isEmpty(colLabel)) {
            // Label has higher priority
            colName = colLabel;
        }
        writeCellValue(colName, true);
        if (i < columnsSize - 1) {
            writeDelimiter();
        }
    }
    writeRowLimit();
}
Also used : DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding)

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