use of org.jkiss.dbeaver.model.DBPDataSource in project dbeaver by dbeaver.
the class ColumnsMappingDialog method createDialogArea.
@Override
protected Composite createDialogArea(Composite parent) {
DBPDataSource targetDataSource = settings.getTargetDataSource(mapping);
boldFont = UIUtils.makeBoldFont(parent.getFont());
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
DBPDataSource sourceDataSource = mapping.getSource().getDataSource();
UIUtils.createLabelText(composite, DTUIMessages.columns_mapping_dialog_composite_label_text_source_container, sourceDataSource == null ? "" : sourceDataSource.getContainer().getName(), SWT.BORDER | SWT.READ_ONLY);
Text sourceEntity = UIUtils.createLabelText(composite, DTUIMessages.columns_mapping_dialog_composite_label_text_source_entity, DBUtils.getObjectFullName(mapping.getSource(), DBPEvaluationContext.UI), SWT.BORDER | SWT.READ_ONLY | SWT.MULTI | SWT.V_SCROLL);
((GridData) sourceEntity.getLayoutData()).widthHint = 600;
((GridData) sourceEntity.getLayoutData()).heightHint = UIUtils.getFontHeight(sourceEntity) * 3;
UIUtils.createLabelText(composite, DTUIMessages.columns_mapping_dialog_composite_label_text_target_container, (targetDataSource == null ? "?" : targetDataSource.getContainer().getName()), SWT.BORDER | SWT.READ_ONLY);
Text targetEntity = UIUtils.createLabelText(composite, DTUIMessages.columns_mapping_dialog_composite_label_text_target_entity, mapping.getTargetName(), SWT.BORDER | SWT.READ_ONLY);
((GridData) targetEntity.getLayoutData()).widthHint = 600;
((GridData) targetEntity.getLayoutData()).heightHint = UIUtils.getFontHeight(sourceEntity) * 3;
mappingViewer = new TableViewer(composite, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.widthHint = 600;
gd.heightHint = 300;
gd.horizontalSpan = 2;
mappingViewer.getTable().setLayoutData(gd);
mappingViewer.getTable().setLinesVisible(true);
mappingViewer.getTable().setHeaderVisible(true);
mappingViewer.setContentProvider(new ListContentProvider());
mappingViewer.getTable().addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.character == SWT.DEL) {
for (TableItem item : mappingViewer.getTable().getSelection()) {
DatabaseMappingAttribute attribute = (DatabaseMappingAttribute) item.getData();
attribute.setMappingType(DatabaseMappingType.skip);
}
mappingViewer.refresh();
} else if (e.character == SWT.SPACE) {
for (TableItem item : mappingViewer.getTable().getSelection()) {
DatabaseMappingAttribute attribute = (DatabaseMappingAttribute) item.getData();
attribute.setMappingType(DatabaseMappingType.existing);
try {
attribute.updateMappingType(new VoidProgressMonitor());
} catch (DBException e1) {
DBWorkbench.getPlatformUI().showError("Bad mapping", "Invalid column mapping", e1);
}
}
mappingViewer.refresh();
}
}
});
{
TableViewerColumn columnSource = new TableViewerColumn(mappingViewer, SWT.LEFT);
columnSource.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
DatabaseMappingAttribute attrMapping = (DatabaseMappingAttribute) cell.getElement();
cell.setText(DBUtils.getObjectFullName(attrMapping.getSource(), DBPEvaluationContext.UI));
if (attrMapping.getIcon() != null) {
cell.setImage(DBeaverIcons.getImage(attrMapping.getIcon()));
}
}
});
columnSource.getColumn().setText(DTUIMessages.columns_mapping_dialog_column_source_text);
columnSource.getColumn().setWidth(170);
}
{
TableViewerColumn columnSourceType = new TableViewerColumn(mappingViewer, SWT.LEFT);
columnSourceType.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
cell.setText(((DatabaseMappingAttribute) cell.getElement()).getSourceType());
}
});
columnSourceType.getColumn().setText(DTUIMessages.columns_mapping_dialog_column_source_type_text);
columnSourceType.getColumn().setWidth(100);
}
{
TableViewerColumn columnTarget = new TableViewerColumn(mappingViewer, SWT.LEFT);
columnTarget.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
DatabaseMappingAttribute mapping = (DatabaseMappingAttribute) cell.getElement();
cell.setText(mapping.getTargetName());
if (mapping.getMappingType() == DatabaseMappingType.unspecified) {
cell.setBackground(UIUtils.getSharedTextColors().getColor(SharedTextColors.COLOR_WARNING));
} else {
cell.setBackground(null);
}
cell.setFont(boldFont);
}
});
columnTarget.getColumn().setText(DTUIMessages.columns_mapping_dialog_column_target_text);
columnTarget.getColumn().setWidth(170);
columnTarget.setEditingSupport(new EditingSupport(mappingViewer) {
@Override
protected CellEditor getCellEditor(Object element) {
try {
java.util.List<String> items = new ArrayList<>();
DatabaseMappingAttribute mapping = (DatabaseMappingAttribute) element;
if (mapping.getParent().getMappingType() == DatabaseMappingType.existing && mapping.getParent().getTarget() instanceof DBSEntity) {
DBSEntity parentEntity = (DBSEntity) mapping.getParent().getTarget();
for (DBSEntityAttribute attr : CommonUtils.safeCollection(parentEntity.getAttributes(new VoidProgressMonitor()))) {
items.add(attr.getName());
}
}
items.add(DatabaseMappingAttribute.TARGET_NAME_SKIP);
return new CustomComboBoxCellEditor(mappingViewer, mappingViewer.getTable(), items.toArray(new String[0]), SWT.DROP_DOWN);
} catch (DBException e) {
DBWorkbench.getPlatformUI().showError("Bad value", "Wrong target column", e);
return null;
}
}
@Override
protected boolean canEdit(Object element) {
return true;
}
@Override
protected Object getValue(Object element) {
return ((DatabaseMappingAttribute) element).getTargetName();
}
@Override
protected void setValue(Object element, Object value) {
try {
String name = CommonUtils.toString(value);
DatabaseMappingAttribute attrMapping = (DatabaseMappingAttribute) element;
if (DatabaseMappingAttribute.TARGET_NAME_SKIP.equals(name)) {
attrMapping.setMappingType(DatabaseMappingType.skip);
} else {
if (attrMapping.getParent().getMappingType() == DatabaseMappingType.existing && attrMapping.getParent().getTarget() instanceof DBSEntity) {
DBSEntity parentEntity = (DBSEntity) attrMapping.getParent().getTarget();
for (DBSEntityAttribute attr : CommonUtils.safeCollection(parentEntity.getAttributes(new VoidProgressMonitor()))) {
if (name.equalsIgnoreCase(attr.getName())) {
attrMapping.setTarget(attr);
attrMapping.setMappingType(DatabaseMappingType.existing);
attrMapping.setTargetName(name);
return;
}
}
}
attrMapping.setMappingType(DatabaseMappingType.create);
attrMapping.setTargetName(name);
}
} catch (DBException e) {
DBWorkbench.getPlatformUI().showError("Bad value", "Wrong target", e);
} finally {
mappingViewer.refresh();
}
}
});
}
{
TableViewerColumn columnTargetType = new TableViewerColumn(mappingViewer, SWT.LEFT);
columnTargetType.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
DatabaseMappingAttribute attrMapping = (DatabaseMappingAttribute) cell.getElement();
DBPDataSource dataSource = settings.getTargetDataSource(attrMapping);
cell.setText(attrMapping.getTargetType(dataSource, true));
cell.setFont(boldFont);
}
});
columnTargetType.getColumn().setText(DTUIMessages.columns_mapping_dialog_column_target_type_text);
columnTargetType.getColumn().setWidth(100);
columnTargetType.setEditingSupport(new EditingSupport(mappingViewer) {
@Override
protected CellEditor getCellEditor(Object element) {
DatabaseMappingAttribute attrMapping = (DatabaseMappingAttribute) element;
Set<String> types = new TreeSet<>();
DBPDataSource dataSource = settings.getTargetDataSource(attrMapping);
if (dataSource instanceof DBPDataTypeProvider) {
for (DBSDataType type : ((DBPDataTypeProvider) dataSource).getLocalDataTypes()) {
types.add(type.getName());
}
}
types.add(attrMapping.getTargetType(dataSource, true));
return new CustomComboBoxCellEditor(mappingViewer, mappingViewer.getTable(), types.toArray(new String[0]), SWT.BORDER);
}
@Override
protected boolean canEdit(Object element) {
return true;
}
@Override
protected Object getValue(Object element) {
DatabaseMappingAttribute attrMapping = (DatabaseMappingAttribute) element;
return attrMapping.getTargetType(settings.getTargetDataSource(attrMapping), true);
}
@Override
protected void setValue(Object element, Object value) {
DatabaseMappingAttribute attrMapping = (DatabaseMappingAttribute) element;
attrMapping.setTargetType(CommonUtils.toString(value));
mappingViewer.refresh(element);
}
});
}
{
TableViewerColumn columnType = new TableViewerColumn(mappingViewer, SWT.LEFT);
columnType.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
DatabaseMappingAttribute mapping = (DatabaseMappingAttribute) cell.getElement();
String text = "";
switch(mapping.getMappingType()) {
case unspecified:
text = "?";
break;
case existing:
text = DTUIMessages.columns_mapping_dialog_cell_text_existing;
break;
case create:
text = DTUIMessages.columns_mapping_dialog_cell_text_new;
break;
case skip:
text = DTUIMessages.columns_mapping_dialog_cell_text_skip;
break;
}
cell.setText(text);
}
});
columnType.getColumn().setText(DTUIMessages.columns_mapping_dialog_column_type_text_mapping);
columnType.getColumn().setWidth(60);
}
mappingViewer.setInput(attributeMappings);
return parent;
}
use of org.jkiss.dbeaver.model.DBPDataSource in project dbeaver by dbeaver.
the class DBeaverUI method showDatabaseError.
private static UserResponse showDatabaseError(String message, DBException error) {
DBPDataSource dataSource = error.getDataSource();
DBPErrorAssistant.ErrorType errorType = dataSource == null ? DBPErrorAssistant.ErrorType.NORMAL : DBExecUtils.discoverErrorType(dataSource, error);
switch(errorType) {
case CONNECTION_LOST:
if (dataSource.getContainer().getDataSource() == null) {
// Error during datasource init
return null;
}
DataSourceInvalidateHandler.showConnectionLostDialog(null, message, error);
return UserResponse.OK;
case DRIVER_CLASS_MISSING:
DriverEditDialog.showBadConfigDialog(null, message, error);
return UserResponse.OK;
}
return null;
}
use of org.jkiss.dbeaver.model.DBPDataSource in project dbeaver by dbeaver.
the class ConnectionPageInitialization method activatePage.
@Override
public void activatePage() {
if (dataSourceDescriptor != null) {
if (!activated) {
// Get settings from data source descriptor
final DBPConnectionConfiguration conConfig = dataSourceDescriptor.getConnectionConfiguration();
autocommit.setSelection(dataSourceDescriptor.isDefaultAutoCommit());
isolationLevel.add("");
DataSourceDescriptor originalDataSource = getWizard().getOriginalDataSource();
if (originalDataSource != null && originalDataSource.isConnected()) {
DBPDataSource dataSource = originalDataSource.getDataSource();
loadDatabaseSettings(dataSource);
}
defaultCatalog.setText(CommonUtils.notEmpty(conConfig.getBootstrap().getDefaultCatalogName()));
defaultSchema.setText(CommonUtils.notEmpty(conConfig.getBootstrap().getDefaultSchemaName()));
keepAliveInterval.setSelection(conConfig.getKeepAliveInterval());
activated = true;
}
} else {
// Default settings
isolationLevel.setEnabled(false);
defaultCatalog.setText("");
defaultSchema.setText("");
}
}
use of org.jkiss.dbeaver.model.DBPDataSource in project dbeaver by dbeaver.
the class DatabaseTransferUtils method generateTargetTableDDL.
public static DBEPersistAction[] generateTargetTableDDL(DBRProgressMonitor monitor, DBCExecutionContext executionContext, DBSObjectContainer schema, DatabaseMappingContainer containerMapping) throws DBException {
if (containerMapping.getMappingType() == DatabaseMappingType.skip) {
return new DBEPersistAction[0];
}
monitor.subTask("Create table '" + containerMapping.getTargetName() + "'");
if (USE_STRUCT_DDL) {
DBEPersistAction[] ddl = generateStructTableDDL(monitor, executionContext, schema, containerMapping);
if (ddl != null) {
return ddl;
}
}
// Struct doesn't work (no proper object managers?)
// Try plain SQL mode
DBPDataSource dataSource = executionContext.getDataSource();
StringBuilder sql = new StringBuilder(500);
String tableName = DBObjectNameCaseTransformer.transformName(dataSource, containerMapping.getTargetName());
containerMapping.setTargetName(tableName);
List<DBEPersistAction> actions = new ArrayList<>();
if (containerMapping.getMappingType() == DatabaseMappingType.create) {
sql.append("CREATE TABLE ");
if (schema instanceof DBSSchema || schema instanceof DBSCatalog) {
sql.append(DBUtils.getQuotedIdentifier(schema));
sql.append(dataSource.getSQLDialect().getCatalogSeparator());
}
sql.append(DBUtils.getQuotedIdentifier(dataSource, tableName)).append("(\n");
Map<DBSAttributeBase, DatabaseMappingAttribute> mappedAttrs = new HashMap<>();
for (DatabaseMappingAttribute attr : containerMapping.getAttributeMappings(monitor)) {
if (attr.getMappingType() != DatabaseMappingType.create) {
continue;
}
if (!mappedAttrs.isEmpty())
sql.append(",\n");
sql.append("\t");
appendAttributeClause(dataSource, sql, attr);
mappedAttrs.put(attr.getSource(), attr);
}
if (containerMapping.getSource() instanceof DBSEntity) {
// Make primary key
Collection<? extends DBSEntityAttribute> identifier = DBUtils.getBestTableIdentifier(monitor, (DBSEntity) containerMapping.getSource());
if (!CommonUtils.isEmpty(identifier)) {
boolean idMapped = true;
for (DBSEntityAttribute idAttr : identifier) {
if (!mappedAttrs.containsKey(idAttr)) {
idMapped = false;
break;
}
}
if (idMapped) {
sql.append(",\n\tPRIMARY KEY (");
boolean hasAttr = false;
for (DBSEntityAttribute idAttr : identifier) {
DatabaseMappingAttribute mappedAttr = mappedAttrs.get(idAttr);
if (hasAttr)
sql.append(",");
sql.append(DBUtils.getQuotedIdentifier(dataSource, mappedAttr.getTargetName()));
hasAttr = true;
}
sql.append(")\n");
}
}
}
sql.append(")");
actions.add(new SQLDatabasePersistAction("Table DDL", sql.toString()));
} else {
for (DatabaseMappingAttribute attr : containerMapping.getAttributeMappings(monitor)) {
if (attr.getMappingType() == DatabaseMappingType.create) {
actions.add(generateTargetAttributeDDL(dataSource, attr));
}
}
}
return actions.toArray(new DBEPersistAction[0]);
}
use of org.jkiss.dbeaver.model.DBPDataSource in project dbeaver by dbeaver.
the class DBExecUtils method bindAttributes.
public static void bindAttributes(@NotNull DBCSession session, @Nullable DBSEntity sourceEntity, @Nullable DBCResultSet resultSet, @NotNull DBDAttributeBinding[] bindings, @Nullable List<Object[]> rows) throws DBException {
final DBRProgressMonitor monitor = session.getProgressMonitor();
final DBPDataSource dataSource = session.getDataSource();
boolean readMetaData = dataSource.getContainer().getPreferenceStore().getBoolean(ModelPreferences.RESULT_SET_READ_METADATA);
if (!readMetaData && sourceEntity == null) {
// Do not read metadata if source entity is not known
return;
}
boolean readReferences = dataSource.getContainer().getPreferenceStore().getBoolean(ModelPreferences.RESULT_SET_READ_REFERENCES);
final Map<DBCEntityMetaData, DBSEntity> entityBindingMap = new IdentityHashMap<>();
monitor.beginTask("Discover resultset metadata", 3);
try {
SQLQuery sqlQuery = null;
DBSEntity entity = null;
if (sourceEntity != null) {
entity = sourceEntity;
} else if (resultSet != 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 = DBUtils.getEntityFromMetaData(monitor, session.getExecutionContext(), entityMeta);
if (entity != null) {
entityBindingMap.put(entityMeta, entity);
}
}
}
}
}
final Map<DBSEntity, DBDRowIdentifier> locatorMap = new IdentityHashMap<>();
monitor.subTask("Discover attributes");
for (DBDAttributeBinding binding : bindings) {
monitor.subTask("Discover attribute '" + binding.getName() + "'");
DBCAttributeMetaData attrMeta = binding.getMetaAttribute();
if (attrMeta == null) {
continue;
}
// 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 = DBUtils.getEntityFromMetaData(monitor, session.getExecutionContext(), 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 if (binding instanceof DBDAttributeBindingMeta) {
DBDAttributeBindingMeta bindingMeta = (DBDAttributeBindingMeta) binding;
DBDPseudoAttribute pseudoAttribute = DBUtils.getPseudoAttribute(attrEntity, attrMeta.getName());
if (pseudoAttribute != null) {
bindingMeta.setPseudoAttribute(pseudoAttribute);
}
DBSEntityAttribute tableColumn;
if (bindingMeta.getPseudoAttribute() != null) {
tableColumn = bindingMeta.getPseudoAttribute().createFakeAttribute(attrEntity, attrMeta);
} else {
tableColumn = attrEntity.getAttribute(monitor, attrMeta.getName());
}
if (tableColumn != null && // - Database doesn't support column name collisions (default)
(sourceEntity != null || bindingMeta.getMetaAttribute().getEntityMetaData() != null || !bindingMeta.getDataSource().getInfo().needsTableMetaForColumnResolution()) && bindingMeta.setEntityAttribute(tableColumn, ((sqlQuery == null || tableColumn.getTypeID() != attrMeta.getTypeID()) && rows != null))) {
// 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, 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 (DBDAttributeBinding binding : bindings) {
if (!(binding instanceof DBDAttributeBindingMeta)) {
continue;
}
DBDAttributeBindingMeta bindingMeta = (DBDAttributeBindingMeta) binding;
// monitor.subTask("Find attribute '" + binding.getName() + "' identifier");
DBSEntityAttribute attr = binding.getEntityAttribute();
if (attr == null) {
bindingMeta.setRowIdentifierStatus("No corresponding table column");
continue;
}
DBSEntity attrEntity = attr.getParentObject();
if (attrEntity != null) {
DBDRowIdentifier rowIdentifier = locatorMap.get(attrEntity);
if (rowIdentifier == null) {
DBSEntityConstraint entityIdentifier = getBestIdentifier(monitor, attrEntity, bindings, readMetaData);
if (entityIdentifier != null) {
rowIdentifier = new DBDRowIdentifier(attrEntity, entityIdentifier);
locatorMap.put(attrEntity, rowIdentifier);
} else {
bindingMeta.setRowIdentifierStatus("Cannot determine unique row identifier");
}
}
bindingMeta.setRowIdentifier(rowIdentifier);
}
}
monitor.worked(1);
}
if (readMetaData && readReferences && rows != null) {
monitor.subTask("Read results metadata");
// Read nested bindings
for (DBDAttributeBinding binding : bindings) {
binding.lateBinding(session, rows);
}
}
/*
monitor.subTask("Load transformers");
// Load transformers
for (DBDAttributeBinding binding : bindings) {
binding.loadTransformers(session, rows);
}
*/
monitor.subTask("Complete metadata load");
// Reload attributes in row identifiers
for (DBDRowIdentifier rowIdentifier : locatorMap.values()) {
rowIdentifier.reloadAttributes(monitor, bindings);
}
} finally {
monitor.done();
}
}
Aggregations