Search in sources :

Example 1 with DBSTable

use of org.jkiss.dbeaver.model.struct.rdb.DBSTable in project dbeaver by serge-rider.

the class ResultSetUtils method bindAttributes.

public static void bindAttributes(DBCSession session, DBCResultSet resultSet, DBDAttributeBindingMeta[] bindings, List<Object[]> rows) throws DBException {
    final DBRProgressMonitor monitor = session.getProgressMonitor();
    final DBPDataSource dataSource = session.getDataSource();
    boolean readMetaData = dataSource.getContainer().getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_READ_METADATA);
    if (!readMetaData) {
        return;
    }
    boolean readReferences = dataSource.getContainer().getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_READ_REFERENCES);
    final Map<DBCEntityMetaData, DBSEntity> entityBindingMap = new IdentityHashMap<>();
    monitor.beginTask("Discover resultset metadata", 3);
    try {
        SQLQuery sqlQuery = null;
        DBSEntity entity = null;
        DBCStatement sourceStatement = resultSet.getSourceStatement();
        if (sourceStatement != null && sourceStatement.getStatementSource() != null) {
            DBCExecutionSource executionSource = sourceStatement.getStatementSource();
            monitor.subTask("Discover owner entity");
            DBSDataContainer dataContainer = executionSource.getDataContainer();
            if (dataContainer instanceof DBSEntity) {
                entity = (DBSEntity) dataContainer;
            }
            DBCEntityMetaData entityMeta = null;
            if (entity == null) {
                // Discover from entity metadata
                Object sourceDescriptor = executionSource.getSourceDescriptor();
                if (sourceDescriptor instanceof SQLQuery) {
                    sqlQuery = (SQLQuery) sourceDescriptor;
                    entityMeta = sqlQuery.getSingleSource();
                }
                if (entityMeta != null) {
                    entity = getEntityFromMetaData(monitor, dataSource, entityMeta);
                    if (entity != null) {
                        entityBindingMap.put(entityMeta, entity);
                    }
                }
            }
        }
        final Map<DBSEntity, DBDRowIdentifier> locatorMap = new IdentityHashMap<>();
        monitor.subTask("Discover attributes");
        for (DBDAttributeBindingMeta binding : bindings) {
            monitor.subTask("Discover attribute '" + binding.getName() + "'");
            DBCAttributeMetaData attrMeta = binding.getMetaAttribute();
            // We got table name and column name
            // To be editable we need this resultset contain set of columns from the same table
            // which construct any unique key
            DBSEntity attrEntity = null;
            final DBCEntityMetaData attrEntityMeta = attrMeta.getEntityMetaData();
            if (attrEntityMeta != null) {
                attrEntity = entityBindingMap.get(attrEntityMeta);
                if (attrEntity == null) {
                    if (entity != null && entity instanceof DBSTable && ((DBSTable) entity).isView()) {
                        // If this is a view then don't try to detect entity for each attribute
                        // MySQL returns source table name instead of view name. That's crazy.
                        attrEntity = entity;
                    } else {
                        attrEntity = getEntityFromMetaData(monitor, dataSource, attrEntityMeta);
                    }
                }
                if (attrEntity != null) {
                    entityBindingMap.put(attrEntityMeta, attrEntity);
                }
            }
            if (attrEntity == null) {
                attrEntity = entity;
            }
            if (attrEntity == null) {
                if (attrEntityMeta != null) {
                    log.debug("Table '" + DBUtils.getSimpleQualifiedName(attrEntityMeta.getCatalogName(), attrEntityMeta.getSchemaName(), attrEntityMeta.getEntityName()) + "' not found in metadata catalog");
                }
            } else {
                DBDPseudoAttribute pseudoAttribute = DBUtils.getPseudoAttribute(attrEntity, attrMeta.getName());
                if (pseudoAttribute != null) {
                    binding.setPseudoAttribute(pseudoAttribute);
                }
                DBSEntityAttribute tableColumn;
                if (binding.getPseudoAttribute() != null) {
                    tableColumn = binding.getPseudoAttribute().createFakeAttribute(attrEntity, attrMeta);
                } else {
                    tableColumn = attrEntity.getAttribute(monitor, attrMeta.getName());
                }
                if (sqlQuery != null) {
                    if (tableColumn != null && tableColumn.getTypeID() != attrMeta.getTypeID()) {
                        // There should be a better solution but for now let's just disable this too smart feature.
                        continue;
                    }
                /*
                        final SQLSelectItem selectItem = sqlQuery.getSelectItem(attrMeta.getName());
                        if (selectItem != null && !selectItem.isPlainColumn()) {
                            // It is not a column.
                            // It maybe an expression, function or anything else
                            continue;
                        }
*/
                }
                if (tableColumn != null && binding.setEntityAttribute(tableColumn)) {
                    // E.g. we fetched strings and found out that we should handle them as LOBs or enums.
                    try {
                        int pos = attrMeta.getOrdinalPosition();
                        for (Object[] row : rows) {
                            row[pos] = binding.getValueHandler().getValueFromObject(session, tableColumn, row[pos], false);
                        }
                    } catch (DBCException e) {
                        log.warn("Error resolving attribute '" + binding.getName() + "' values", e);
                    }
                }
            }
        }
        monitor.worked(1);
        // Init row identifiers
        monitor.subTask("Detect unique identifiers");
        for (DBDAttributeBindingMeta binding : bindings) {
            //monitor.subTask("Find attribute '" + binding.getName() + "' identifier");
            DBSEntityAttribute attr = binding.getEntityAttribute();
            if (attr == null) {
                continue;
            }
            DBSEntity attrEntity = attr.getParentObject();
            if (attrEntity != null) {
                DBDRowIdentifier rowIdentifier = locatorMap.get(attrEntity);
                if (rowIdentifier == null) {
                    DBSEntityReferrer entityIdentifier = getBestIdentifier(monitor, attrEntity, bindings);
                    if (entityIdentifier != null) {
                        rowIdentifier = new DBDRowIdentifier(attrEntity, entityIdentifier);
                        locatorMap.put(attrEntity, rowIdentifier);
                    }
                }
                binding.setRowIdentifier(rowIdentifier);
            }
        }
        monitor.worked(1);
        if (readReferences) {
            monitor.subTask("Late bindings");
            // Read nested bindings
            for (DBDAttributeBinding binding : bindings) {
                binding.lateBinding(session, rows);
            }
        }
        monitor.subTask("Complete metadata load");
        // Reload attributes in row identifiers
        for (DBDRowIdentifier rowIdentifier : locatorMap.values()) {
            rowIdentifier.reloadAttributes(monitor, bindings);
        }
    } finally {
        monitor.done();
    }
}
Also used : DBSTable(org.jkiss.dbeaver.model.struct.rdb.DBSTable) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) SQLQuery(org.jkiss.dbeaver.model.sql.SQLQuery) DBVEntityConstraint(org.jkiss.dbeaver.model.virtual.DBVEntityConstraint) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Example 2 with DBSTable

