use of org.jkiss.dbeaver.model.data.DBDAttributeBinding in project dbeaver by serge-rider.
the class ValidateUniqueKeyUsageDialog method useAllColumns.
private static boolean useAllColumns(ResultSetViewer viewer) {
// Use all columns
final DBDRowIdentifier identifier = viewer.getVirtualEntityIdentifier();
DBVEntityConstraint constraint = (DBVEntityConstraint) identifier.getUniqueKey();
List<DBSEntityAttribute> uniqueColumns = new ArrayList<>();
for (DBDAttributeBinding binding : viewer.getModel().getAttributes()) {
if (binding.getEntityAttribute() != null) {
uniqueColumns.add(binding.getEntityAttribute());
}
}
if (uniqueColumns.isEmpty()) {
DBWorkbench.getPlatformUI().showError("Use All Columns", "No valid columns found for unique key");
return false;
}
constraint.setAttributes(uniqueColumns);
constraint.setUseAllColumns(true);
try {
identifier.reloadAttributes(new VoidProgressMonitor(), viewer.getModel().getAttributes());
} catch (DBException e) {
DBWorkbench.getPlatformUI().showError("Use All Columns", "Can't reload unique columns", e);
return false;
}
return true;
}
use of org.jkiss.dbeaver.model.data.DBDAttributeBinding in project dbeaver by serge-rider.
the class FilterSettingsDialog method createDialogArea.
@Override
protected Control createDialogArea(Composite parent) {
getShell().setText(ResultSetMessages.controls_resultset_filter_title);
getShell().setImage(DBeaverIcons.getImage(UIIcon.FILTER));
Composite composite = (Composite) super.createDialogArea(parent);
TabFolder tabFolder = new TabFolder(composite, SWT.NONE);
tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
TreeColumn criteriaColumn;
{
Composite columnsGroup = UIUtils.createPlaceholder(tabFolder, 1);
FilteredTree filteredTree = new FilteredTree(columnsGroup, SWT.SINGLE | SWT.FULL_SELECTION | SWT.CHECK, new NamedObjectPatternFilter(), true) {
@Override
protected TreeViewer doCreateTreeViewer(Composite parent, int style) {
columnsViewer = new CheckboxTreeViewer(parent, style);
return columnsViewer;
}
};
columnsViewer.setContentProvider(new TreeContentProvider() {
@Override
public Object[] getChildren(Object parentElement) {
final java.util.List<DBDAttributeBinding> nestedBindings = ((DBDAttributeBinding) parentElement).getNestedBindings();
if (nestedBindings == null || nestedBindings.isEmpty()) {
return null;
}
final DBDAttributeBinding[] res = nestedBindings.toArray(new DBDAttributeBinding[0]);
Arrays.sort(res, activeSorter);
return res;
}
@Override
public boolean hasChildren(Object element) {
final java.util.List<DBDAttributeBinding> nestedBindings = ((DBDAttributeBinding) element).getNestedBindings();
return nestedBindings != null && !nestedBindings.isEmpty();
}
});
columnsViewer.setLabelProvider(new ColumnLabelProvider());
columnsViewer.setCheckStateProvider(new CheckStateProvider());
final Tree columnsTree = columnsViewer.getTree();
GridData gd = new GridData(GridData.FILL_BOTH);
gd.heightHint = 300;
columnsTree.setLayoutData(gd);
columnsTree.setHeaderVisible(true);
columnsTree.setLinesVisible(true);
UIUtils.createTreeColumn(columnsTree, SWT.LEFT, ResultSetMessages.controls_resultset_filter_column_name);
UIUtils.createTreeColumn(columnsTree, SWT.LEFT, "#");
UIUtils.createTreeColumn(columnsTree, SWT.LEFT, ResultSetMessages.controls_resultset_filter_column_order);
criteriaColumn = UIUtils.createTreeColumn(columnsTree, SWT.LEFT, ResultSetMessages.controls_resultset_filter_column_criteria);
treeEditor = new FilterSettingsTreeEditor(columnsTree);
columnsViewer.addCheckStateListener(event -> {
DBDAttributeConstraint constraint = getBindingConstraint((DBDAttributeBinding) event.getElement());
constraint.setVisible(event.getChecked());
});
{
ToolBar toolbar = new ToolBar(columnsGroup, SWT.HORIZONTAL | SWT.RIGHT);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalIndent = 3;
toolbar.setLayoutData(gd);
toolbar.setLayout(new FillLayout());
moveTopButton = createToolItem(toolbar, ResultSetMessages.dialog_toolbar_move_to_top, UIIcon.ARROW_TOP, () -> {
int selectionIndex = getSelectionIndex(columnsViewer.getTree());
moveColumns(selectionIndex, 0);
});
moveTopButton.setEnabled(false);
moveUpButton = createToolItem(toolbar, ResultSetMessages.dialog_toolbar_move_up, UIIcon.ARROW_UP, () -> {
int selectionIndex = getSelectionIndex(columnsViewer.getTree());
swapColumns(selectionIndex, selectionIndex - 1);
});
moveUpButton.setEnabled(false);
moveDownButton = createToolItem(toolbar, ResultSetMessages.dialog_toolbar_move_down, UIIcon.ARROW_DOWN, () -> {
int selectionIndex = getSelectionIndex(columnsViewer.getTree());
swapColumns(selectionIndex, selectionIndex + 1);
});
moveDownButton.setEnabled(false);
moveBottomButton = createToolItem(toolbar, ResultSetMessages.dialog_toolbar_move_to_bottom, UIIcon.ARROW_BOTTOM, () -> {
int selectionIndex = getSelectionIndex(columnsViewer.getTree());
moveColumns(selectionIndex, getItemsCount() - 1);
});
moveBottomButton.setEnabled(false);
UIUtils.createToolBarSeparator(toolbar, SWT.VERTICAL);
createToolItem(toolbar, ResultSetMessages.dialog_toolbar_sort, UIIcon.SORT, () -> {
attributes.sort(ALPHA_SORTER);
for (int i = 0; i < attributes.size(); i++) {
final DBDAttributeConstraint constraint = getBindingConstraint(attributes.get(i));
constraint.setVisualPosition(i);
}
columnsViewer.refresh();
});
UIUtils.createToolBarSeparator(toolbar, SWT.VERTICAL);
ToolItem showAllButton = createToolItem(toolbar, ResultSetMessages.dialog_toolbar_show_all, null, () -> {
for (DBDAttributeConstraint constraint : constraints) {
constraint.setVisible(true);
}
columnsViewer.refresh();
});
showAllButton.setImage(UIUtils.getShardImage(ISharedImages.IMG_ETOOL_DEF_PERSPECTIVE));
ToolItem showNoneButton = createToolItem(toolbar, ResultSetMessages.dialog_toolbar_show_none, null, () -> {
for (DBDAttributeConstraint constraint : constraints) {
constraint.setVisible(false);
}
columnsViewer.refresh();
});
showNoneButton.setImage(UIUtils.getShardImage(ISharedImages.IMG_ELCL_REMOVEALL));
createToolItem(toolbar, ResultSetMessages.dialog_toolbar_reset, UIIcon.REFRESH, () -> {
dataFilter.reset();
constraints = new ArrayList<>(dataFilter.getConstraints());
refreshData();
// columnsViewer.refresh();
// $NON-NLS-1$
orderText.setText("");
// $NON-NLS-1$
whereText.setText("");
});
columnsViewer.addSelectionChangedListener(event -> {
int selectionIndex = getSelectionIndex(columnsViewer.getTree());
moveTopButton.setEnabled(selectionIndex > 0);
moveUpButton.setEnabled(selectionIndex > 0);
moveDownButton.setEnabled(selectionIndex >= 0 && selectionIndex < getItemsCount() - 1);
moveBottomButton.setEnabled(selectionIndex >= 0 && selectionIndex < getItemsCount() - 1);
});
}
TabItem libsTab = new TabItem(tabFolder, SWT.NONE);
libsTab.setText(ResultSetMessages.controls_resultset_filter_group_columns);
libsTab.setToolTipText("Set criteria and order for individual column(s)");
libsTab.setControl(columnsGroup);
}
createCustomFilters(tabFolder);
// Fill columns
columnsViewer.setInput(attributes);
refreshData();
// Pack UI
UIUtils.asyncExec(() -> UIUtils.packColumns(columnsViewer.getTree(), true, new float[] { .45f, .05f, .05f, .45f }));
if (criteriaColumn.getWidth() < 200) {
criteriaColumn.setWidth(200);
}
if (!resultSetViewer.supportsDataFilter()) {
Label warnLabel = new Label(composite, SWT.NONE);
warnLabel.setText(ResultSetMessages.controls_resultset_filter_warning_custom_order_disabled);
warnLabel.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_RED));
}
return parent;
}
use of org.jkiss.dbeaver.model.data.DBDAttributeBinding in project dbeaver by serge-rider.
the class ResultSetFilterPanel method getProposals.
@Override
public IContentProposal[] getProposals(String contents, int position) {
if (!viewer.getPreferenceStore().getBoolean(ResultSetPreferences.RESULT_SET_FILTER_AUTO_COMPLETE_PROPOSIAL)) {
return null;
}
SQLSyntaxManager syntaxManager = new SQLSyntaxManager();
DBPDataSource dataSource = viewer.getDataSource();
if (dataSource != null) {
syntaxManager.init(dataSource);
}
SQLWordPartDetector wordDetector = new SQLWordPartDetector(new Document(contents), syntaxManager, position);
String word = wordDetector.getFullWord();
final List<IContentProposal> proposals = new ArrayList<>();
if (CommonUtils.isEmptyTrimmed(word))
word = contents;
word = word.toLowerCase(Locale.ENGLISH);
String attrName = word;
final DBRRunnableWithProgress reader = monitor -> {
DBDAttributeBinding[] attributes = viewer.getModel().getAttributes();
for (DBDAttributeBinding attribute : attributes) {
if (attribute.isCustom()) {
continue;
}
final String name = DBUtils.getUnQuotedIdentifier(attribute.getDataSource(), attribute.getName());
if (CommonUtils.isEmpty(attrName) || name.toLowerCase(Locale.ENGLISH).startsWith(attrName)) {
final String content = DBUtils.getQuotedIdentifier(attribute) + " ";
proposals.add(new ContentProposalExt(content, attribute.getName(), DBInfoUtils.makeObjectDescription(monitor, attribute.getAttribute(), false), content.length(), DBValueFormatting.getObjectImage(attribute)));
}
}
};
SystemJob searchJob = new SystemJob("Extract attribute proposals", reader);
searchJob.schedule();
UIUtils.waitJobCompletion(searchJob);
String[] filterKeywords = { SQLConstants.KEYWORD_AND, SQLConstants.KEYWORD_OR, SQLConstants.KEYWORD_IS, SQLConstants.KEYWORD_NOT, SQLConstants.KEYWORD_NULL };
for (String kw : filterKeywords) {
if (attrName.isEmpty() || kw.startsWith(attrName.toUpperCase())) {
if (dataSource != null) {
kw = dataSource.getSQLDialect().storesUnquotedCase().transform(kw);
}
proposals.add(new ContentProposal(kw + " ", kw + ": SQL expression keyword"));
}
}
return proposals.toArray(new IContentProposal[0]);
}
use of org.jkiss.dbeaver.model.data.DBDAttributeBinding in project dbeaver by serge-rider.
the class DataExporterXLSX method printHeader.
private void printHeader(DBCResultSet resultSet, Worksheet wsh) throws DBException {
boolean hasDescription = false;
if (showDescription) {
// Read bindings to extract column descriptions
boolean bindingsOk = true;
DBDAttributeBindingMeta[] bindings = new DBDAttributeBindingMeta[columns.length];
for (int i = 0; i < columns.length; i++) {
if (columns[i] instanceof DBDAttributeBindingMeta) {
bindings[i] = (DBDAttributeBindingMeta) columns[i];
} else {
bindingsOk = false;
break;
}
}
if (bindingsOk) {
DBSEntity sourceEntity = null;
if (getSite().getSource() instanceof DBSEntity) {
sourceEntity = (DBSEntity) getSite().getSource();
}
DBExecUtils.bindAttributes(resultSet.getSession(), sourceEntity, resultSet, bindings, null);
}
for (DBDAttributeBinding column : columns) {
if (!CommonUtils.isEmpty(column.getDescription())) {
hasDescription = true;
break;
}
}
}
SXSSFSheet sh = (SXSSFSheet) wsh.getSh();
Row row = sh.createRow(wsh.getCurrentRow());
int startCol = rowNumber ? 1 : 0;
sh.trackAllColumnsForAutoSizing();
for (int i = 0, columnsSize = columns.length; i < columnsSize; i++) {
DBDAttributeBinding column = columns[i];
String colName = column.getLabel();
if (CommonUtils.isEmpty(colName)) {
colName = column.getName();
}
Cell cell = row.createCell(i + startCol, CellType.STRING);
cell.setCellValue(colName);
cell.setCellStyle(styleHeader);
}
if (hasDescription) {
wsh.incRow();
Row descRow = sh.createRow(wsh.getCurrentRow());
for (int i = 0, columnsSize = columns.length; i < columnsSize; i++) {
Cell descCell = descRow.createCell(i + startCol, CellType.STRING);
String description = columns[i].getDescription();
if (CommonUtils.isEmpty(description)) {
description = "";
}
descCell.setCellValue(description);
descCell.setCellStyle(styleHeader);
}
}
for (int i = 0, columnsSize = columns.length; i < columnsSize; i++) {
sh.autoSizeColumn(i);
}
wsh.incRow();
try {
sh.flushRows();
} catch (IOException e) {
throw new DBException("Error processing header", e);
}
sh.untrackAllColumnsForAutoSizing();
}
use of org.jkiss.dbeaver.model.data.DBDAttributeBinding in project dbeaver by serge-rider.
the class OpenSpreadsheetHandler method execute.
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IResultSetController resultSet = ResultSetHandlerMain.getActiveResultSet(HandlerUtil.getActivePart(event));
if (resultSet == null) {
DBWorkbench.getPlatformUI().showError("Open Excel", "No active results viewer");
return null;
}
ResultSetDataContainerOptions options = new ResultSetDataContainerOptions();
IResultSetSelection rsSelection = resultSet.getSelection();
List<ResultSetRow> rsSelectedRows = rsSelection.getSelectedRows();
if (rsSelectedRows.size() > 1) {
List<Long> selectedRows = new ArrayList<>();
for (ResultSetRow selectedRow : rsSelectedRows) {
selectedRows.add((long) selectedRow.getRowNumber());
}
List<String> selectedAttributes = new ArrayList<>();
for (DBDAttributeBinding attributeBinding : rsSelection.getSelectedAttributes()) {
selectedAttributes.add(attributeBinding.getName());
}
options.setSelectedRows(selectedRows);
options.setSelectedColumns(selectedAttributes);
}
ResultSetDataContainer dataContainer = new ResultSetDataContainer(resultSet, options);
if (dataContainer.getDataSource() == null) {
DBWorkbench.getPlatformUI().showError("Open Excel", ModelMessages.error_not_connected_to_database);
return null;
}
AbstractJob exportJob = new AbstractJob("Open Excel") {
{
setUser(true);
setSystem(false);
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
try {
File tempDir = DBWorkbench.getPlatform().getTempFolder(monitor, "office-files");
File tempFile = new File(tempDir, CommonUtils.escapeFileName(CommonUtils.truncateString(dataContainer.getName(), 32)) + "." + new SimpleDateFormat("yyyyMMdd-HHmmss").format(System.currentTimeMillis()) + ".xlsx");
tempFile.deleteOnExit();
StreamExporterAbstract exporter = new DataExporterXLSX();
StreamTransferConsumer consumer = new StreamTransferConsumer();
StreamConsumerSettings settings = new StreamConsumerSettings();
settings.setOutputEncodingBOM(false);
settings.setOpenFolderOnFinish(false);
settings.setOutputFolder(tempDir.getAbsolutePath());
settings.setOutputFilePattern(tempFile.getName());
Map<String, Object> properties = DataExporterXLSX.getDefaultProperties();
consumer.initTransfer(dataContainer, settings, new IDataTransferConsumer.TransferParameters(true, false), exporter, properties);
DBDDataFilter dataFilter = resultSet.getModel().getDataFilter();
DatabaseTransferProducer producer = new DatabaseTransferProducer(dataContainer, dataFilter);
DatabaseProducerSettings producerSettings = new DatabaseProducerSettings();
producerSettings.setExtractType(DatabaseProducerSettings.ExtractType.SINGLE_QUERY);
producerSettings.setQueryRowCount(false);
producerSettings.setSelectedRowsOnly(true);
producerSettings.setSelectedColumnsOnly(true);
producer.transferData(monitor, consumer, null, producerSettings, null);
consumer.finishTransfer(monitor, false);
UIUtils.asyncExec(() -> {
if (!UIUtils.launchProgram(tempFile.getAbsolutePath())) {
DBWorkbench.getPlatformUI().showError("Open XLSX", "Can't open XLSX file '" + tempFile.getAbsolutePath() + "'");
}
});
} catch (Exception e) {
DBWorkbench.getPlatformUI().showError("Error opening in Excel", null, e);
}
return Status.OK_STATUS;
}
};
exportJob.schedule();
return null;
}
Aggregations