use of org.jkiss.dbeaver.model.struct.rdb.DBSTable in project dbeaver by serge-rider.

the class ResultSetUtils method getBestIdentifier.

private static DBSEntityReferrer getBestIdentifier(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntity table, DBDAttributeBindingMeta[] bindings) throws DBException {
    List<DBSEntityReferrer> identifiers = new ArrayList<>(2);
    // Check for pseudo attrs (ROWID)
    for (DBDAttributeBindingMeta column : bindings) {
        DBDPseudoAttribute pseudoAttribute = column.getPseudoAttribute();
        if (pseudoAttribute != null && pseudoAttribute.getType() == DBDPseudoAttributeType.ROWID) {
            identifiers.add(new DBDPseudoReferrer(table, column));
            break;
        }
    }
    if (table instanceof DBSTable && ((DBSTable) table).isView()) {
    // Skip physical identifiers for views. There are nothing anyway
    } else if (identifiers.isEmpty()) {
        // Check indexes first.
        if (table instanceof DBSTable) {
            try {
                Collection<? extends DBSTableIndex> indexes = ((DBSTable) table).getIndexes(monitor);
                if (!CommonUtils.isEmpty(indexes)) {
                    for (DBSTableIndex index : indexes) {
                        if (DBUtils.isIdentifierIndex(monitor, index)) {
                            identifiers.add(index);
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                // Indexes are not supported or not available
                // Just skip them
                log.debug(e);
            }
        }
        if (identifiers.isEmpty()) {
            // Check constraints
            Collection<? extends DBSEntityConstraint> constraints = table.getConstraints(monitor);
            if (constraints != null) {
                for (DBSEntityConstraint constraint : constraints) {
                    if (DBUtils.isIdentifierConstraint(monitor, constraint)) {
                        identifiers.add((DBSEntityReferrer) constraint);
                    }
                }
            }
        }
    }
    if (CommonUtils.isEmpty(identifiers)) {
        // No physical identifiers
        // Make new or use existing virtual identifier
        DBVEntity virtualEntity = DBVUtils.findVirtualEntity(table, true);
        identifiers.add(virtualEntity.getBestIdentifier());
    }
    if (!CommonUtils.isEmpty(identifiers)) {
        // Find PK or unique key
        DBSEntityReferrer uniqueId = null;
        for (DBSEntityReferrer referrer : identifiers) {
            if (isGoodReferrer(monitor, bindings, referrer)) {
                if (referrer.getConstraintType() == DBSEntityConstraintType.PRIMARY_KEY) {
                    return referrer;
                } else if (referrer.getConstraintType().isUnique() || (referrer instanceof DBSTableIndex && ((DBSTableIndex) referrer).isUnique())) {
                    uniqueId = referrer;
                }
            }
        }
        return uniqueId;
    }
    return null;
}
Also used : DBSTable(org.jkiss.dbeaver.model.struct.rdb.DBSTable) DBSTableIndex(org.jkiss.dbeaver.model.struct.rdb.DBSTableIndex) DBException(org.jkiss.dbeaver.DBException) DBVEntity(org.jkiss.dbeaver.model.virtual.DBVEntity)

Example 3 with DBSTable

use of org.jkiss.dbeaver.model.struct.rdb.DBSTable in project dbeaver by serge-rider.

the class DiagramCreateWizardPage method createControl.

@Override
public void createControl(Composite parent) {
    Composite placeholder = UIUtils.createPlaceholder(parent, 1);
    Composite configGroup = UIUtils.createControlGroup(placeholder, ERDMessages.wizard_page_diagram_create_group_settings, 2, GridData.FILL_BOTH, 0);
    //$NON-NLS-1$
    final Text projectNameText = UIUtils.createLabelText(configGroup, "Name", null);
    projectNameText.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            diagram.setName(projectNameText.getText());
            updateState();
        }
    });
    Label contentLabel = UIUtils.createControlLabel(configGroup, ERDMessages.wizard_page_diagram_create_label_init_content);
    GridData gd = new GridData(GridData.BEGINNING);
    gd.horizontalSpan = 2;
    contentLabel.setLayoutData(gd);
    final DBNProject rootNode = DBeaverCore.getInstance().getNavigatorModel().getRoot().getProject(DBeaverCore.getInstance().getProjectRegistry().getActiveProject());
    if (rootNode == null) {
        setControl(placeholder);
        return;
    }
    contentTree = new DatabaseNavigatorTree(configGroup, rootNode.getDatabases(), SWT.SINGLE | SWT.CHECK);
    gd = new GridData(GridData.FILL_BOTH);
    gd.horizontalSpan = 2;
    gd.heightHint = 400;
    contentTree.setLayoutData(gd);
    CheckboxTreeViewer viewer = (CheckboxTreeViewer) contentTree.getViewer();
    viewer.setCheckStateProvider(new ICheckStateProvider() {

        @Override
        public boolean isChecked(Object element) {
            return false;
        }

        @Override
        public boolean isGrayed(Object element) {
            if (element instanceof DBNDatabaseNode && !(element instanceof DBNDataSource)) {
                DBSObject object = ((DBNDatabaseNode) element).getObject();
                if (object instanceof DBSTable) {
                    return false;
                }
            }
            return true;
        }
    });
    setControl(placeholder);
}
Also used : DBNProject(org.jkiss.dbeaver.model.navigator.DBNProject) DBSTable(org.jkiss.dbeaver.model.struct.rdb.DBSTable) Composite(org.eclipse.swt.widgets.Composite) ModifyListener(org.eclipse.swt.events.ModifyListener) ICheckStateProvider(org.eclipse.jface.viewers.ICheckStateProvider) DBNDataSource(org.jkiss.dbeaver.model.navigator.DBNDataSource) Label(org.eclipse.swt.widgets.Label) Text(org.eclipse.swt.widgets.Text) DatabaseNavigatorTree(org.jkiss.dbeaver.ui.navigator.database.DatabaseNavigatorTree) CheckboxTreeViewer(org.eclipse.jface.viewers.CheckboxTreeViewer) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) ModifyEvent(org.eclipse.swt.events.ModifyEvent) GridData(org.eclipse.swt.layout.GridData) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) DBNDatabaseNode(org.jkiss.dbeaver.model.navigator.DBNDatabaseNode)

Aggregations

DBSTable (org.jkiss.dbeaver.model.struct.rdb.DBSTable)3 CheckboxTreeViewer (org.eclipse.jface.viewers.CheckboxTreeViewer)1 ICheckStateProvider (org.eclipse.jface.viewers.ICheckStateProvider)1 ModifyEvent (org.eclipse.swt.events.ModifyEvent)1 ModifyListener (org.eclipse.swt.events.ModifyListener)1 GridData (org.eclipse.swt.layout.GridData)1 Composite (org.eclipse.swt.widgets.Composite)1 Label (org.eclipse.swt.widgets.Label)1 Text (org.eclipse.swt.widgets.Text)1 DBException (org.jkiss.dbeaver.DBException)1 DBPDataSource (org.jkiss.dbeaver.model.DBPDataSource)1 DBNDataSource (org.jkiss.dbeaver.model.navigator.DBNDataSource)1 DBNDatabaseNode (org.jkiss.dbeaver.model.navigator.DBNDatabaseNode)1 DBNProject (org.jkiss.dbeaver.model.navigator.DBNProject)1 DBRProgressMonitor (org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)1 SQLQuery (org.jkiss.dbeaver.model.sql.SQLQuery)1 DBSObject (org.jkiss.dbeaver.model.struct.DBSObject)1 DBSTableIndex (org.jkiss.dbeaver.model.struct.rdb.DBSTableIndex)1 DBVEntity (org.jkiss.dbeaver.model.virtual.DBVEntity)1 DBVEntityConstraint (org.jkiss.dbeaver.model.virtual.DBVEntityConstraint)1