diff options
Diffstat (limited to 'wizards/com/sun/star/wizards/db')
-rw-r--r-- | wizards/com/sun/star/wizards/db/BlindtextCreator.java | 113 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/ColumnPropertySet.java | 213 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/CommandMetaData.java | 772 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/CommandName.java | 267 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/DBMetaData.java | 1123 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/DatabaseObjectWizard.java | 75 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/FieldColumn.java | 471 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/MANIFEST.MF | 0 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/QueryMetaData.java | 293 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/RecordParser.java | 306 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/RelationController.java | 161 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/SQLQueryComposer.java | 421 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/TableDescriptor.java | 861 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/TypeInspector.java | 465 |
14 files changed, 5541 insertions, 0 deletions
diff --git a/wizards/com/sun/star/wizards/db/BlindtextCreator.java b/wizards/com/sun/star/wizards/db/BlindtextCreator.java new file mode 100644 index 000000000000..b52381def054 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/BlindtextCreator.java @@ -0,0 +1,113 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.wizards.db; + +import com.sun.star.wizards.common.JavaTools; + +/** + * + * @author bc93774 + */ +public class BlindtextCreator +{ + + public static final String BlindText = + "Ut wisi enim ad minim veniam, quis nostrud exerci tation " + "ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor " + "in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at " + "vero et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore " + "te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy " + "nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, " + "quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. " + "Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum " + "dolore eu feugiat nulla facilisis at vero et accumsan et iusto odio dignissim qui blandit praesent " + "luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis " + "eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum."; + + public static String adjustBlindTextlength(String FieldTitle, int FieldWidth, boolean bIsCurLandscape, boolean bIsGroupTable, String[] _RecordFieldNames) + { + String BlindTextString = ""; + if (bIsGroupTable) + { + return getBlindTextString(FieldTitle, FieldWidth, FieldWidth); + } + int MaxFieldCount = getMaxFieldCount(bIsCurLandscape); + if (_RecordFieldNames.length <= 2 * MaxFieldCount) + { + if (_RecordFieldNames.length <= MaxFieldCount) + { + BlindTextString = getBlindTextString(FieldTitle, FieldWidth, FieldWidth); + } + else + { + BlindTextString = getBlindTextString(FieldTitle, FieldWidth, (int) (0.5 * FieldWidth)); + } + } + else + { + BlindTextString = getBlindTextString(FieldTitle, FieldWidth, (int) 1.1 * FieldTitle.length()); + } + return BlindTextString; + } + + public static String getBlindTextString(String FieldTitle, int FieldWidth, int MaxWidth) + { + String[] BlindTextArray = JavaTools.ArrayoutofString(BlindText, " "); + String PartBlindText = BlindTextArray[0]; + String NewPartBlindText; + int MaxHeaderWidth; + int iWidth = FieldWidth; + int Titlelength = (int) 1.1 * FieldTitle.length(); // We assume that the TableHeading is bold + + if (Titlelength > PartBlindText.length()) + { + MaxHeaderWidth = Titlelength; + } + else + { + MaxHeaderWidth = PartBlindText.length(); + } + if (MaxHeaderWidth > MaxWidth) + { + MaxWidth = MaxHeaderWidth; + } + int i = 1; + do + { + NewPartBlindText = PartBlindText + " " + BlindTextArray[i]; + if (NewPartBlindText.length() < MaxWidth) + { + PartBlindText = NewPartBlindText; + i += 1; + } + } + while (NewPartBlindText.length() < MaxWidth); + return PartBlindText; + } + + private static int getMaxFieldCount(boolean bIsCurLandscape) + { + if (bIsCurLandscape == true) + { + return 5; + } + else + { + return 3; + } + } +} diff --git a/wizards/com/sun/star/wizards/db/ColumnPropertySet.java b/wizards/com/sun/star/wizards/db/ColumnPropertySet.java new file mode 100644 index 000000000000..204ba2328321 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/ColumnPropertySet.java @@ -0,0 +1,213 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.wizards.db; + +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.sdbc.DataType; +import com.sun.star.wizards.common.Properties; +// import com.sun.star.wizards.db.TypeInspector; + +public class ColumnPropertySet +{ + + TypeInspector oTypeInspector; + public XPropertySet xPropertySet; + private int nType; + private String sTypeName = ""; + + public ColumnPropertySet(TypeInspector _oTypeInspector, XPropertySet _xPropertySet) + { + xPropertySet = _xPropertySet; + oTypeInspector = _oTypeInspector; + } + + private PropertyValue[] propertySet2PropertyValueArray(XPropertySet _xNewPropertySet) throws com.sun.star.uno.Exception + { + Property[] props = _xNewPropertySet.getPropertySetInfo().getProperties(); + PropertyValue[] ret = new PropertyValue[props.length]; + for (int i = 0; i < props.length; i++) + { + PropertyValue val = new PropertyValue(); + val.Name = props[i].Name; + val.Value = _xNewPropertySet.getPropertyValue(val.Name); + ret[i] = val; + } + return ret; + } + + private void assignPropertyValues(String _sNewName, PropertyValue[] _aNewColPropertyValues, boolean _bsetDefaultProperties) + { + try + { + nType = ((Integer) Properties.getPropertyValue(_aNewColPropertyValues, "Type")).intValue(); + nType = oTypeInspector.convertDataType(nType); + if (Properties.hasPropertyValue(_aNewColPropertyValues, "TypeName")) + { + sTypeName = (String) Properties.getPropertyValue(_aNewColPropertyValues, "TypeName"); + } + Integer precision = null; + if (Properties.hasPropertyValue(_aNewColPropertyValues, "Precision")) + { + precision = (Integer) Properties.getPropertyValue(_aNewColPropertyValues, "Precision"); + + } + if ((nType == DataType.VARCHAR) && (precision == null || precision.intValue() == 0)) + { + precision = new Integer(50); + } + if (precision != null) + { + xPropertySet.setPropertyValue("Precision", precision); + } + setType(nType, sTypeName, precision); + for (int i = 0; i < _aNewColPropertyValues.length; i++) + { + String sPropName = _aNewColPropertyValues[i].Name; + if (_sNewName != null && sPropName.equals("Name")) + { + xPropertySet.setPropertyValue("Name", _sNewName); + } + else if (sPropName.equals("Precision")) + { + // do nothing, see above + } + else if ((!sPropName.equals("Type")) && (!sPropName.equals("TypeName"))) + { + Object oColValue = _aNewColPropertyValues[i].Value; + assignPropertyValue(sPropName, oColValue); + } + } + if (_bsetDefaultProperties) + { + assignPropertyValue("IsNullable", new Integer(oTypeInspector.isNullable(xPropertySet))); + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + + } + + public void assignPropertyValues(PropertyValue[] _aNewColPropertyValues, boolean _bsetDefaultProperties) + { + assignPropertyValues(null /* dont change the name */, _aNewColPropertyValues, _bsetDefaultProperties); + } + + public void assignNewPropertySet(String _sNewName, XPropertySet _xNewPropertySet) + { + try + { + assignPropertyValues( + _sNewName, propertySet2PropertyValueArray(_xNewPropertySet), false /*setDefaultProperties*/); + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + } + + private int getPrecision() + { + try + { + return ((Integer) xPropertySet.getPropertyValue("Precision")).intValue(); + } + catch (Exception e) + { + e.printStackTrace(System.out); + return 0; + } + } + + private void setType(int _nType, String _sTypeName, Integer precision) + { + if (_sTypeName.equals("")) + { + sTypeName = oTypeInspector.getDefaultTypeName(nType, precision); + } + else + { + sTypeName = _sTypeName; + } + nType = oTypeInspector.getDataType(sTypeName); + assignPropertyValue("Type", new Integer(nType)); + assignPropertyValue("TypeName", sTypeName); + } + + private void assignPropertyValue(String _spropname, Object _oValue) + { + try + { + if (_spropname.equals("Type")) + { + nType = ((Integer) _oValue).intValue(); + xPropertySet.setPropertyValue("Type", new Integer(nType)); + } + else if (_spropname.equals("Name")) + { + String sName = (String) _oValue; + if (!sName.equals("")) + { + xPropertySet.setPropertyValue("Name", sName); + } + } + else if (_spropname.equals("Scale")) + { + int nScale = ((Integer) _oValue).intValue(); + nScale = oTypeInspector.getScale(xPropertySet); + xPropertySet.setPropertyValue("Scale", new Integer(nScale)); + } + else if (_spropname.equals("IsNullable")) + { + int nNullability = ((Integer) _oValue).intValue(); + nNullability = oTypeInspector.getNullability(xPropertySet, nNullability); + xPropertySet.setPropertyValue("IsNullable", new Integer(nNullability)); + } + else if (_spropname.equals("TypeName")) + { + String sTypeName = (String) _oValue; + xPropertySet.setPropertyValue("TypeName", sTypeName); + } + else + { + xPropertySet.setPropertyValue(_spropname, _oValue); + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + } + + private int getType() + { + return nType; + } +} diff --git a/wizards/com/sun/star/wizards/db/CommandMetaData.java b/wizards/com/sun/star/wizards/db/CommandMetaData.java new file mode 100644 index 000000000000..ad54020e8645 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/CommandMetaData.java @@ -0,0 +1,772 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.wizards.db; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbcx.KeyType; +import com.sun.star.sdbcx.XColumnsSupplier; +import com.sun.star.sdbcx.XKeysSupplier; +import com.sun.star.uno.AnyConverter; +import com.sun.star.awt.VclWindowPeerAttribute; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.Locale; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XIndexAccess; +import com.sun.star.container.XNameAccess; +import com.sun.star.embed.EntryInitModes; +import com.sun.star.wizards.common.Helper; +import com.sun.star.wizards.common.JavaTools; +import com.sun.star.wizards.common.NumberFormatter; +import com.sun.star.wizards.common.Resource; +import java.util.HashMap; +import java.util.Map; +import java.util.Vector; + +public class CommandMetaData extends DBMetaData +{ + public Map FieldTitleSet = new HashMap(); + public String[] m_aAllFieldNames = new String[]{}; + public FieldColumn[] FieldColumns = new FieldColumn[]{}; + public String[] GroupFieldNames = new String[] {}; + private String[][] SortFieldNames = new String[][] {}; + private String[] RecordFieldNames = new String[] {}; + public String[][] AggregateFieldNames = new String[][] {}; + public String[] NumericFieldNames = new String[] {}; + public String[] NonAggregateFieldNames; + private int CommandType; + private String Command; + boolean bCatalogAtStart = true; + String sCatalogSep = ""; + String sIdentifierQuote = ""; + boolean bCommandComposerAttributesalreadyRetrieved = false; + + + private XIndexAccess xIndexKeys; + + public CommandMetaData(XMultiServiceFactory xMSF, Locale _aLocale, NumberFormatter oNumberFormatter) + { + super(xMSF, _aLocale, oNumberFormatter); + } + + public CommandMetaData(XMultiServiceFactory xMSF) + { + super(xMSF); + } + + + public void initializeFieldColumns(boolean _bgetDefaultValue, String _CommandName, String[] _FieldNames) + { + this.setCommandName(_CommandName); + FieldColumns = new FieldColumn[_FieldNames.length]; + for (int i = 0; i < _FieldNames.length; i++) + { + FieldColumns[i] = new FieldColumn(this, _FieldNames[i], this.getCommandName(), false); +// if (_bgetDefaultValue) +// { +// FieldColumns[i].getDefaultValue(); +// } + } + } + + + public void initializeFieldColumns(String[] _FieldNames, XNameAccess _xColumns) + { + FieldColumns = new FieldColumn[_FieldNames.length]; + for (int i = 0; i < _FieldNames.length; i++) + { + FieldColumns[i] = new FieldColumn(this,_xColumns, _FieldNames[i] ); + } + } + + + public void initializeFieldColumns(String[] _FieldNames, String _CommandName) + { + this.setCommandName(_CommandName); + FieldColumns = new FieldColumn[_FieldNames.length]; + for (int i = 0; i < _FieldNames.length; i++) + { + FieldColumns[i] = new FieldColumn(this, _FieldNames[i], _CommandName, false); + if (FieldTitleSet != null) + { + if (FieldTitleSet.containsKey(_FieldNames[i])) + { + FieldColumns[i].setFieldTitle( (String) FieldTitleSet.get(_FieldNames[i]) ); + if (FieldColumns[i].getFieldTitle() == null) + { + FieldColumns[i].setFieldTitle( _FieldNames[i] ); + FieldTitleSet.put(_FieldNames[i], _FieldNames[i]); + } + } + } + } + } + + public Map getFieldTitleSet() + { + return FieldTitleSet; + } + + + public XPropertySet getColumnObjectByFieldName(String _FieldName, boolean _bgetByDisplayName) + { + try + { + FieldColumn CurFieldColumn = null; + if (_bgetByDisplayName) + { + CurFieldColumn = this.getFieldColumnByDisplayName(_FieldName); + } + else + { + CurFieldColumn = this.getFieldColumnByFieldName(_FieldName); + } + String CurCommandName = CurFieldColumn.getCommandName(); + CommandObject oCommand = getTableByName(CurCommandName); + Object oColumn = oCommand.getColumns().getByName(CurFieldColumn.getFieldName()); + XPropertySet xColumn = UnoRuntime.queryInterface( XPropertySet.class, oColumn ); + return xColumn; + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + return null; + } + } + + + // @SuppressWarnings("unchecked") + public void prependSortFieldNames(String[] _fieldnames) + { + Vector aSortFields = new Vector(); + for (int i = 0; i < _fieldnames.length; i++) + { + String[] sSortFieldName = new String[2]; + sSortFieldName[0] = _fieldnames[i]; + int index = JavaTools.FieldInTable(SortFieldNames, _fieldnames[i]); + if (index > -1) + + { + sSortFieldName[1] = SortFieldNames[index][1]; + } + else + + { + sSortFieldName[1] = "ASC"; + } + aSortFields.add(sSortFieldName); + } + for (int i = 0; i < SortFieldNames.length; i++) + { + if (JavaTools.FieldInList(_fieldnames, SortFieldNames[i][0]) == -1) + { + aSortFields.add(SortFieldNames[i]); + } + } + SortFieldNames = new String[aSortFields.size()][2]; + aSortFields.toArray(SortFieldNames); + } + + public String[][] getSortFieldNames() + { + return SortFieldNames; + } + public void setSortFieldNames(String[][] aNewListList) + { + SortFieldNames = aNewListList; + } + + public FieldColumn getFieldColumn(String _FieldName, String _CommandName) + { + if (FieldColumns.length > 0) + { + for (int i = 0; i < FieldColumns.length; i++) + { + if (FieldColumns[i].getFieldName().equals(_FieldName)) + + { + if (FieldColumns[i].getCommandName().equals(_CommandName)) + { + return FieldColumns[i]; + } + } + } + } + return null; + } + + + + public FieldColumn getFieldColumnByFieldName(String _FieldName) + { + for (int i = 0; i < FieldColumns.length; i++) + { + String sFieldName = FieldColumns[i].getFieldName(); + if (sFieldName.equals(_FieldName)) + { + return FieldColumns[i]; + } + if (_FieldName.indexOf('.') == -1) + { + String sCompound = Command + "." + _FieldName; + if (sFieldName.equals(sCompound)) + { + return FieldColumns[i]; + } + } + } + throw new com.sun.star.uno.RuntimeException(); + } + + + public FieldColumn getFieldColumnByDisplayName(String _DisplayName) + { + for (int i = 0; i < FieldColumns.length; i++) + { + String sDisplayName = FieldColumns[i].getDisplayFieldName(); + if (sDisplayName.equals(_DisplayName)) + { + return FieldColumns[i]; + } + if (_DisplayName.indexOf('.') == -1) + { + String sCompound = Command + "." + _DisplayName; + if (sDisplayName.equals(sCompound)) + { + return FieldColumns[i]; + } + } + } + throw new com.sun.star.uno.RuntimeException(); + } + + + public FieldColumn getFieldColumnByTitle(String _FieldTitle) + { + for (int i = 0; i < FieldColumns.length; i++) + { + if (FieldColumns[i].getFieldTitle().equals(_FieldTitle)) + { + return FieldColumns[i]; + } + } + // throw new com.sun.star.uno.RuntimeException(); + // LLA: Group works with fields direct + for (int i = 0; i < FieldColumns.length; i++) + { + if (FieldColumns[i].getFieldName().equals(_FieldTitle)) + { + return FieldColumns[i]; + } + } + throw new com.sun.star.uno.RuntimeException(); + } + + + public boolean getFieldNamesOfCommand(String _commandname, int _commandtype, boolean _bAppendMode) + { + try + { + // Object oField; + java.util.Vector<String> ResultFieldNames = new java.util.Vector<String>(10); + String[] FieldNames; + CommandObject oCommand = this.getCommandByName(_commandname, _commandtype); + FieldNames = oCommand.getColumns().getElementNames(); + if (FieldNames.length > 0) + { + for (int n = 0; n < FieldNames.length; n++) + { + final String sFieldName = FieldNames[n]; + Object oField = oCommand.getColumns().getByName(sFieldName); + int iType = AnyConverter.toInt(Helper.getUnoPropertyValue(oField, "Type")); + // BinaryFieldTypes are not included in the WidthList + if (JavaTools.FieldInIntTable(WidthList, iType) >= 0) + { +// if (_bAppendMode) +// ResultFieldNames.addElement(_commandname + "." + FieldNames[n]); +// else + ResultFieldNames.addElement(sFieldName); + } + else if (JavaTools.FieldInIntTable(BinaryTypes, iType) >= 0) + { + ResultFieldNames.addElement(sFieldName); + } + } + // FieldNames = new String[FieldNames.length]; + // FieldTypes = new int[FieldNames.length]; + m_aAllFieldNames = new String[ResultFieldNames.size()]; + ResultFieldNames.copyInto(m_aAllFieldNames); + return true; + } + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + } + Resource oResource = new Resource(xMSF, "Database", "dbw"); + String sMsgNoFieldsFromCommand = oResource.getResText(RID_DB_COMMON + 45); + sMsgNoFieldsFromCommand = JavaTools.replaceSubString(sMsgNoFieldsFromCommand, _commandname, "%NAME"); + showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, sMsgNoFieldsFromCommand); + return false; + } + + + + + + + public String[] getOrderableColumns(String[] _fieldnames) + { + Vector<String> aOrderableColumns = new Vector<String>(); + int ncount = 0; + for (int i = 0; i < _fieldnames.length; i++) + { + FieldColumn ofieldcolumn = getFieldColumnByFieldName(_fieldnames[i]); + if (getDBDataTypeInspector().isColumnOrderable(ofieldcolumn.getXColumnPropertySet())) + { + aOrderableColumns.addElement(_fieldnames[i]); + ncount++; + } + } + String[] sretfieldnames = new String[ncount]; + aOrderableColumns.toArray(sretfieldnames); + return sretfieldnames; + } + + + /** + * @return Returns the command. + */ + public String getCommandName() + { + return Command; + } + /** + * @param _command The command to set. + */ + public void setCommandName(String _command) + { + Command = _command; + } + + /** + * @return Returns the commandType. + */ + public int getCommandType() + { + return CommandType; + } + + /** + * @param _commandType The commandType to set. + */ + public void setCommandType(int _commandType) + { + CommandType = _commandType; + } + + + public boolean isnumeric(FieldColumn _oFieldColumn) + { + try + { + CommandObject oTable = super.getTableByName(_oFieldColumn.getCommandName()); + Object oField = oTable.getColumns().getByName(_oFieldColumn.getFieldName()); + int iType = AnyConverter.toInt(Helper.getUnoPropertyValue(oField, "Type")); + int ifound = java.util.Arrays.binarySearch(NumericTypes, iType); + if ((ifound < NumericTypes.length) && (ifound > 0)) + { + return (NumericTypes[ifound] == iType); + } + else + { + return false; + } + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + return false; + } + } + + public String[] setNumericFields() + { + try + { + Vector<String> numericfieldsvector = new java.util.Vector<String>(); + for (int i = 0; i < FieldColumns.length; i++) + { + if (isnumeric(FieldColumns[i])) + { + numericfieldsvector.addElement(FieldColumns[i].getDisplayFieldName()); + } + } + NumericFieldNames = new String[numericfieldsvector.size()]; + numericfieldsvector.toArray(NumericFieldNames); + return NumericFieldNames; + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + return new String[]{}; + } + } + + public String[] getFieldNames(String[] _sDisplayFieldNames, String _sCommandName) + { + Vector<String> sFieldNamesVector = new java.util.Vector<String>(); + for (int i = 0; i < FieldColumns.length; i++) + { + if (_sCommandName.equals(FieldColumns[i].getCommandName())) + { + if (JavaTools.FieldInList(_sDisplayFieldNames, FieldColumns[i].getDisplayFieldName()) > -1) + { + sFieldNamesVector.addElement(FieldColumns[i].getFieldName()); + } + } + } + String[] sFieldNames = new String[sFieldNamesVector.size()]; + sFieldNamesVector.toArray(sFieldNames); + return sFieldNames; + } + + + + public String[] getFieldNames() + { + String[] sFieldNames = new String[FieldColumns.length]; + for (int i = 0; i < FieldColumns.length; i++) + { + sFieldNames[i] = FieldColumns[i].getFieldName(); + } + return sFieldNames; + } + + public String[] getDisplayFieldNames() + { + String[] sDisplayFieldNames = new String[FieldColumns.length]; + for (int i = 0; i < FieldColumns.length; i++) + { + sDisplayFieldNames[i] = FieldColumns[i].getDisplayFieldName(); + } + return sDisplayFieldNames; + } + + + public String[] setNonAggregateFieldNames() + { + try + { + Vector<String> nonaggregatefieldsvector = new java.util.Vector<String>(); + for (int i = 0; i < FieldColumns.length; i++) + { + if (JavaTools.FieldInTable(AggregateFieldNames, FieldColumns[i].getDisplayFieldName()) == -1) + { + nonaggregatefieldsvector.addElement(FieldColumns[i].getDisplayFieldName()); + } + } + NonAggregateFieldNames = new String[nonaggregatefieldsvector.size()]; + nonaggregatefieldsvector.toArray(NonAggregateFieldNames); + return NonAggregateFieldNames; + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + return new String[]{}; + } + } + + /** + * the fieldnames passed over are not necessarily the ones that are defined in the class + * @param _DisplayFieldNames + * @return + */ + public boolean hasNumericalFields(String[] _DisplayFieldNames) + + { + if (_DisplayFieldNames != null) + { + if (_DisplayFieldNames.length > 0) + { + for (int i = 0; i < _DisplayFieldNames.length; i++) + { + if (isnumeric(getFieldColumnByDisplayName(_DisplayFieldNames[i]))) + { + return true; + } + } + } + } + return false; + } + + public String getFieldTitle(String FieldName) + { + String FieldTitle = FieldName; + if (this.FieldTitleSet != null) + { + FieldTitle = (String) this.FieldTitleSet.get(FieldName); //FieldTitles[TitleIndex]; + if (FieldTitle == null) + { + return FieldName; + } + } + return FieldTitle; + } + + + public void setFieldTitles(String[] sFieldTitles) + { + int nFieldColLength = FieldColumns.length; + for (int i = 0; i < sFieldTitles.length; i++) + { + if (i < nFieldColLength) + { + FieldColumns[i].setFieldTitle(sFieldTitles[i]); + } + + } + } + + + public String[] getFieldTitles() + { + String[] sFieldTitles = new String[FieldColumns.length]; + for (int i = 0; i < FieldColumns.length; i++) + { + sFieldTitles[i] = FieldColumns[i].getFieldTitle(); + } + return sFieldTitles; + } + + + public void setGroupFieldNames(String[] GroupFieldNames) + { + this.GroupFieldNames = GroupFieldNames; + } + + + public String[] getGroupFieldNames() + { + return GroupFieldNames; + } + + public void createRecordFieldNames() + { + String CurFieldName; + int GroupFieldCount; + int TotFieldCount = FieldColumns.length; + // int SortFieldCount = SortFieldNames[0].length; + GroupFieldCount = JavaTools.getArraylength(GroupFieldNames); + RecordFieldNames = new String[TotFieldCount - GroupFieldCount]; + + int a = 0; + for (int i = 0; i < TotFieldCount; i++) + { + CurFieldName = FieldColumns[i].getFieldName(); + if (JavaTools.FieldInList(GroupFieldNames, CurFieldName) < 0) + { + RecordFieldNames[a] = CurFieldName; + // a += 1; + ++a; + } + } + } + public void setRecordFieldNames(String [] _aNewList) + { + RecordFieldNames = _aNewList; + } + public String[] getRecordFieldNames() + { + return RecordFieldNames; + } + public String getRecordFieldName(int i) + { + return RecordFieldNames[i]; + } + + /**@deprecated use 'RelationController' class instead + * + * @param _stablename + * @param _ncommandtype + * @return + */ + public String[] getReferencedTables(String _stablename, int _ncommandtype) + { + String[] sTotReferencedTables = new String[]{}; + try + { + if (_ncommandtype == com.sun.star.sdb.CommandType.TABLE) + { + if (xDBMetaData.supportsIntegrityEnhancementFacility()) + { + java.util.Vector<String> TableVector = new java.util.Vector<String>(); + Object oTable = getTableNamesAsNameAccess().getByName(_stablename); + XKeysSupplier xKeysSupplier = UnoRuntime.queryInterface( XKeysSupplier.class, oTable ); + xIndexKeys = xKeysSupplier.getKeys(); + for (int i = 0; i < xIndexKeys.getCount(); i++) + { + XPropertySet xPropertySet = UnoRuntime.queryInterface( XPropertySet.class, xIndexKeys.getByIndex( i ) ); + int curtype = AnyConverter.toInt(xPropertySet.getPropertyValue("Type")); + if (curtype == KeyType.FOREIGN) + { + // getImportedKeys (RelationController.cxx /source/ui/relationdesign) /Zeile 475 + String sreftablename = AnyConverter.toString(xPropertySet.getPropertyValue("ReferencedTable")); + if (getTableNamesAsNameAccess().hasByName(sreftablename)) + { + TableVector.addElement(sreftablename); + } + } + } + if (TableVector.size() > 0) + { + sTotReferencedTables = new String[TableVector.size()]; + TableVector.copyInto(sTotReferencedTables); + } + } + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + return sTotReferencedTables; + } + + /**@deprecated use 'RelationController' class instead + * + * @param _sreferencedtablename + * @return + */ + public String[][] getKeyColumns(String _sreferencedtablename) + { + String[][] skeycolumnnames = null; + try + { + for (int i = 0; i < xIndexKeys.getCount(); i++) + { + XPropertySet xPropertySet = UnoRuntime.queryInterface( XPropertySet.class, xIndexKeys.getByIndex( i ) ); + int curtype = AnyConverter.toInt(xPropertySet.getPropertyValue("Type")); + if (curtype == KeyType.FOREIGN) + { + String scurreftablename = AnyConverter.toString(xPropertySet.getPropertyValue("ReferencedTable")); + if (getTableNamesAsNameAccess().hasByName(scurreftablename)) + { + if (scurreftablename.equals(_sreferencedtablename)) + { + XColumnsSupplier xColumnsSupplier = UnoRuntime.queryInterface( XColumnsSupplier.class, xPropertySet ); + String[] smastercolnames = xColumnsSupplier.getColumns().getElementNames(); + skeycolumnnames = new String[2][smastercolnames.length]; + skeycolumnnames[0] = smastercolnames; + skeycolumnnames[1] = new String[smastercolnames.length]; + for (int n = 0; n < smastercolnames.length; n++) + { + XPropertySet xcolPropertySet = UnoRuntime.queryInterface( XPropertySet.class, xColumnsSupplier.getColumns().getByName( smastercolnames[n] ) ); + skeycolumnnames[1][n] = AnyConverter.toString(xcolPropertySet.getPropertyValue("RelatedColumn")); + } + return skeycolumnnames; + } + } + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + return skeycolumnnames; + } + + + public void openFormDocument(boolean _bReadOnly) + { + try + { + Object oEmbeddedFactory = super.xMSF.createInstance("com.sun.star.embed.OOoEmbeddedObjectFactory"); + int iEntryInitMode = EntryInitModes.DEFAULT_INIT; //TRUNCATE_INIT??? + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + } + + + public void setCommandComposingAttributes() + { + try + { + boolean bCatalogAtStart2 = xDBMetaData.isCatalogAtStart(); + sCatalogSep = xDBMetaData.getCatalogSeparator(); + sIdentifierQuote = xDBMetaData.getIdentifierQuoteString(); + bCommandComposerAttributesalreadyRetrieved = true; + } + catch (SQLException e) + { + e.printStackTrace(System.out); + } + } + + + /** + * @return Returns the bCatalogAtStart. + */ + public boolean isCatalogAtStart() + { + if (!bCommandComposerAttributesalreadyRetrieved) + { + setCommandComposingAttributes(); + } + return bCatalogAtStart; + } + + /** + * @return Returns the sCatalogSep. + */ + public String getCatalogSeparator() + { + if (!bCommandComposerAttributesalreadyRetrieved) + { + setCommandComposingAttributes(); + } + return sCatalogSep; + } + + /** + * @return Returns the sIdentifierQuote. + */ + public String getIdentifierQuote() + { + if (!bCommandComposerAttributesalreadyRetrieved) + { + setCommandComposingAttributes(); + } + return sIdentifierQuote; + } +} diff --git a/wizards/com/sun/star/wizards/db/CommandName.java b/wizards/com/sun/star/wizards/db/CommandName.java new file mode 100644 index 000000000000..aa8a4f9c7ea9 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/CommandName.java @@ -0,0 +1,267 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.wizards.db; + +import com.sun.star.sdbc.SQLException; +import com.sun.star.uno.Exception; +import com.sun.star.wizards.common.JavaTools; + +public class CommandName +{ + + protected CommandMetaData oCommandMetaData; + protected String CatalogName = ""; + protected String SchemaName = ""; + protected String TableName = ""; + protected String DisplayName = ""; + protected String ComposedName = ""; + protected String AliasName = ""; + protected boolean bCatalogAtStart; + protected String sCatalogSep; + protected String sIdentifierQuote; + protected boolean baddQuotation = true; + + public CommandName(CommandMetaData _CommandMetaData, String _DisplayName) + { + oCommandMetaData = _CommandMetaData; + setComposedCommandName(_DisplayName); + } + + public CommandName(CommandMetaData _CommandMetaData, String _CatalogName, String _SchemaName, String _TableName, boolean _baddQuotation) + { + try + { + baddQuotation = _baddQuotation; + oCommandMetaData = _CommandMetaData; + if ((_CatalogName != null) && (oCommandMetaData.xDBMetaData.supportsCatalogsInTableDefinitions())) + { + if (!_CatalogName.equals("")) + { + CatalogName = _CatalogName; + } + } + if ((_SchemaName != null) && (oCommandMetaData.xDBMetaData.supportsSchemasInTableDefinitions())) + { + if (!_SchemaName.equals("")) + { + SchemaName = _SchemaName; + } + } + if (_TableName != null) + { + if (!_TableName.equals("")) + { + TableName = _TableName; + } + } + setComposedCommandName(); + } + catch (SQLException e) + { + e.printStackTrace(System.out); + } + } + + private void setComposedCommandName(String _DisplayName) + { + try + { + if (this.setMetaDataAttributes()) + { + this.DisplayName = _DisplayName; + int iIndex; + if (oCommandMetaData.xDBMetaData.supportsCatalogsInDataManipulation() == true) + { // ...dann Catalog mit in TableName + iIndex = _DisplayName.indexOf(sCatalogSep); + if (iIndex >= 0) + { + if (bCatalogAtStart == true) + { + CatalogName = _DisplayName.substring(0, iIndex); + _DisplayName = _DisplayName.substring(iIndex + 1, _DisplayName.length()); + } + else + { + CatalogName = _DisplayName.substring(iIndex + 1, _DisplayName.length()); + _DisplayName = _DisplayName.substring(0, iIndex); + } + } + } + if (oCommandMetaData.xDBMetaData.supportsSchemasInDataManipulation() == true) + { + String[] NameList; + NameList = new String[0]; + NameList = JavaTools.ArrayoutofString(_DisplayName, "."); + SchemaName = NameList[0]; + TableName = NameList[1]; // TODO Was ist mit diesem Fall: CatalogSep = "." und CatalogName = "" + } + else + { + TableName = _DisplayName; + } + setComposedCommandName(); + } + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + } + } + + public void setComposedCommandName() + { + if (this.setMetaDataAttributes()) + { + if (CatalogName != null) + { + if (!CatalogName.equals("")) + { + if (bCatalogAtStart == true) + { + ComposedName = quoteName(CatalogName) + sCatalogSep; + } + } + } + if (SchemaName != null) + { + if (!SchemaName.equals("")) + { + ComposedName += quoteName(SchemaName) + "."; + } + } + if (ComposedName.equals("")) + { + ComposedName = quoteName(TableName); + } + else + { + ComposedName += quoteName(TableName); + } + if ((bCatalogAtStart == false) && (CatalogName != null)) + { + if (!CatalogName.equals("")) + { + ComposedName += sCatalogSep + quoteName(CatalogName); + } + } + } + } + + private boolean setMetaDataAttributes() + { + try + { + bCatalogAtStart = oCommandMetaData.xDBMetaData.isCatalogAtStart(); + sCatalogSep = oCommandMetaData.xDBMetaData.getCatalogSeparator(); + sIdentifierQuote = oCommandMetaData.xDBMetaData.getIdentifierQuoteString(); + return true; + } + catch (SQLException e) + { + e.printStackTrace(System.out); + return false; + } + } + + public String quoteName(String _sName) + { + if (baddQuotation) + { + return quoteName(_sName, this.oCommandMetaData.getIdentifierQuote()); + } + else + { + return _sName; + } + } + + public static String quoteName(String sName, String _sIdentifierQuote) + { + if (sName == null) + { + sName = ""; + } + String ReturnQuote = ""; + ReturnQuote = _sIdentifierQuote + sName + _sIdentifierQuote; + return ReturnQuote; + } + + public void setAliasName(String _AliasName) + { + AliasName = _AliasName; + } + + public String getAliasName() + { + return AliasName; + } + + /** + * @return Returns the catalogName. + */ + public String getCatalogName() + { + return CatalogName; + } + + /** + * @return Returns the composedName. + */ + public String getComposedName() + { + return ComposedName; + } + + /** + * @return Returns the displayName. + */ + public String getDisplayName() + { + return DisplayName; + } + + /** + * @return Returns the schemaName. + */ + public String getSchemaName() + { + return SchemaName; + } + + /** + * @return Returns the tableName. + */ + public String getTableName() + { + return TableName; + } + + public CommandMetaData getCommandMetaData() + { + return oCommandMetaData; + } +} diff --git a/wizards/com/sun/star/wizards/db/DBMetaData.java b/wizards/com/sun/star/wizards/db/DBMetaData.java new file mode 100644 index 000000000000..16f8587e535c --- /dev/null +++ b/wizards/com/sun/star/wizards/db/DBMetaData.java @@ -0,0 +1,1123 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.wizards.db; + +import com.sun.star.awt.XWindow; +import com.sun.star.lang.XInitialization; +import com.sun.star.ui.dialogs.XExecutableDialog; + +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.awt.VclWindowPeerAttribute; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XChild; +import com.sun.star.container.XHierarchicalNameAccess; +import com.sun.star.container.XHierarchicalNameContainer; +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNameContainer; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.frame.XModel; +import com.sun.star.frame.XStorable; +import com.sun.star.lang.XComponent; +import com.sun.star.sdbc.DataType; +import com.sun.star.sdb.XOfficeDatabaseDocument; +import com.sun.star.sdb.XDocumentDataSource; +import com.sun.star.sdb.tools.XConnectionTools; +import com.sun.star.sdbcx.XColumnsSupplier; + +import com.sun.star.ucb.XSimpleFileAccess; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.AnyConverter; +import com.sun.star.util.XCloseable; +import com.sun.star.util.XNumberFormatsSupplier; + +import com.sun.star.task.XInteractionHandler; +import com.sun.star.sdb.XFormDocumentsSupplier; +import com.sun.star.sdb.XQueryDefinitionsSupplier; +import com.sun.star.sdb.XReportDocumentsSupplier; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbc.XDatabaseMetaData; +import com.sun.star.sdbc.XDataSource; +import com.sun.star.sdbc.XResultSet; +import com.sun.star.sdbc.XRow; +import com.sun.star.sdb.XCompletedConnection; +import com.sun.star.lang.Locale; +import com.sun.star.lang.XSingleServiceFactory; +import com.sun.star.sdb.XQueriesSupplier; +import com.sun.star.sdbc.XConnection; +import com.sun.star.sdbcx.XTablesSupplier; +import com.sun.star.wizards.common.Configuration; +import com.sun.star.wizards.common.Desktop; +import com.sun.star.wizards.common.FileAccess; +import com.sun.star.wizards.common.JavaTools; +import com.sun.star.wizards.common.NamedValueCollection; +import com.sun.star.wizards.common.NumberFormatter; +import com.sun.star.wizards.common.Properties; +import com.sun.star.wizards.common.Resource; +import com.sun.star.wizards.common.SystemDialog; +import com.sun.star.uno.Any; +import java.util.Vector; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class DBMetaData +{ + + private XNameAccess xQueryNames; + public XDatabaseMetaData xDBMetaData; + private XDataSource m_dataSource; + private XPropertySet m_dataSourceSettings; + private XOfficeDatabaseDocument xModel; + private XPropertySet xDataSourcePropertySet; + public String[] DataSourceNames; + public String[] CommandNames; + public java.util.Vector CommandObjects = new Vector(1); + public Locale aLocale; + public int[] CommandTypes; + public String DataSourceName; + public com.sun.star.sdbc.XConnection DBConnection; + public com.sun.star.sdb.tools.XConnectionTools ConnectionTools; + public com.sun.star.lang.XMultiServiceFactory xMSF; + public XComponent xConnectionComponent; + public SQLQueryComposer oSQLQueryComposer; + + private XNameAccess m_xTableNames; + private XInteractionHandler oInteractionHandler; + private XNameAccess xNameAccess; + private XInterface xDatabaseContext; + private XCompletedConnection xCompleted; + // private int[] nDataTypes = null; + private XWindowPeer xWindowPeer; + private String[] TableNames = new String[] {}; + private String[] QueryNames = new String[] {}; + + protected int[][] WidthList; + protected static final int[] NumericTypes = { + DataType.TINYINT, // == -6; + DataType.BIGINT, // == -5 + DataType.NUMERIC, // == - 2 + DataType.DECIMAL, // == 3; + DataType.INTEGER, // == 4; + DataType.SMALLINT, // == 5; + DataType.FLOAT, // == 6; + DataType.REAL, // == 7; + DataType.DOUBLE, // == 8; + }; + protected static final int[] BinaryTypes = { //new int[12]; + DataType.BINARY, + DataType.VARBINARY, + DataType.LONGVARBINARY, + DataType.BLOB, + DataType.SQLNULL, + DataType.OBJECT, + DataType.DISTINCT, + DataType.STRUCT, + DataType.ARRAY, + DataType.CLOB, + DataType.REF + /* DataType.OTHER, */ + }; + + private int iMaxColumnsInSelect; + private int iMaxColumnsInGroupBy; + private int iMaxColumnsInTable; + private int iMaxColumnNameLength = -1; + private int iMaxTableNameLength = -1; + private boolean bPasswordIsRequired; + private final static int NOLIMIT = 9999999; + protected final static int RID_DB_COMMON = 1000; + private final static int INVALID = 9999999; + public TypeInspector oTypeInspector; + private NumberFormatter oNumberFormatter = null; + private long lDateCorrection = INVALID; + private boolean bdisposeConnection = false; + + public XPropertySet getDataSourcePropertySet() + { + return xDataSourcePropertySet; + } + + public DBMetaData(XMultiServiceFactory xMSF) + { + getInterfaces(xMSF); + InitializeWidthList(); + } + + public DBMetaData(XMultiServiceFactory xMSF, Locale _aLocale, NumberFormatter _oNumberFormatter) + { + oNumberFormatter = _oNumberFormatter; + aLocale = _aLocale; + getInterfaces(xMSF); + InitializeWidthList(); + } + + public NumberFormatter getNumberFormatter() + { + if (oNumberFormatter == null) + { + try + { + XNumberFormatsSupplier xNumberFormatsSupplier = (XNumberFormatsSupplier) AnyConverter.toObject(XNumberFormatsSupplier.class, xDataSourcePropertySet.getPropertyValue("NumberFormatsSupplier")); + //TODO get the locale from the datasource + aLocale = Configuration.getOfficeLocale(xMSF); + oNumberFormatter = new NumberFormatter(xMSF, xNumberFormatsSupplier, aLocale); + lDateCorrection = oNumberFormatter.getNullDateCorrection(); + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + } + return oNumberFormatter; + } + + public long getNullDateCorrection() + { + if (lDateCorrection == INVALID) + { + if (oNumberFormatter == null) + { + oNumberFormatter = getNumberFormatter(); + } + lDateCorrection = oNumberFormatter.getNullDateCorrection(); + } + return lDateCorrection; + } + + void getInterfaces(XMultiServiceFactory xMSF) + { + try + { + this.xMSF = xMSF; + xDatabaseContext = (XInterface) xMSF.createInstance("com.sun.star.sdb.DatabaseContext"); + xNameAccess = UnoRuntime.queryInterface( XNameAccess.class, xDatabaseContext ); + XInterface xInteractionHandler = (XInterface) xMSF.createInstance("com.sun.star.task.InteractionHandler"); + oInteractionHandler = UnoRuntime.queryInterface( XInteractionHandler.class, xInteractionHandler ); + DataSourceNames = xNameAccess.getElementNames(); + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + } + } + + public void setCommandTypes() + { + int TableCount; + int QueryCount; + int CommandCount; + int i; + int a; + TableCount = JavaTools.getArraylength(TableNames); + QueryCount = JavaTools.getArraylength(QueryNames); + CommandCount = TableCount + QueryCount; + CommandTypes = new int[CommandCount]; + if (TableCount > 0) + { + for (i = 0; i < TableCount; i++) + { + CommandTypes[i] = com.sun.star.sdb.CommandType.TABLE; + } + a = i; + for (i = 0; i < QueryCount; i++) + { + CommandTypes[a] = com.sun.star.sdb.CommandType.QUERY; + a += 1; + } + } + } + + public boolean hasTableByName(String _stablename) + { + // getTableNames(); + return getTableNamesAsNameAccess().hasByName(_stablename); + } + + @SuppressWarnings("unchecked") + public void setTableByName(String _tableName) + { + CommandObject oTableObject = new CommandObject(_tableName, com.sun.star.sdb.CommandType.TABLE); + this.CommandObjects.addElement(oTableObject); + } + + public CommandObject getTableByName(String _tablename) + { + return getCommandByName(_tablename, com.sun.star.sdb.CommandType.TABLE); + } + + public CommandObject getQueryByName(String _queryname) + { + return getCommandByName(_queryname, com.sun.star.sdb.CommandType.QUERY); + } + + public CommandObject getCommandByName(String _commandname, int _commandtype) + { + CommandObject oCommand = null; + for (int i = 0; i < CommandObjects.size(); i++) + { + oCommand = (CommandObject) CommandObjects.elementAt(i); + if ((oCommand.Name.equals(_commandname)) && (oCommand.CommandType == _commandtype)) + { + return oCommand; + } + } + if (oCommand == null) + { + oCommand = new CommandObject(_commandname, _commandtype); + CommandObjects.addElement(oCommand); + } + return oCommand; + } + + public void setQueryByName(String _QueryName) + { + CommandObject oQueryObject = new CommandObject(_QueryName, com.sun.star.sdb.CommandType.QUERY); + this.CommandObjects.addElement(oQueryObject); + } + + public class CommandObject + { + + private XNameAccess xColumns; + private XPropertySet xPropertySet; + private String Name; + private int CommandType; + + public CommandObject(String _CommandName, int _CommandType) + { + try + { + Object oCommand; + this.Name = _CommandName; + this.CommandType = _CommandType; + // if (getTableNamesAsNameAccess() == null) + // { + // initCommandNames(); + // } + if (CommandType == com.sun.star.sdb.CommandType.TABLE) + { + oCommand = getTableNamesAsNameAccess().getByName(Name); + } + else + { + oCommand = getQueryNamesAsNameAccess().getByName(Name); + } + XColumnsSupplier xCommandCols = UnoRuntime.queryInterface( XColumnsSupplier.class, oCommand ); + xPropertySet = UnoRuntime.queryInterface( XPropertySet.class, oCommand ); +// TODO: Performance leak getColumns() take very long. + xColumns = UnoRuntime.queryInterface( XNameAccess.class, xCommandCols.getColumns() ); + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + } + } + public XNameAccess getColumns() + { + return xColumns; + } + public String getName() + { + return Name; + } + public XPropertySet getPropertySet() + { + return xPropertySet; + } + } + + public boolean hasEscapeProcessing(XPropertySet _xQueryPropertySet) + { + boolean bHasEscapeProcessing = false; + try + { + if (_xQueryPropertySet.getPropertySetInfo().hasPropertyByName("EscapeProcessing")) + { + bHasEscapeProcessing = AnyConverter.toBoolean(_xQueryPropertySet.getPropertyValue("EscapeProcessing")); + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + return bHasEscapeProcessing; + } + + // public void initCommandNames() + // { + // getTableNames(); + // } + + public XNameAccess getQueryNamesAsNameAccess() + { + XQueriesSupplier xDBQueries = UnoRuntime.queryInterface( XQueriesSupplier.class, DBConnection ); + xQueryNames = xDBQueries.getQueries(); + return xQueryNames; + } + + public XNameAccess getTableNamesAsNameAccess() + { + XTablesSupplier xDBTables = UnoRuntime.queryInterface( XTablesSupplier.class, DBConnection ); + XNameAccess xTableNames = xDBTables.getTables(); + return xTableNames; + } + + public String[] getQueryNames() + { + if (QueryNames != null) + { + if (QueryNames.length > 0) + { + return QueryNames; + } + } + QueryNames = getQueryNamesAsNameAccess().getElementNames(); + return QueryNames; + } + + public String[] getTableNames() + { + if (TableNames != null) + { + if (TableNames.length > 0) + { + return TableNames; + } + } + TableNames = getTableNamesAsNameAccess().getElementNames(); + return TableNames; + } + + void InitializeWidthList() + { + WidthList = new int[17][2]; + WidthList[0][0] = DataType.BIT; // == -7; + WidthList[1][0] = DataType.BOOLEAN; // = 16 + WidthList[2][0] = DataType.TINYINT; // == -6; + WidthList[3][0] = DataType.BIGINT; // == -5; + WidthList[4][0] = DataType.LONGVARCHAR; // == -1; + WidthList[5][0] = DataType.CHAR; // == 1; + WidthList[6][0] = DataType.NUMERIC; // == 2; + WidthList[7][0] = DataType.DECIMAL; // == 3; [mit Nachkommastellen] + WidthList[8][0] = DataType.INTEGER; // == 4; + WidthList[9][0] = DataType.SMALLINT; // == 5; + WidthList[10][0] = DataType.FLOAT; // == 6; + WidthList[11][0] = DataType.REAL; // == 7; + WidthList[12][0] = DataType.DOUBLE; // == 8; + WidthList[13][0] = DataType.VARCHAR; // == 12; + WidthList[14][0] = DataType.DATE; // == 91; + WidthList[15][0] = DataType.TIME; // == 92; + WidthList[16][0] = DataType.TIMESTAMP; // == 93; + // NumericTypes are all types where aggregate functions can be performed on. + // Similarly to a major competitor date/time/timmestamp fields are not included + + + } + + public boolean isBinaryDataType(int _itype) + { + if (NumericTypes == null) + { + InitializeWidthList(); + } + return (JavaTools.FieldInIntTable(BinaryTypes, _itype) > -1); + } + + public int getMaxTablesInSelect() + { + try + { + int itablecount = xDBMetaData.getMaxTablesInSelect(); + if (itablecount == 0) + { + return DBMetaData.NOLIMIT; + } + else + { + return itablecount; + } + } + catch (SQLException e) + { + e.printStackTrace(System.out); + return - 1; + } + } + + public int getMaxColumnsInSelect() + { + return iMaxColumnsInSelect; + } + + public int getMaxColumnsInGroupBy() + { + return iMaxColumnsInGroupBy; + } + + private void setMaxColumnsInSelect() throws SQLException + { + iMaxColumnsInSelect = xDBMetaData.getMaxColumnsInSelect(); + if (iMaxColumnsInSelect == 0) + { + iMaxColumnsInSelect = DBMetaData.NOLIMIT; + } + } + + private void setMaxColumnsInGroupBy() throws SQLException + { + iMaxColumnsInGroupBy = xDBMetaData.getMaxColumnsInGroupBy(); + if (iMaxColumnsInGroupBy == 0) + { + iMaxColumnsInGroupBy = DBMetaData.NOLIMIT; + } + } + + public int getMaxColumnsInTable() throws SQLException + { + iMaxColumnsInTable = xDBMetaData.getMaxColumnsInTable(); + if (iMaxColumnsInTable == 0) + { + iMaxColumnsInTable = DBMetaData.NOLIMIT; + } + return iMaxColumnsInTable; + } + + private void getDataSourceObjects() throws Exception + { + try + { + xDBMetaData = DBConnection.getMetaData(); + getDataSourceInterfaces(); + setMaxColumnsInGroupBy(); + setMaxColumnsInSelect(); + } + catch (SQLException e) + { + e.printStackTrace(System.out); + } + } + + private void ensureDataSourceSettings() throws UnknownPropertyException, WrappedTargetException + { + if ( m_dataSourceSettings != null ) + return; + + XPropertySet dataSourceProperties = UnoRuntime.queryInterface( XPropertySet.class, getDataSource() ); + m_dataSourceSettings = UnoRuntime.queryInterface( XPropertySet.class, dataSourceProperties.getPropertyValue( "Settings" ) ); + } + + public boolean isSQL92CheckEnabled() + { + boolean isSQL92CheckEnabled = false; + try + { + ensureDataSourceSettings(); + isSQL92CheckEnabled = AnyConverter.toBoolean( m_dataSourceSettings.getPropertyValue( "EnableSQL92Check" ) ); + } + catch (Exception e) + { + e.printStackTrace(); + } + return isSQL92CheckEnabled; + } + + public String verifyName(String _sname, int _maxlen) + { + if (_sname.length() > _maxlen) + { + return _sname.substring(0, _maxlen); + } + if (this.isSQL92CheckEnabled()) + { + return Desktop.removeSpecialCharacters(xMSF, Configuration.getOfficeLocale(xMSF), _sname); + } + return _sname; + } + + public XDataSource getDataSource() + { + if (m_dataSource == null) + { + try + { + Object oDataSource = xNameAccess.getByName(DataSourceName); + m_dataSource = UnoRuntime.queryInterface( XDataSource.class, oDataSource ); + } + catch (com.sun.star.container.NoSuchElementException e) + { + } + catch (com.sun.star.lang.WrappedTargetException e) + { + } + } + return m_dataSource; + } + + private void setDataSourceByName(String _DataSourceName, boolean bgetInterfaces) + { + try + { + this.DataSourceName = _DataSourceName; + getDataSourceInterfaces(); + XDocumentDataSource xDocu = UnoRuntime.queryInterface( XDocumentDataSource.class, getDataSource() ); + if (xDocu != null) + { + xModel = xDocu.getDatabaseDocument(); + } + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + } + } + + public void getDataSourceInterfaces() throws Exception + { + xCompleted = UnoRuntime.queryInterface( XCompletedConnection.class, getDataSource() ); + xDataSourcePropertySet = UnoRuntime.queryInterface( XPropertySet.class, getDataSource() ); + bPasswordIsRequired = ((Boolean) xDataSourcePropertySet.getPropertyValue("IsPasswordRequired")).booleanValue(); + } + + public boolean getConnection(PropertyValue[] curproperties) + { + try + { + XConnection xConnection = null; + if (Properties.hasPropertyValue(curproperties, "ActiveConnection")) + { + xConnection = UnoRuntime.queryInterface( XConnection.class, Properties.getPropertyValue( curproperties, "ActiveConnection" ) ); + if (xConnection != null) + { + com.sun.star.container.XChild child = UnoRuntime.queryInterface( com.sun.star.container.XChild.class, xConnection ); + + m_dataSource = UnoRuntime.queryInterface( XDataSource.class, child.getParent() ); + XDocumentDataSource xDocu = UnoRuntime.queryInterface( XDocumentDataSource.class, m_dataSource ); + if (xDocu != null) + { + xModel = xDocu.getDatabaseDocument(); + } + XPropertySet xPSet = UnoRuntime.queryInterface( XPropertySet.class, m_dataSource ); + if (xPSet != null) + { + DataSourceName = AnyConverter.toString(xPSet.getPropertyValue("Name")); + } + return getConnection(xConnection); + } + else + { + bdisposeConnection = true; + } + } + else + { + bdisposeConnection = true; + } + if (Properties.hasPropertyValue(curproperties, "DataSourceName")) + { + String sDataSourceName = AnyConverter.toString(Properties.getPropertyValue(curproperties, "DataSourceName")); + return getConnection(sDataSourceName); + } + else if (Properties.hasPropertyValue(curproperties, "DataSource")) + { + m_dataSource = UnoRuntime.queryInterface( XDataSource.class, Properties.getPropertyValue( curproperties, "DataSource" ) ); + XDocumentDataSource xDocu = UnoRuntime.queryInterface( XDocumentDataSource.class, this.m_dataSource ); + if (xDocu != null) + { + xModel = xDocu.getDatabaseDocument(); + } + return getConnection(m_dataSource); + } + if (Properties.hasPropertyValue(curproperties, "DatabaseLocation")) + { + String sDataSourceName = AnyConverter.toString(Properties.getPropertyValue(curproperties, "DatabaseLocation")); + return getConnection(sDataSourceName); + } + else if (xConnection != null) + { + bdisposeConnection = false; + return getConnection(xConnection); + } + } + catch (IllegalArgumentException e) + { + e.printStackTrace(System.out); + } + catch (UnknownPropertyException e) + { + e.printStackTrace(System.out); + } + catch (WrappedTargetException e) + { + e.printStackTrace(System.out); + } + + return false; + } + + private boolean getConnection(String _DataSourceName) + { + setDataSourceByName(_DataSourceName, true); + return getConnection( getDataSource() ); + } + + private boolean getConnection(com.sun.star.sdbc.XConnection _DBConnection) + { + try + { + this.DBConnection = _DBConnection; + this.ConnectionTools = UnoRuntime.queryInterface( XConnectionTools.class, this.DBConnection ); + getDataSourceObjects(); + return true; + } + catch (Exception e) + { + e.printStackTrace(System.out); + return false; + } + } + + private boolean getConnection(XDataSource _dataSource) + { + Resource oResource = new Resource(xMSF, "Database", "dbw"); + try + { + int iMsg = 0; + boolean bgetConnection = false; + if (DBConnection != null) + { + xConnectionComponent.dispose(); + } + getDataSourceInterfaces(); + if (bPasswordIsRequired == false) + { + DBConnection = _dataSource.getConnection("", ""); + bgetConnection = true; + } + else + { + XInteractionHandler xInteractionHandler = UnoRuntime.queryInterface( XInteractionHandler.class, xMSF.createInstance("com.sun.star.task.InteractionHandler") ); + boolean bExitLoop = true; + do + { + XCompletedConnection xCompleted2 = UnoRuntime.queryInterface( XCompletedConnection.class, _dataSource ); + try + { + DBConnection = xCompleted2.connectWithCompletion( xInteractionHandler ); + bgetConnection = DBConnection != null; + if (bgetConnection == false) + { + bExitLoop = true; + } + } + catch (Exception exception) + { + // Note: WindowAttributes from toolkit/source/awt/vclxtoolkit.cxx + String sMsgNoConnection = oResource.getResText(RID_DB_COMMON + 14); + iMsg = showMessageBox("QueryBox", VclWindowPeerAttribute.RETRY_CANCEL, sMsgNoConnection); + bExitLoop = iMsg == 0; + bgetConnection = false; + } + } + while (bExitLoop == false); + } + if (bgetConnection == false) + { + String sMsgConnectionImpossible = oResource.getResText(RID_DB_COMMON + 35); + showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, sMsgConnectionImpossible); + } + else + { + xConnectionComponent = UnoRuntime.queryInterface( XComponent.class, DBConnection ); + ConnectionTools = UnoRuntime.queryInterface( XConnectionTools.class, DBConnection ); + getDataSourceObjects(); + } + return bgetConnection; + } + catch (Exception exception) + { + String sMsgConnectionImpossible = oResource.getResText(RID_DB_COMMON + 35); + showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, sMsgConnectionImpossible); + exception.printStackTrace(System.out); + return false; + } + } + + public int getMaxColumnNameLength() + { + try + { + if (iMaxColumnNameLength <= 0) + { + iMaxColumnNameLength = xDBMetaData.getMaxColumnNameLength(); + } + return iMaxColumnNameLength; + } + catch (SQLException e) + { + e.printStackTrace(System.out); + return 0; + } + } + + public int getMaxTableNameLength() + { + try + { + if (iMaxTableNameLength <= 0) + { + iMaxTableNameLength = xDBMetaData.getMaxTableNameLength(); + } + return iMaxTableNameLength; + } + catch (SQLException e) + { + e.printStackTrace(System.out); + return 0; + } + } + + public boolean supportsPrimaryKeys() + { + boolean supportsPrimaryKeys = false; + try + { + ensureDataSourceSettings(); + Any primaryKeySupport = (Any)m_dataSourceSettings.getPropertyValue( "PrimaryKeySupport" ); + if ( AnyConverter.isVoid( primaryKeySupport ) ) + supportsPrimaryKeys = supportsCoreSQLGrammar(); + else + supportsPrimaryKeys = AnyConverter.toBoolean( primaryKeySupport ); + } + catch ( Exception ex ) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, ex ); + } + return supportsPrimaryKeys; + } + + public boolean supportsCoreSQLGrammar() + { + try + { + return xDBMetaData.supportsCoreSQLGrammar(); + } + catch (SQLException e) + { + e.printStackTrace(System.out); + return false; + } + } + + public boolean supportsAutoIncrementation() + { + return false; + } + + /** + * inserts a Query to a datasource; There is no validation if the queryname is already existing in the datasource + * @param oQuery + * @param QueryName + */ + public boolean createQuery(SQLQueryComposer _oSQLQueryComposer, String _QueryName) + { + try + { + XQueryDefinitionsSupplier xQueryDefinitionsSuppl = UnoRuntime.queryInterface( XQueryDefinitionsSupplier.class, m_dataSource ); + XNameAccess xQueryDefs = xQueryDefinitionsSuppl.getQueryDefinitions(); + XSingleServiceFactory xSSFQueryDefs = UnoRuntime.queryInterface( XSingleServiceFactory.class, xQueryDefs ); + Object oQuery = xSSFQueryDefs.createInstance(); //"com.sun.star.sdb.QueryDefinition" + XPropertySet xPSet = UnoRuntime.queryInterface( XPropertySet.class, oQuery ); + + String s = _oSQLQueryComposer.m_xQueryAnalyzer.getQuery(); + xPSet.setPropertyValue("Command", s); + + XNameContainer xNameCont = UnoRuntime.queryInterface( XNameContainer.class, xQueryDefs ); + ConnectionTools.getObjectNames().checkNameForCreate(com.sun.star.sdb.CommandType.QUERY, _QueryName); + xNameCont.insertByName(_QueryName, oQuery); + return true; + } + catch (WrappedTargetException exception) + { + SQLException sqlError = null; + try + { + sqlError = (SQLException) exception.TargetException; + } + catch (ClassCastException castError) + { + } + + if (sqlError != null) + { + callSQLErrorMessageDialog(sqlError, null); + return false; + } + exception.printStackTrace(System.out); + } + catch (SQLException exception) + { + callSQLErrorMessageDialog(exception, null); + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + } + return false; + } + + public void dispose() + { + if ((DBConnection != null) && (this.bdisposeConnection)) + { + xConnectionComponent.dispose(); + } + } + + public XHierarchicalNameAccess getReportDocuments() + { + XReportDocumentsSupplier xReportDocumentSuppl = UnoRuntime.queryInterface( XReportDocumentsSupplier.class, this.xModel ); + xReportDocumentSuppl.getReportDocuments(); + XHierarchicalNameAccess xReportHier = UnoRuntime.queryInterface( XHierarchicalNameAccess.class, xReportDocumentSuppl.getReportDocuments() ); + return xReportHier; + } + + public XHierarchicalNameAccess getFormDocuments() + { + XFormDocumentsSupplier xFormDocumentSuppl = UnoRuntime.queryInterface( XFormDocumentsSupplier.class, xModel ); + XHierarchicalNameAccess xFormHier = UnoRuntime.queryInterface( XHierarchicalNameAccess.class, xFormDocumentSuppl.getFormDocuments() ); + return xFormHier; + } + + public boolean hasFormDocumentByName(String _sFormName) + { + XFormDocumentsSupplier xFormDocumentSuppl = UnoRuntime.queryInterface( XFormDocumentsSupplier.class, xModel ); + XNameAccess xFormNameAccess = UnoRuntime.queryInterface( XNameAccess.class, xFormDocumentSuppl.getFormDocuments() ); + return xFormNameAccess.hasByName(_sFormName); + } + + public void addFormDocument(XComponent _xComponent) + { + XHierarchicalNameAccess _xFormDocNameAccess = getFormDocuments(); + addDatabaseDocument(_xComponent, _xFormDocNameAccess, false); + } + + public void addReportDocument(XComponent _xComponent, boolean _bcreatedynamicreport) + { + XHierarchicalNameAccess xReportDocNameAccess = getReportDocuments(); + addDatabaseDocument(_xComponent, xReportDocNameAccess, _bcreatedynamicreport); + } + + /** + * adds the passed document as a report or a form to the database. Afterwards the document is deleted. + * the document may not be open + * @param _xComponent + * @param _xDocNameAccess + * @param _bcreateTemplate describes the type of the document: "form" or "report" + */ + public void addDatabaseDocument(XComponent _xComponent, XHierarchicalNameAccess _xDocNameAccess, boolean i_createTemplate) + { + try + { + XModel xDocumentModel = UnoRuntime.queryInterface( XModel.class, _xComponent ); + String documentURL = xDocumentModel.getURL(); + String basename = FileAccess.getBasename(documentURL, "/"); + XCloseable xCloseable = UnoRuntime.queryInterface( XCloseable.class, _xComponent ); + xCloseable.close(false); + + NamedValueCollection creationArgs = new NamedValueCollection(); + creationArgs.put( "Name", basename ); + creationArgs.put( "URL", documentURL ); + creationArgs.put( "AsTemplate", new Boolean( i_createTemplate ) ); + XMultiServiceFactory xDocMSF = UnoRuntime.queryInterface( XMultiServiceFactory.class, _xDocNameAccess ); + Object oDBDocument = xDocMSF.createInstanceWithArguments( "com.sun.star.sdb.DocumentDefinition", creationArgs.getPropertyValues() ); + XHierarchicalNameContainer xHier = UnoRuntime.queryInterface( XHierarchicalNameContainer.class, _xDocNameAccess ); + String sdocname = Desktop.getUniqueName(_xDocNameAccess, basename); + xHier.insertByHierarchicalName(sdocname, oDBDocument); + XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess"); + XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface( XSimpleFileAccess.class, xInterface ); + xSimpleFileAccess.kill(documentURL); + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + } + + public void createTypeInspector() throws SQLException + { + oTypeInspector = new TypeInspector(xDBMetaData.getTypeInfo()); + } + + public TypeInspector getDBDataTypeInspector() + { + return oTypeInspector; + } + + private String[] StringsFromResultSet(XResultSet _xResultSet, int _icol) + { + String[] sColValues = null; + try + { + XRow xRow = UnoRuntime.queryInterface( XRow.class, _xResultSet ); + Vector aColVector = new Vector(); + while (_xResultSet.next()) + { + aColVector.addElement(xRow.getString(_icol)); + } + sColValues = new String[aColVector.size()]; + aColVector.toArray(sColValues); + } + catch (SQLException e) + { + e.printStackTrace(); + } + return sColValues; + } + + public String[] getCatalogNames() + { + try + { + XResultSet xResultSet = xDBMetaData.getCatalogs(); + return StringsFromResultSet(xResultSet, 1); + } + catch (SQLException e) + { + e.printStackTrace(System.out); + return null; + } + } + + public String[] getSchemaNames() + { + try + { + XResultSet xResultSet = xDBMetaData.getSchemas(); + return StringsFromResultSet(xResultSet, 1); + } + catch (SQLException e) + { + e.printStackTrace(System.out); + return null; + } + } + + public boolean storeDatabaseDocumentToTempPath(XComponent _xcomponent, String _storename) + { + try + { + XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess"); + XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface( XSimpleFileAccess.class, xInterface ); + String storepath = FileAccess.getOfficePath(xMSF, "Temp", xSimpleFileAccess) + "/" + _storename; + XStorable xStoreable = UnoRuntime.queryInterface( XStorable.class, _xcomponent ); + PropertyValue[] oStoreProperties = new PropertyValue[1]; + oStoreProperties[0] = Properties.createProperty("FilterName", "writer8"); + storepath += ".odt"; + xStoreable.storeAsURL(storepath, oStoreProperties); + return true; + } + catch (Exception e) + { + e.printStackTrace(System.out); + return false; + } + } + + public int showMessageBox(String windowServiceName, int windowAttribute, String MessageText) + { + if (getWindowPeer() != null) + { + return SystemDialog.showMessageBox(xMSF, xWindowPeer, windowServiceName, windowAttribute, MessageText); + } + else + { + return SystemDialog.showMessageBox(xMSF, windowServiceName, windowAttribute, MessageText); + } + } + + /** + * @return Returns the xWindowPeer. + */ + public XWindowPeer getWindowPeer() + { + return xWindowPeer; + } + + /** + * @param windowPeer The xWindowPeer to set. + * Should be called as soon as a Windowpeer of a wizard dialog is available + * The windowpeer is needed to call a Messagebox + */ + public void setWindowPeer(XWindowPeer windowPeer) + { + xWindowPeer = windowPeer; + } + + public void callSQLErrorMessageDialog(SQLException oSQLException, XWindow _xWindow) + { + try + { + Object oDialog = xMSF.createInstance("com.sun.star.sdb.ErrorMessageDialog"); + XInitialization xInitialization = UnoRuntime.queryInterface( XInitialization.class, oDialog ); + PropertyValue[] aPropertyValue = new PropertyValue[2]; + aPropertyValue[0] = Properties.createProperty("SQLException", oSQLException); + aPropertyValue[1] = Properties.createProperty("ParentWindow", _xWindow); + xInitialization.initialize(aPropertyValue); + XExecutableDialog xExecutableDialog = UnoRuntime.queryInterface( XExecutableDialog.class, oDialog ); + xExecutableDialog.execute(); + } + catch (com.sun.star.uno.Exception ex) + { + ex.printStackTrace(); + } + } + + public void finish() + { + xQueryNames = null; + oInteractionHandler = null; + xNameAccess = null; + xDatabaseContext = null; + xDBMetaData = null; + m_dataSource = null; + xModel = null; + xCompleted = null; + xDataSourcePropertySet = null; + xWindowPeer = null; + DBConnection = null; + ConnectionTools = null; + xMSF = null; + xConnectionComponent = null; + oSQLQueryComposer = null; + CommandObjects = null; + } +} diff --git a/wizards/com/sun/star/wizards/db/DatabaseObjectWizard.java b/wizards/com/sun/star/wizards/db/DatabaseObjectWizard.java new file mode 100644 index 000000000000..5c65d73794f0 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/DatabaseObjectWizard.java @@ -0,0 +1,75 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package com.sun.star.wizards.db; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.frame.XController; +import com.sun.star.frame.XFrame; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.sdb.application.XDatabaseDocumentUI; +import com.sun.star.sdbc.SQLException; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.wizards.common.Desktop; +import com.sun.star.wizards.common.NamedValueCollection; +import com.sun.star.wizards.ui.WizardDialog; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * is a base class for a wizard creating a database object + * @author frank.schoenheit@sun.com + */ +public abstract class DatabaseObjectWizard extends WizardDialog +{ + protected final PropertyValue[] m_wizardContext; + protected final XDatabaseDocumentUI m_docUI; + protected final XFrame m_frame; + + protected DatabaseObjectWizard( final XMultiServiceFactory i_orb, final int i_helpIDBase, final PropertyValue[] i_wizardContext ) + { + super( i_orb, i_helpIDBase ); + m_wizardContext = i_wizardContext; + + final NamedValueCollection wizardContext = new NamedValueCollection( m_wizardContext ); + m_docUI = wizardContext.queryOrDefault( "DocumentUI", (XDatabaseDocumentUI)null, XDatabaseDocumentUI.class ); + + if ( m_docUI != null ) + { + XController docController = UnoRuntime.queryInterface( XController.class, m_docUI ); + m_frame = docController.getFrame(); + } + else + { + XFrame parentFrame = wizardContext.queryOrDefault( "ParentFrame", (XFrame)null, XFrame.class ); + if ( parentFrame != null ) + m_frame = parentFrame; + else + m_frame = Desktop.getActiveFrame( xMSF ); + } + } + + protected final void loadSubComponent( final int i_type, final String i_name, final boolean i_forEditing ) + { + try + { + m_docUI.loadComponent( i_type, i_name, i_forEditing ); + } + catch ( IllegalArgumentException ex ) + { + Logger.getLogger( this.getClass().getName() ).log( Level.SEVERE, null, ex ); + } + catch ( NoSuchElementException ex ) + { + Logger.getLogger( this.getClass().getName() ).log( Level.SEVERE, null, ex ); + } + catch ( SQLException ex ) + { + Logger.getLogger( this.getClass().getName() ).log( Level.SEVERE, null, ex ); + } + } +} diff --git a/wizards/com/sun/star/wizards/db/FieldColumn.java b/wizards/com/sun/star/wizards/db/FieldColumn.java new file mode 100644 index 000000000000..041aab5f5300 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/FieldColumn.java @@ -0,0 +1,471 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.wizards.db; + +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XNameAccess; +// import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.sdbc.DataType; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.wizards.common.*; + +public class FieldColumn +{ + protected int ColIndex; + + private Object DefaultValue; + private String m_sFieldName; + private String m_sDisplayFieldName; + private String FieldTitle; + private String m_sCommandName; + private int m_nDBFormatKey; + private int m_nFieldType; + private XPropertySet m_xColPropertySet; + + // field meta data + private int FieldWidth; + private int StandardFormatKey; + private boolean bIsNumberFormat; + + private static boolean bFormatKeysInitialized = false; + private static int iDateFormatKey; + private static int iDateTimeFormatKey; + private static int iNumberFormatKey; + private static int iTextFormatKey; + private static int iTimeFormatKey; + private static int iLogicalFormatKey; + + private CommandMetaData m_aCommandMetaData; + + public FieldColumn(CommandMetaData oCommandMetaData, String _DisplayFieldName) + { + m_sDisplayFieldName = _DisplayFieldName; + m_sCommandName = oCommandMetaData.getCommandName(); + m_sFieldName = getOnlyFieldName(m_sDisplayFieldName, m_sCommandName); +// TODO: could be wrong here! +// FieldTitle = _DisplayFieldName; // oCommandMetaData.getFieldTitle(m_sFieldName); + FieldTitle = m_sFieldName; + DBMetaData.CommandObject oTable = oCommandMetaData.getTableByName(m_sCommandName); + initializeFormatKeys(oCommandMetaData, oTable.getColumns()); + } + + public FieldColumn(CommandMetaData oCommandMetaData, String _FieldName, String _CommandName, boolean _bInstantiateByDisplayName) + { + m_sCommandName = _CommandName; + if (_bInstantiateByDisplayName) + { + m_sDisplayFieldName = _FieldName; + m_sFieldName = getOnlyFieldName(_FieldName, _CommandName); + } + else + { + m_sFieldName = _FieldName; + m_sDisplayFieldName = composeDisplayFieldName(_CommandName, m_sFieldName); + } + FieldTitle = m_sFieldName; + m_aCommandMetaData = oCommandMetaData; + } + + public FieldColumn(CommandMetaData oCommandMetaData, XNameAccess _xColumns, String _FieldName) + { + m_sFieldName = _FieldName; +// FieldTitle = m_sFieldName; + m_sDisplayFieldName = m_sFieldName; + ColIndex = JavaTools.FieldInList(_xColumns.getElementNames(), m_sFieldName) + 1; + initializeFormatKeys(oCommandMetaData, _xColumns); + } + + public int getFieldType() + { + if (m_nFieldType == 0) + { + DBMetaData.CommandObject oTable = m_aCommandMetaData.getTableByName(m_sCommandName); + initializeFormatKeys(m_aCommandMetaData, oTable.getColumns()); + } + return m_nFieldType; + } + + public int getFieldWidth() + { + getFieldType(); // will collect meta data 'bout the column, if not already done so + return FieldWidth; + } + + public int getDBFormatKey() + { + getFieldType(); // will collect meta data 'bout the column, if not already done so + return m_nDBFormatKey; + } + + public int getStandardFormatKey() + { + getFieldType(); // will collect meta data 'bout the column, if not already done so + return StandardFormatKey; + } + public boolean isNumberFormat() + { + getFieldType(); // will collect meta data 'bout the column, if not already done so + return bIsNumberFormat; + } + + /** + * Remove the pre name, we want the name after the 'dot' + * @param _DisplayFieldName + * @param _CommandName + * @return + */ + private String getOnlyFieldName(String _DisplayFieldName, String _CommandName) + { + final String sName = _DisplayFieldName.substring(_CommandName.length() + 1, _DisplayFieldName.length()); + return sName; + } + + public static String composeDisplayFieldName(String _sCommandName, String _sFieldName) + { + return _sCommandName + "." + _sFieldName; + } + + private void initializeFormatKeys(CommandMetaData oCommandMetaData, XNameAccess _xColumns) + { + try + { + m_xColPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, _xColumns.getByName(m_sFieldName)); + ColIndex = JavaTools.FieldInList(_xColumns.getElementNames(), m_sFieldName) + 1; + m_nFieldType = AnyConverter.toInt(m_xColPropertySet.getPropertyValue("Type")); + getTyperelatedFieldData(); + + if (bFormatKeysInitialized == false) + { + final NumberFormatter aNumberFormatter = oCommandMetaData.getNumberFormatter(); + + iDateFormatKey = aNumberFormatter.getDateFormatKey(); + iDateTimeFormatKey = aNumberFormatter.getDateTimeFormatKey(); + iNumberFormatKey = aNumberFormatter.getNumberFormatKey(); + iTextFormatKey = aNumberFormatter.getTextFormatKey(); + iTimeFormatKey = aNumberFormatter.getTimeFormatKey(); + iLogicalFormatKey = aNumberFormatter.getLogicalFormatKey(); + bFormatKeysInitialized = true; + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + } + + public XPropertySet getXColumnPropertySet() + { + getFieldType(); // will collect meta data 'bout the column, if not already done so + return m_xColPropertySet; + } + + public void setCommandName(String _CommandName) + { + m_sCommandName = _CommandName; + } + + public String getDisplayFieldName() + { + return m_sDisplayFieldName; + } + + public String getCommandName() + { + return m_sCommandName; + } + + public String getFieldName() + { + return m_sFieldName; + } + + public String getFieldTitle() + { + return FieldTitle; + } + + public void setFieldTitle(String _sTitle) + { + FieldTitle = _sTitle; + } + + public static String getCommandName(String _DisplayName) + { + String locCommandName = null; + String[] sFieldMetaData = JavaTools.ArrayoutofString(_DisplayName, "."); + if (sFieldMetaData.length >= 2) + { + String locfieldname = sFieldMetaData[sFieldMetaData.length - 1]; + locCommandName = _DisplayName.substring(0, _DisplayName.length() - locfieldname.length() - 1); + } + return locCommandName; + } + + public boolean isBoolean() + { + boolean bIsBoolean = false; + switch ( getFieldType() ) + { + case DataType.BIT: // == -7; + case DataType.BOOLEAN: + bIsBoolean = true; + break; + default: + bIsBoolean = false; + } + return bIsBoolean; + } + + private void getTyperelatedFieldData() + { + try + { + switch ( getFieldType() ) + { + case DataType.BIT: // == -7; + case DataType.BOOLEAN: + // Todo: Look if the defaultvalue has been set in the Datasource + StandardFormatKey = iLogicalFormatKey; + FieldWidth = 5; + bIsNumberFormat = true; + break; + + case DataType.TINYINT: // == -6; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 5; + bIsNumberFormat = true; + break; + + case DataType.SMALLINT: // == 5; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 5; + bIsNumberFormat = true; + break; + + case DataType.INTEGER: // == 4; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 10; + bIsNumberFormat = true; + break; + + case DataType.BIGINT: // == -5; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 15; + bIsNumberFormat = true; + break; + + case DataType.CHAR: // == 1; + StandardFormatKey = iTextFormatKey; + getTextFieldWidth(10); + bIsNumberFormat = false; + break; + + case DataType.VARCHAR: // == 12; + StandardFormatKey = iTextFormatKey; + getTextFieldWidth(30); + bIsNumberFormat = false; + break; + + case DataType.LONGVARCHAR: // == -1; + StandardFormatKey = iTextFormatKey; + getTextFieldWidth(60); + bIsNumberFormat = false; + break; + + case DataType.NUMERIC: // == 2; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 20; + bIsNumberFormat = true; + break; + + case DataType.DECIMAL: // == 3; [mit Nachkommastellen] + StandardFormatKey = iNumberFormatKey; + FieldWidth = 10 + AnyConverter.toInt(m_xColPropertySet.getPropertyValue("Scale")) + 1; + bIsNumberFormat = true; + break; + + case DataType.FLOAT: // == 6; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 10 + AnyConverter.toInt(m_xColPropertySet.getPropertyValue("Scale")) + 1; + bIsNumberFormat = true; + break; + + case DataType.REAL: // == 7; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 10 + AnyConverter.toInt(m_xColPropertySet.getPropertyValue("Scale")) + 1; + bIsNumberFormat = true; + break; + + case DataType.DOUBLE: // == 8; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 10 + AnyConverter.toInt(m_xColPropertySet.getPropertyValue("Scale")) + 1; + bIsNumberFormat = true; + break; + + case DataType.DATE: // == 91; + StandardFormatKey = iDateFormatKey; + FieldWidth = 10; + bIsNumberFormat = true; + break; + + case DataType.TIME: // == 92; + StandardFormatKey = iTimeFormatKey; + FieldWidth = 10; + bIsNumberFormat = true; + break; + + case DataType.TIMESTAMP: // == 93; + StandardFormatKey = iDateTimeFormatKey; + FieldWidth = 20; + bIsNumberFormat = true; + break; + } + + Object oKey = m_xColPropertySet.getPropertyValue("FormatKey"); + if (AnyConverter.isVoid(oKey)) + { + m_nDBFormatKey = StandardFormatKey; + } + else + { + m_nDBFormatKey = AnyConverter.toInt(oKey); + } + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + m_nDBFormatKey = StandardFormatKey; + } + } + + private void getTextFieldWidth(int iWidth) + { + try + { + FieldWidth = AnyConverter.toInt(m_xColPropertySet.getPropertyValue("Precision")); + if (FieldWidth > 0) + { + if (FieldWidth > (2 * iWidth)) + { + FieldWidth = 2 * iWidth; + } + else if (FieldWidth == 0) + { + FieldWidth = iWidth; + } + } + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + } + } + + public void initDefaultValue() + { + switch (getFieldType()) + { + case DataType.BIT: // == -7; + case DataType.BOOLEAN: + DefaultValue = (Object) Integer.valueOf("1"); + break; + + case DataType.TINYINT: // == -6; + DefaultValue = (Object) Integer.valueOf("98"); + break; + + case DataType.SMALLINT: // == 5; + DefaultValue = (Object) Integer.valueOf("987"); + break; + + case DataType.INTEGER: // == 4; + DefaultValue = (Object) Integer.valueOf("9876"); + break; + + case DataType.BIGINT: // == -5; + DefaultValue = (Object) Integer.valueOf("98765"); + break; + + case DataType.CHAR: // == 1; + DefaultValue = (Object) String.valueOf('x'); + break; + + case DataType.VARCHAR: // == 12; + DefaultValue = (Object) BlindtextCreator.getBlindTextString(FieldTitle, FieldWidth, FieldWidth); + break; + + case DataType.LONGVARCHAR: // == -1; + DefaultValue = (Object) BlindtextCreator.getBlindTextString(FieldTitle, FieldWidth, FieldWidth); + break; + + case DataType.NUMERIC: // == 2; + DefaultValue = (Object) Double.valueOf("9876.5"); + break; + + case DataType.DECIMAL: // == 3; [mit Nachkommastellen] + DefaultValue = (Object) Double.valueOf("9876.5"); + break; + + case DataType.FLOAT: // == 6; + DefaultValue = (Object) Double.valueOf("9876.5"); + break; + + case DataType.REAL: // == 7; + DefaultValue = (Object) Double.valueOf("9876.5"); + break; + + case DataType.DOUBLE: // == 8; + DefaultValue = (Object) Double.valueOf("9876.54"); + break; + + case DataType.DATE: // == 91; + DefaultValue = (Object) Double.valueOf("42510"); + break; + + case DataType.TIME: // == 92; + DefaultValue = (Object) Double.valueOf("10"); + break; + + case DataType.TIMESTAMP: // == 93; + DefaultValue = (Object) Double.valueOf("5454110"); + break; + + default: + break; + } + } + + public Object getDefaultValue() + { + if ( DefaultValue == null ) + initDefaultValue(); + return DefaultValue; + } + +} diff --git a/wizards/com/sun/star/wizards/db/MANIFEST.MF b/wizards/com/sun/star/wizards/db/MANIFEST.MF new file mode 100644 index 000000000000..e69de29bb2d1 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/MANIFEST.MF diff --git a/wizards/com/sun/star/wizards/db/QueryMetaData.java b/wizards/com/sun/star/wizards/db/QueryMetaData.java new file mode 100644 index 000000000000..2c49de15696b --- /dev/null +++ b/wizards/com/sun/star/wizards/db/QueryMetaData.java @@ -0,0 +1,293 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.wizards.db; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.beans.PropertyValue; + +import java.util.*; +import com.sun.star.lang.Locale; +import com.sun.star.wizards.common.*; + +public class QueryMetaData extends CommandMetaData +{ + + FieldColumn CurFieldColumn; + public String Command; + // Vector CommandNamesV; + private PropertyValue[][] m_aFilterConditions; /* = new PropertyValue[][] {}; */ + + public PropertyValue[][] GroupByFilterConditions = new PropertyValue[][] + { + }; + public String[] UniqueAggregateFieldNames = new String[] + { + }; + public int Type = QueryType.SODETAILQUERY; + + public static interface QueryType + { + + final static int SOSUMMARYQUERY = 0; + final static int SODETAILQUERY = 1; + } + + public QueryMetaData(XMultiServiceFactory xMSF, Locale CharLocale, NumberFormatter oNumberFormatter) + { + super(xMSF, CharLocale, oNumberFormatter); + } + + public QueryMetaData(XMultiServiceFactory _xMSF) + { + super(_xMSF); + } + + public void setFilterConditions(PropertyValue[][] _FilterConditions) + { + this.m_aFilterConditions = _FilterConditions; + } + + public PropertyValue[][] getFilterConditions() + { + if (m_aFilterConditions == null) + { + m_aFilterConditions = new PropertyValue[][] + { + }; + } + return m_aFilterConditions; + } + + public void setGroupByFilterConditions(PropertyValue[][] _GroupByFilterConditions) + { + this.GroupByFilterConditions = _GroupByFilterConditions; + } + + public PropertyValue[][] getGroupByFilterConditions() + { + return this.GroupByFilterConditions; + } +// public void addFieldColumn(String _FieldName, String _sCommandName){ +// FieldColumn oFieldColumn = getFieldColumn(_FieldName, _sCommandName); +// if (oFieldColumn == null){ +// FieldColumn[] LocFieldColumns = new FieldColumn[FieldColumns.length + 1]; +// System.arraycopy(FieldColumns, 0, LocFieldColumns, 0, FieldColumns.length); +// LocFieldColumns[FieldColumns.length] = new FieldColumn(this, _FieldName, _sCommandName); +// FieldColumns = LocFieldColumns; +// } +// } + public void addSeveralFieldColumns(String[] _FieldNames, String _sCommandName) + { + Vector oToBeAddedFieldColumns = new Vector(); + for (int i = 0; i < _FieldNames.length; i++) + { + FieldColumn oFieldColumn = getFieldColumn(_FieldNames[i], _sCommandName); + if (oFieldColumn == null) + { + oToBeAddedFieldColumns.add(new FieldColumn(this, _FieldNames[i], _sCommandName, false)); + } + } + if (oToBeAddedFieldColumns.size() > 0) + { + int nOldFieldCount = FieldColumns.length; + FieldColumn[] LocFieldColumns = new FieldColumn[nOldFieldCount + oToBeAddedFieldColumns.size()]; + System.arraycopy(FieldColumns, 0, LocFieldColumns, 0, nOldFieldCount); + for (int i = 0; i < oToBeAddedFieldColumns.size(); i++) + { + LocFieldColumns[nOldFieldCount + i] = (FieldColumn) oToBeAddedFieldColumns.elementAt(i); + } + FieldColumns = LocFieldColumns; + } + } + + public void reorderFieldColumns(String[] _sDisplayFieldNames) + { + FieldColumn[] LocFieldColumns = new FieldColumn[FieldColumns.length]; + for (int i = 0; i < _sDisplayFieldNames.length; i++) + { + FieldColumn LocFieldColumn = this.getFieldColumnByDisplayName(_sDisplayFieldNames[i]); + LocFieldColumns[i] = LocFieldColumn; + } + System.arraycopy(LocFieldColumns, 0, FieldColumns, 0, LocFieldColumns.length); + } + + public void removeSeveralFieldColumnsByDisplayFieldName(String[] _DisplayFieldNames) + { + Vector oRemainingFieldColumns = new Vector(); + int a = 0; + for (int n = 0; n < FieldColumns.length; n++) + { + String sDisplayFieldName = FieldColumns[n].getDisplayFieldName(); + if (!(JavaTools.FieldInList(_DisplayFieldNames, sDisplayFieldName) > -1)) + { + oRemainingFieldColumns.add(FieldColumns[n]); + } + } + FieldColumns = new FieldColumn[oRemainingFieldColumns.size()]; + oRemainingFieldColumns.toArray(FieldColumns); + } + + public void removeFieldColumn(String _sFieldName, String _sCommandName) + { + FieldColumn oFieldColumn = getFieldColumn(_sFieldName, _sCommandName); + int a = 0; + if (oFieldColumn != null) + { + FieldColumn[] LocFieldColumns = new FieldColumn[FieldColumns.length - 1]; + for (int i = 0; i < FieldColumns.length; i++) + { + if (!FieldColumns[i].getFieldName().equals(_sFieldName)) + { + if (!FieldColumns[i].getCommandName().equals(_sCommandName)) + { + LocFieldColumns[a] = FieldColumns[i]; + a++; + } + } + } + FieldColumns = LocFieldColumns; + } + } + + public String[] getIncludedCommandNames() + { + // FieldColumn CurQueryField; + Vector CommandNamesV = new Vector(1); + // String CurCommandName; + for (int i = 0; i < FieldColumns.length; i++) + { + final FieldColumn CurQueryField = FieldColumns[i]; + final String CurCommandName = CurQueryField.getCommandName(); + if (!CommandNamesV.contains(CurCommandName)) + { + CommandNamesV.addElement(CurCommandName); + } + } + String[] sIncludedCommandNames = new String[CommandNamesV.size()]; + CommandNamesV.toArray(sIncludedCommandNames); + return sIncludedCommandNames; + } + + public static String[] getIncludedCommandNames(String[] _FieldNames) + { + Vector CommandNames = new Vector(1); + for (int i = 0; i < _FieldNames.length; i++) + { + String CurCommandName = ""; + String[] MetaList = JavaTools.ArrayoutofString(_FieldNames[i], "."); + if (MetaList.length > 1) + { + for (int a = 0; a < MetaList.length - 1; a++) + { + CurCommandName += MetaList[a]; + } + if (!CommandNames.contains(CurCommandName)) + { + CommandNames.addElement(CurCommandName); + } + } + } + String[] sIncludedCommandNames = new String[CommandNames.size()]; + CommandNames.toArray(sIncludedCommandNames); + return sIncludedCommandNames; + } + + public String[] getFieldNamesOfCommand(String _sCommandName) + { + CommandObject oTable = getTableByName(_sCommandName); + return oTable.getColumns().getElementNames(); + } + + public void initializeFieldTitleSet(boolean _bAppendMode) + { + try + { + // this.getIncludedCommandNames(); // fills the var CommandNamesV indirectly :-( + if (FieldTitleSet == null) + { + FieldTitleSet = new HashMap(); + } + String[] aCommandNames = getIncludedCommandNames(); + for (int i = 0; i < aCommandNames.length; i++) + { + String sCommandName = aCommandNames[i]; + CommandObject oTable = getTableByName(sCommandName); + String sTableName = oTable.getName(); + String[] LocFieldNames = oTable.getColumns().getElementNames(); + for (int a = 0; a < LocFieldNames.length; a++) + { + String sDisplayFieldName = FieldColumn.composeDisplayFieldName(sTableName, LocFieldNames[a]); + if (!FieldTitleSet.containsKey(sDisplayFieldName)) + { + FieldTitleSet.put(sDisplayFieldName, LocFieldNames[a]); + } + } + } + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + } + } + + public String[] getUniqueAggregateFieldNames() + { + Vector UniqueAggregateFieldVector = new Vector(0); + for (int i = 0; i < AggregateFieldNames.length; i++) + { + if (!UniqueAggregateFieldVector.contains(AggregateFieldNames[i][0])) + { + UniqueAggregateFieldVector.add(AggregateFieldNames[i][0]); + } + } + UniqueAggregateFieldNames = new String[UniqueAggregateFieldVector.size()]; + UniqueAggregateFieldVector.toArray(UniqueAggregateFieldNames); + return UniqueAggregateFieldNames; + } + + public boolean hasNumericalFields() + { + for (int i = 0; i < FieldColumns.length; i++) + { + if (FieldColumns[i].isNumberFormat()) + { + return true; + } + } + return false; + } + + public int getAggregateIndex(String _DisplayFieldName) + { + int iAggregate = -1; + if (Type == QueryType.SOSUMMARYQUERY) + { + iAggregate = JavaTools.FieldInTable(AggregateFieldNames, _DisplayFieldName); + } + return iAggregate; + } +} diff --git a/wizards/com/sun/star/wizards/db/RecordParser.java b/wizards/com/sun/star/wizards/db/RecordParser.java new file mode 100644 index 000000000000..6c8ddb5b2c36 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/RecordParser.java @@ -0,0 +1,306 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.wizards.db; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.XComponent; +import com.sun.star.sdbc.DataType; +import com.sun.star.sdbcx.XColumnsSupplier; +import com.sun.star.uno.Any; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import com.sun.star.wizards.common.Helper; +import com.sun.star.sdb.XCompletedExecution; +import com.sun.star.lang.Locale; +import com.sun.star.wizards.common.InvalidQueryException; +import com.sun.star.wizards.common.JavaTools; +import com.sun.star.wizards.common.NumberFormatter; +import com.sun.star.sdbc.XResultSet; +import com.sun.star.task.XInteractionHandler; + +public class RecordParser extends QueryMetaData +{ + + XNameAccess xColumns; + com.sun.star.sdbc.XRow xRow; + com.sun.star.sdbc.XRow xResultSetRow; + public XResultSet ResultSet; + XInterface xRowSet; + XCompletedExecution xExecute; + XColumnsSupplier xRowSetColumnsSupplier; + XComponent xRowSetComponent; + XInteractionHandler xInteraction; + public FieldColumn[] GroupFieldColumns; + public FieldColumn[] RecordFieldColumns; + + public RecordParser(XMultiServiceFactory _xMSF, Locale _aLocale, NumberFormatter _oNumberFormatter) + { + super(_xMSF, _aLocale, _oNumberFormatter); + getInterfaces(); + } + + /** Creates a new instance of RecordParser */ + public RecordParser(XMultiServiceFactory _xMSF) + { + super(_xMSF); + getInterfaces(); + } + + private void getInterfaces() + { + try + { + xRowSet = (XInterface) xMSF.createInstance("com.sun.star.sdb.RowSet"); + xRowSetColumnsSupplier = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, xRowSet); + xRowSetComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, xRowSet); + xExecute = (com.sun.star.sdb.XCompletedExecution) UnoRuntime.queryInterface(com.sun.star.sdb.XCompletedExecution.class, xRowSet); + XInterface oInteraction = (XInterface) xMSF.createInstance("com.sun.star.task.InteractionHandler"); + xInteraction = (XInteractionHandler) UnoRuntime.queryInterface(XInteractionHandler.class, oInteraction); + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + } + } + + private Object getColumnStringValue(int ColIndex) + { + try + { + com.sun.star.uno.Type CurType; + Object oAny; + String sValue = xResultSetRow.getString(ColIndex); //??? + CurType = new com.sun.star.uno.Type(String.class); + oAny = AnyConverter.toObject(CurType, sValue); + return oAny; + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + return null; + } + } + + private Object getColumnDoubleValue(int ColIndex, boolean bisDate) + { + try + { + Double DblValue; + if (bisDate) + { + DblValue = new Double(xResultSetRow.getDouble(ColIndex) + (double) super.getNullDateCorrection()); + } + else + { + DblValue = new Double(xResultSetRow.getDouble(ColIndex)); + } + if (!xResultSetRow.wasNull()) + { + return DblValue; + } + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + } + return Any.VOID; + } + + public Object getColumnValue(int ColIndex, int iType) + { + boolean bResult; + Object oAny = Any.VOID; + switch (iType) + { + case DataType.BIT: // == -7; + case DataType.BOOLEAN: + oAny = getColumnDoubleValue(ColIndex, false); + break; + + case DataType.TINYINT: // == -6; + oAny = getColumnDoubleValue(ColIndex, false); + break; + + case DataType.BIGINT: // == -5; + oAny = getColumnDoubleValue(ColIndex, false); + break; + + case DataType.CHAR: // == 1; + oAny = getColumnStringValue(ColIndex); + break; + + case DataType.VARCHAR: // == 12; + oAny = getColumnStringValue(ColIndex); + // double sResult = xResultSetRow.getClob(ColIndex); //??? + break; + + case DataType.LONGVARCHAR: // == -1; + oAny = getColumnStringValue(ColIndex); + // double sResult = xResultSetRow.getCharacterStream(ColIndex); + break; + + case DataType.NUMERIC: // == 2; + oAny = getColumnDoubleValue(ColIndex, false); + break; + + case DataType.INTEGER: // == 4; + oAny = getColumnDoubleValue(ColIndex, false); + break; + + case DataType.SMALLINT: // == 5; + oAny = getColumnDoubleValue(ColIndex, false); + break; + + case DataType.DECIMAL: // == 3; [mit Nachkommastellen] + oAny = getColumnDoubleValue(ColIndex, false); + break; + + case DataType.FLOAT: // == 6; + oAny = getColumnDoubleValue(ColIndex, false); + break; + + case DataType.REAL: // == 7; + oAny = getColumnDoubleValue(ColIndex, false); + break; + + case DataType.DOUBLE: // == 8; + oAny = getColumnDoubleValue(ColIndex, false); + break; + + case DataType.DATE: // == 91; + oAny = getColumnDoubleValue(ColIndex, true); + break; + + case DataType.TIME: // == 92; + oAny = getColumnDoubleValue(ColIndex, false); + break; + + case DataType.TIMESTAMP: // == 93; + oAny = getColumnDoubleValue(ColIndex, true); + break; + } + + // Is the index OK; increment? + // String sValue = xResultSetRow.getString(ColIndex); + return oAny; + } + + public boolean executeCommand(int _nCommandType) throws InvalidQueryException + { + try + { + Helper.setUnoPropertyValue(xRowSet, "DataSourceName", DataSourceName); + Helper.setUnoPropertyValue(xRowSet, "ActiveConnection", DBConnection); + Helper.setUnoPropertyValue(xRowSet, "Command", Command); + Helper.setUnoPropertyValue(xRowSet, "CommandType", new Integer(_nCommandType)); // CommandType + xExecute.executeWithCompletion(xInteraction); + com.sun.star.sdb.XResultSetAccess xResultAccess = (com.sun.star.sdb.XResultSetAccess) UnoRuntime.queryInterface(com.sun.star.sdb.XResultSetAccess.class, xRowSet); + ResultSet = xResultAccess.createResultSet(); + xResultSetRow = (com.sun.star.sdbc.XRow) UnoRuntime.queryInterface(com.sun.star.sdbc.XRow.class, ResultSet); + XColumnsSupplier xDBCols = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, ResultSet); + xColumns = xDBCols.getColumns(); + setCommandType(_nCommandType); + return true; + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + throw new InvalidQueryException(xMSF, Command); + } + } + + public boolean getFields(String[] _sFieldNames, boolean binitializeDBColumns) + { + try + { + if (binitializeDBColumns == true) + { + initializeFieldColumns(_sFieldNames, xColumns); + } + String[] AllQueryFieldNames = xColumns.getElementNames(); + String[] sFieldNames = getFieldNames(); + for (int i = 0; i < FieldColumns.length; i++) + { + String sFieldName = FieldColumns[i].getFieldName(); + int nColIndex = JavaTools.FieldInList(AllQueryFieldNames, sFieldName) + 1; + FieldColumns[i].ColIndex = nColIndex; + if (nColIndex == -1) + { + throw new InvalidQueryException(xMSF, Command); + } + } + GroupFieldColumns = getFieldColumnList(GroupFieldNames); + RecordFieldColumns = getFieldColumnList(getRecordFieldNames()); + return true; + } + catch (InvalidQueryException queryexception) + { + queryexception.printStackTrace(System.out); + return false; + } + } + + private FieldColumn[] getFieldColumnList(String[] _FieldNames) + { + FieldColumn[] LocFieldColumns = new FieldColumn[_FieldNames.length]; + for (int i = 0; i < _FieldNames.length; i++) + { + LocFieldColumns[i] = super.getFieldColumnByFieldName(_FieldNames[i]); + } + return LocFieldColumns; + } + + public Object getGroupColumnValue(int ColIndex) + { + FieldColumn CurDBFieldColumn = this.GroupFieldColumns[ColIndex]; + return getColumnValue(CurDBFieldColumn.ColIndex, CurDBFieldColumn.getFieldType()); + } + + public boolean getcurrentRecordData(java.util.Vector DataVector) + { + Object[] RecordValueArray = new Object[RecordFieldColumns.length]; + for (int i = 0; i < RecordFieldColumns.length; i++) + { + FieldColumn CurDBFieldColumn = this.RecordFieldColumns[i]; + RecordValueArray[i] = getColumnValue(CurDBFieldColumn.ColIndex, CurDBFieldColumn.getFieldType()); //FinalColIndex + } + DataVector.addElement(RecordValueArray); + return true; + } + + public void dispose() + { + if (xRowSetComponent != null) + { + xRowSetComponent.dispose(); + } + super.dispose(); + } +} diff --git a/wizards/com/sun/star/wizards/db/RelationController.java b/wizards/com/sun/star/wizards/db/RelationController.java new file mode 100644 index 000000000000..acf47581d3e2 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/RelationController.java @@ -0,0 +1,161 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.wizards.db; + +import java.util.Vector; + +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbc.XResultSet; +import com.sun.star.sdbc.XRow; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.wizards.common.JavaTools; + +/** + * @author bc93774 + * + * TODO To change the template for this generated type comment go to + * Window - Preferences - Java - Code Style - Code Templates + */ +public class RelationController extends CommandName +{ + + private int PKTABLE_CAT = 1; + private int PKTABLE_SCHEM = 2; + private int PKTABLE_NAME = 3; + private int PKCOLUMN_NAME = 4; + private int FKTABLE_CAT = 5; + private int FKTABLE_SCHEM = 6; + private int FKTABLE_NAME = 7; + private int FKCOLUMN_NAME = 8; + + public RelationController(CommandMetaData _CommandMetaData, String _CatalogName, String _SchemaName, String _TableName, boolean _baddQuotation) + { + super(_CommandMetaData, _CatalogName, _SchemaName, _TableName, _baddQuotation); + } + + public RelationController(CommandMetaData _CommandMetaData, String _DisplayName) + { + super(_CommandMetaData, _DisplayName); + } + + public String[] getExportedKeys() + { + String[] sReferencedTableNames = new String[] + { + }; + try + { + String[] sTableNames = super.getCommandMetaData().getTableNames(); + Vector aReferencedTableVector = new Vector(); + XResultSet xResultSet = super.getCommandMetaData().xDBMetaData.getExportedKeys((getCatalogName(this)), getSchemaName(), getTableName()); + XRow xRow = (XRow) UnoRuntime.queryInterface(XRow.class, xResultSet); + while (xResultSet.next()) + { + String sForeignCatalog = xRow.getString(FKTABLE_CAT); + String sForeignScheme = xRow.getString(FKTABLE_SCHEM); + String sForeignTableName = xRow.getString(FKTABLE_NAME); + CommandName oCommandName = new CommandName(getCommandMetaData(), sForeignCatalog, sForeignScheme, sForeignTableName, false); + aReferencedTableVector.add(oCommandName.getComposedName()); + } + sReferencedTableNames = new String[aReferencedTableVector.size()]; + aReferencedTableVector.toArray(sReferencedTableNames); + } + catch (SQLException e) + { + e.printStackTrace(System.out); + } + return sReferencedTableNames; + } + + private Object getCatalogName(CommandName _oCommandName) + { + String sLocCatalog = _oCommandName.getCatalogName(); + if (sLocCatalog.equals("")) + { + return null; + } + else + { + return sLocCatalog; + } + } + + public String[][] getImportedKeyColumns(String _sreferencedtablename) + { + String[][] sKeyColumnNames = new String[][] + { + }; + try + { + CommandName oLocCommandName = new CommandName(super.getCommandMetaData(), _sreferencedtablename); + XResultSet xResultSet = super.getCommandMetaData().xDBMetaData.getImportedKeys(getCatalogName(oLocCommandName), oLocCommandName.getSchemaName(), oLocCommandName.getTableName()); + XRow xRow = (XRow) UnoRuntime.queryInterface(XRow.class, xResultSet); + boolean bleaveLoop = false; + Vector aMasterFieldNamesVector = new Vector(); + Vector aSlaveFieldNamesVector = new Vector(); + while (xResultSet.next() && !bleaveLoop) + { + String sPrimaryCatalog = null; + String sPrimarySchema = null; + if (super.getCommandMetaData().xDBMetaData.supportsCatalogsInDataManipulation()) + { + sPrimaryCatalog = xRow.getString(PKTABLE_CAT); + } + if (super.getCommandMetaData().xDBMetaData.supportsSchemasInDataManipulation()) + { + sPrimarySchema = xRow.getString(PKTABLE_SCHEM); + } + String sPrimaryTableName = xRow.getString(PKTABLE_NAME); + String sPrimaryColumnName = xRow.getString(PKCOLUMN_NAME); + String sForeignColumnName = xRow.getString(FKCOLUMN_NAME); + if (JavaTools.isSame(getTableName(), sPrimaryTableName)) + { + if (sPrimarySchema == null || JavaTools.isSame(getSchemaName(), sPrimarySchema)) + { + if (JavaTools.isSame(getCatalogName(), sPrimaryCatalog)) + { + aSlaveFieldNamesVector.add(sForeignColumnName); + aMasterFieldNamesVector.add(sPrimaryColumnName); + bleaveLoop = true; //Only one relation may exist between two tables... + } + } + + } + } + sKeyColumnNames = new String[2][aMasterFieldNamesVector.size()]; + sKeyColumnNames[0] = new String[aSlaveFieldNamesVector.size()]; + sKeyColumnNames[1] = new String[aMasterFieldNamesVector.size()]; + aSlaveFieldNamesVector.toArray(sKeyColumnNames[0]); + aMasterFieldNamesVector.toArray(sKeyColumnNames[1]); + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + return sKeyColumnNames; + } +} diff --git a/wizards/com/sun/star/wizards/db/SQLQueryComposer.java b/wizards/com/sun/star/wizards/db/SQLQueryComposer.java new file mode 100644 index 000000000000..a6a63c5a4fc7 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/SQLQueryComposer.java @@ -0,0 +1,421 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.wizards.db; + +import java.util.Vector; + +// import com.sun.star.lang.IllegalArgumentException; +// import com.sun.star.lang.WrappedTargetException; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.beans.*; +// import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XIndexAccess; +// import com.sun.star.container.XNameAccess; +import com.sun.star.sdbcx.XColumnsSupplier; +// import com.sun.star.sdb.XColumn; +import com.sun.star.sdb.XSQLQueryComposerFactory; +import com.sun.star.sdb.XSingleSelectQueryComposer; +import com.sun.star.sdb.XSingleSelectQueryAnalyzer; +import com.sun.star.ui.dialogs.XExecutableDialog; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.sdbc.SQLException; +import com.sun.star.lang.XInitialization; +import com.sun.star.awt.XWindow; + +import com.sun.star.wizards.common.*; + +public class SQLQueryComposer +{ + + public XColumnsSupplier xColSuppl; + // XSQLQueryComposer xSQLQueryComposer; + QueryMetaData CurDBMetaData; + // String m_sSelectClause; + // String m_sFromClause; + public XSingleSelectQueryAnalyzer m_xQueryAnalyzer; + Vector composedCommandNames = new Vector(1); + public XSingleSelectQueryComposer m_xQueryComposer; + XMultiServiceFactory xMSF; + boolean bincludeGrouping = true; + + public SQLQueryComposer(QueryMetaData _CurDBMetaData) + { + try + { + this.CurDBMetaData = _CurDBMetaData; + xMSF = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, CurDBMetaData.DBConnection); + final Object oQueryComposer = xMSF.createInstance("com.sun.star.sdb.SingleSelectQueryComposer"); + m_xQueryAnalyzer = (XSingleSelectQueryAnalyzer) UnoRuntime.queryInterface(XSingleSelectQueryAnalyzer.class, oQueryComposer); + m_xQueryComposer = (XSingleSelectQueryComposer) UnoRuntime.queryInterface(XSingleSelectQueryComposer.class, m_xQueryAnalyzer); + XSQLQueryComposerFactory xSQLComposerFactory; + xSQLComposerFactory = (XSQLQueryComposerFactory) UnoRuntime.queryInterface(XSQLQueryComposerFactory.class, CurDBMetaData.DBConnection); + // /* XSQLQueryComposer */ xSQLQueryComposer = xSQLComposerFactory.createQueryComposer(); + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + } + } + + private boolean addtoSelectClause(String DisplayFieldName) throws SQLException + { + if (bincludeGrouping) + { + if (CurDBMetaData.xDBMetaData.supportsGroupByUnrelated()) + { + if (CurDBMetaData.GroupFieldNames != null) + { + if (JavaTools.FieldInList(CurDBMetaData.GroupFieldNames, DisplayFieldName) > -1) + { + return false; + } + } + } + } + return true; + } + + public String getSelectClause(boolean _baddAliasFieldNames) throws SQLException + { + String sSelectBaseClause = "SELECT "; + String sSelectClause = sSelectBaseClause; + for (int i = 0; i < CurDBMetaData.FieldColumns.length; i++) + { + if (addtoSelectClause(CurDBMetaData.FieldColumns[i].getDisplayFieldName())) + { + int iAggregate = CurDBMetaData.getAggregateIndex(CurDBMetaData.FieldColumns[i].getDisplayFieldName()); + if (iAggregate > -1) + { + sSelectClause += CurDBMetaData.AggregateFieldNames[iAggregate][1] + "(" + getComposedAliasFieldName(CurDBMetaData.AggregateFieldNames[iAggregate][0]) + ")"; + if (_baddAliasFieldNames) + { + sSelectClause += getAliasFieldNameClause(CurDBMetaData.AggregateFieldNames[iAggregate][0]); + } + } + else + { + sSelectClause += getComposedAliasFieldName(CurDBMetaData.FieldColumns[i].getDisplayFieldName()); + if (_baddAliasFieldNames) + { + sSelectClause += getAliasFieldNameClause(CurDBMetaData.FieldColumns[i].getDisplayFieldName()); + } + } + sSelectClause += ", "; + } + } + // TODO: little bit unhandy version of remove the append 'comma' at the end + if (sSelectClause.equals(sSelectBaseClause)) + { + sSelectClause = sSelectClause.substring(0, sSelectClause.length() - 1); + } + else + { + sSelectClause = sSelectClause.substring(0, sSelectClause.length() - 2); + } + return sSelectClause; + } + + public String getAliasFieldNameClause(String _FieldName) + { + String FieldTitle = CurDBMetaData.getFieldTitle(_FieldName); + if (!FieldTitle.equals(_FieldName)) + { + return " AS " + CommandName.quoteName(FieldTitle, CurDBMetaData.getIdentifierQuote()); + } + else + { + return ""; + } + } + + public void appendFilterConditions() throws SQLException + { + try + { + for (int i = 0; i < CurDBMetaData.getFilterConditions().length; i++) + { + String sCurFieldName = CurDBMetaData.getFilterConditions()[i][0].Name; + m_xQueryComposer.setStructuredFilter(CurDBMetaData.getFilterConditions()); + } + String s = m_xQueryAnalyzer.getQuery(); + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + } + } + + public void prependSortingCriteria() throws SQLException + { + XIndexAccess xColumnIndexAccess = m_xQueryAnalyzer.getOrderColumns(); + m_xQueryComposer.setOrder(""); + for (int i = 0; i < CurDBMetaData.getSortFieldNames().length; i++) + { + appendSortingCriterion(i, false); + } + for (int i = 0; i < xColumnIndexAccess.getCount(); i++) + { + try + { + XPropertySet xColumnPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xColumnIndexAccess.getByIndex(i)); + String sName = (String) xColumnPropertySet.getPropertyValue("Name"); + if (JavaTools.FieldInTable(CurDBMetaData.getSortFieldNames(), sName) == -1) + { + boolean bascend = AnyConverter.toBoolean(xColumnPropertySet.getPropertyValue("IsAscending")); + m_xQueryComposer.appendOrderByColumn(xColumnPropertySet, bascend); + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + } + } + + private void appendSortingCriterion(int _SortIndex, boolean _baddAliasFieldNames) throws SQLException + { + String sSortValue = CurDBMetaData.getSortFieldNames()[_SortIndex][0]; + XPropertySet xColumn = CurDBMetaData.getColumnObjectByFieldName(sSortValue, _baddAliasFieldNames); + + String sSort = CurDBMetaData.getSortFieldNames()[_SortIndex][1]; + boolean bascend = (sSort.equals("ASC")); + m_xQueryComposer.appendOrderByColumn(xColumn, bascend); + } + + public void appendSortingcriteria(boolean _baddAliasFieldNames) throws SQLException + { + String sOrder = ""; + m_xQueryComposer.setOrder(""); + for (int i = 0; i < CurDBMetaData.getSortFieldNames().length; i++) + { + String sSortValue = CurDBMetaData.getSortFieldNames()[i][0]; + int iAggregate = CurDBMetaData.getAggregateIndex(sSortValue); + if (iAggregate > -1) + { + sOrder = m_xQueryAnalyzer.getOrder(); + if (sOrder.length() > 0) + { + sOrder += ", "; + } + sOrder += CurDBMetaData.AggregateFieldNames[iAggregate][1] + "(" + CurDBMetaData.AggregateFieldNames[iAggregate][0] + ")"; + sOrder += " " + CurDBMetaData.getSortFieldNames()[i][1]; + m_xQueryComposer.setOrder(sOrder); + } + else + { + appendSortingCriterion(i, _baddAliasFieldNames); + } + sOrder = m_xQueryAnalyzer.getOrder(); + } + // just for debug! + sOrder = m_xQueryComposer.getOrder(); + int dummy = 0; + } + + public void appendGroupByColumns(boolean _baddAliasFieldNames) throws SQLException + { + for (int i = 0; i < CurDBMetaData.GroupFieldNames.length; i++) + { + XPropertySet xColumn = CurDBMetaData.getColumnObjectByFieldName(CurDBMetaData.GroupFieldNames[i], _baddAliasFieldNames); + m_xQueryComposer.appendGroupByColumn(xColumn); + } + String s = m_xQueryAnalyzer.getQuery(); + } + + public void setDBMetaData(QueryMetaData _oDBMetaData) + { + this.CurDBMetaData = _oDBMetaData; + } + + private PropertyValue[][] replaceConditionsByAlias(PropertyValue _filterconditions[][]) + { + for (int n = 0; n < _filterconditions.length; n++) + { + for (int m = 0; m < _filterconditions[n].length; m++) + { + _filterconditions[n][m].Name = getComposedAliasFieldName(_filterconditions[n][m].Name); + } + } + return _filterconditions; + } + + public String getQuery() + { + return m_xQueryAnalyzer.getQuery(); + } + + private String getFromClause() + { + String sFromClause = "FROM"; + String[] sCommandNames = CurDBMetaData.getIncludedCommandNames(); + for (int i = 0; i < sCommandNames.length; i++) + { + CommandName curCommandName = new CommandName(CurDBMetaData, sCommandNames[i]); //(setComposedCommandName) + curCommandName.setAliasName(getuniqueAliasName(curCommandName.getTableName())); + sFromClause += " " + curCommandName.getComposedName() + " " + quoteName(curCommandName.getAliasName()); + if (i < sCommandNames.length - 1) + { + sFromClause += ", "; + } + // fill composedCommandNames + composedCommandNames.add(curCommandName); + } + return sFromClause; + } + + public boolean setQueryCommand(XWindow _xParentWindow, boolean _bincludeGrouping, boolean _baddAliasFieldNames) + { + try + { + String s; + bincludeGrouping = _bincludeGrouping; + String sFromClause = getFromClause(); + String sSelectClause = getSelectClause(_baddAliasFieldNames); + String queryclause = sSelectClause + " " + sFromClause; + m_xQueryAnalyzer.setQuery(queryclause); + if (CurDBMetaData.getFilterConditions() != null) + { + if (CurDBMetaData.getFilterConditions().length > 0) + { + CurDBMetaData.setFilterConditions(replaceConditionsByAlias(CurDBMetaData.getFilterConditions())); + m_xQueryComposer.setStructuredFilter(CurDBMetaData.getFilterConditions()); + } + } + s = m_xQueryAnalyzer.getQuery(); + if (_bincludeGrouping) + { + appendGroupByColumns(_baddAliasFieldNames); + if (CurDBMetaData.GroupByFilterConditions.length > 0) + { + m_xQueryComposer.setStructuredHavingClause(CurDBMetaData.GroupByFilterConditions); + } + } + appendSortingcriteria(_baddAliasFieldNames); + + s = m_xQueryAnalyzer.getQuery(); + return true; + } + catch (Exception exception) + { + exception.printStackTrace(System.out); + displaySQLErrorDialog(exception, _xParentWindow); + return false; + } + } + + private String getComposedAliasFieldName(String _fieldname) + { + FieldColumn CurFieldColumn = CurDBMetaData.getFieldColumnByDisplayName(_fieldname); + CommandName curComposedCommandName = getComposedCommandByDisplayName(CurFieldColumn.getCommandName()); + String curAliasName = curComposedCommandName.getAliasName(); + return quoteName(curAliasName) + "." + quoteName(CurFieldColumn.getFieldName()); + } + + private CommandName getComposedCommandByAliasName(String _AliasName) + { + if (composedCommandNames != null) + { + CommandName curComposedName; + for (int i = 0; i < composedCommandNames.size(); i++) + { + curComposedName = (CommandName) composedCommandNames.elementAt(i); + if (curComposedName.getAliasName().equals(_AliasName)) + { + return curComposedName; + } + } + } + return null; + } + + public CommandName getComposedCommandByDisplayName(String _DisplayName) + { + if (composedCommandNames != null) + { + CommandName curComposedName; + for (int i = 0; i < composedCommandNames.size(); i++) + { + curComposedName = (CommandName) composedCommandNames.elementAt(i); + if (curComposedName.getDisplayName().equals(_DisplayName)) + { + return curComposedName; + } + } + } + return null; + } + + public String getuniqueAliasName(String _TableName) + { + int a = 0; + String AliasName = ""; + boolean bAliasNameexists = true; + String locAliasName = _TableName; + while (bAliasNameexists == true) + { + bAliasNameexists = (getComposedCommandByAliasName(locAliasName) != null); + if (bAliasNameexists) + { + a++; + locAliasName = _TableName + "_" + String.valueOf(a); + } + else + { + AliasName = locAliasName; + } + } + return AliasName; + } + + private String quoteName(String _sname) + { + return CommandName.quoteName(_sname, CurDBMetaData.getIdentifierQuote()); + } + + public void displaySQLErrorDialog(Exception _exception, XWindow _xParentWindow) + { + try + { + Object oErrorDialog = CurDBMetaData.xMSF.createInstance("com.sun.star.sdb.ErrorMessageDialog"); + XInitialization xInitialize = (XInitialization) UnoRuntime.queryInterface(XInitialization.class, oErrorDialog); + XExecutableDialog xExecute = (XExecutableDialog) UnoRuntime.queryInterface(XExecutableDialog.class, oErrorDialog); + PropertyValue[] rDispatchArguments = new PropertyValue[3]; + rDispatchArguments[0] = Properties.createProperty("Title", Configuration.getProductName(CurDBMetaData.xMSF) + " Base"); + rDispatchArguments[1] = Properties.createProperty("ParentWindow", _xParentWindow); + rDispatchArguments[2] = Properties.createProperty("SQLException", _exception); + xInitialize.initialize(rDispatchArguments); + xExecute.execute(); + //TODO dispose??? + } + catch (Exception typeexception) + { + typeexception.printStackTrace(System.out); + } + } +} diff --git a/wizards/com/sun/star/wizards/db/TableDescriptor.java b/wizards/com/sun/star/wizards/db/TableDescriptor.java new file mode 100644 index 000000000000..8e3b740417c4 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/TableDescriptor.java @@ -0,0 +1,861 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.wizards.db; + +import com.sun.star.awt.XWindow; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.sdbc.SQLException; +import com.sun.star.wizards.common.JavaTools; +import java.util.Vector; + +import com.sun.star.awt.VclWindowPeerAttribute; +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.ContainerEvent; +import com.sun.star.container.XContainer; +import com.sun.star.container.XContainerListener; +import com.sun.star.container.XHierarchicalNameAccess; +import com.sun.star.container.XIndexAccess; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.EventObject; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.sdbcx.KeyType; +import com.sun.star.sdbcx.XAppend; +import com.sun.star.sdbcx.XColumnsSupplier; +import com.sun.star.sdbcx.XDataDescriptorFactory; +import com.sun.star.sdbcx.XDrop; +import com.sun.star.sdbcx.XKeysSupplier; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.wizards.common.Desktop; +import com.sun.star.wizards.common.Properties; + +public class TableDescriptor extends CommandMetaData implements XContainerListener +{ + + XDataDescriptorFactory xTableDataDescriptorFactory; + XPropertySet xPropTableDataDescriptor; + private XNameAccess xNameAccessColumns; + private XIndexAccess xIndexAccessKeys; + public XDataDescriptorFactory xColumnDataDescriptorFactory; + XContainer xTableContainer; + XAppend xTableAppend; + XDrop xTableDrop; + private XAppend xKeyAppend; + private XDrop xKeyDrop; + private String[] sTableFilters = null; + private Vector columncontainer; + private Vector keycolumncontainer; + public XHierarchicalNameAccess xTableHierarchicalNameAccess; + private CommandName ComposedTableName; + private XAppend xKeyColAppend; + private XColumnsSupplier xKeyColumnSupplier; + private XPropertySet xKey; + private boolean bIDFieldisInserted = false; + private String IDFieldName = ""; + private String sColumnAlreadyExistsMessage = ""; +// private WizardDialog oUnoDialog; + private XWindow xWindow; + + /** + * @param xMSF + */ + public TableDescriptor(XMultiServiceFactory xMSF, XWindow _xWindow, String _sColumnAlreadyExistsMessage) + { + super(xMSF); + columncontainer = new Vector(); + keycolumncontainer = new Vector(); + sColumnAlreadyExistsMessage = _sColumnAlreadyExistsMessage; + xWindow = _xWindow; + } + + private class ColumnDescriptor + { + + String Name; + XPropertySet xColPropertySet; + + public ColumnDescriptor(XPropertySet _xColPropertySet, String _Name) + { + Name = _Name; + xColPropertySet = _xColPropertySet; + } + } + + public boolean getConnection(PropertyValue[] _curPropertyValue) + { + if (super.getConnection(_curPropertyValue)) + { + // XTablesSupplier xDBTables = (XTablesSupplier) UnoRuntime.queryInterface(XTablesSupplier.class, DBConnection); + // xTableNames = xDBTables.getTables(); + xTableAppend = UnoRuntime.queryInterface( XAppend.class, getTableNamesAsNameAccess() ); + xTableDrop = UnoRuntime.queryInterface( XDrop.class, getTableNamesAsNameAccess() ); + xTableDataDescriptorFactory = UnoRuntime.queryInterface( XDataDescriptorFactory.class, getTableNamesAsNameAccess() ); + xPropTableDataDescriptor = xTableDataDescriptorFactory.createDataDescriptor(); + XColumnsSupplier xColumnsSupplier = UnoRuntime.queryInterface( XColumnsSupplier.class, xPropTableDataDescriptor ); + xNameAccessColumns = xColumnsSupplier.getColumns(); + xColumnDataDescriptorFactory = UnoRuntime.queryInterface( XDataDescriptorFactory.class, xNameAccessColumns ); + try + { + createTypeInspector(); + sTableFilters = (String[]) AnyConverter.toArray(getDataSourcePropertySet().getPropertyValue("TableFilter")); + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + return true; + } + else + { + return false; + } + } + + private void removePrimaryKeys() + { + if (keycolumncontainer.size() > 0) + { + for (int i = (keycolumncontainer.size() - 1); i >= 0; i--) + { + keycolumncontainer.remove(i); + } + } + } + + public boolean createPrimaryKeys(String[] _fieldnames, boolean _bAutoincrementation) + { + try + { + XKeysSupplier xKeySupplier = (XKeysSupplier) UnoRuntime.queryInterface(XKeysSupplier.class, xPropTableDataDescriptor); + xIndexAccessKeys = xKeySupplier.getKeys(); + XDataDescriptorFactory xKeyFac = (XDataDescriptorFactory) UnoRuntime.queryInterface(XDataDescriptorFactory.class, xIndexAccessKeys); + xKeyDrop = (XDrop) UnoRuntime.queryInterface(XDrop.class, xIndexAccessKeys); + xKeyAppend = (XAppend) UnoRuntime.queryInterface(XAppend.class, xKeyFac); + xKey = xKeyFac.createDataDescriptor(); + xKey.setPropertyValue("Type", new Integer(KeyType.PRIMARY)); + xKeyColumnSupplier = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, xKey); + XDataDescriptorFactory xKeyColFac = (XDataDescriptorFactory) UnoRuntime.queryInterface(XDataDescriptorFactory.class, xKeyColumnSupplier.getColumns()); + xKeyColAppend = (XAppend) UnoRuntime.queryInterface(XAppend.class, xKeyColFac); + removePrimaryKeys(); + for (int i = 0; i < _fieldnames.length; i++) + { + XPropertySet xKeyColPropertySet = xKeyColFac.createDataDescriptor(); + xKeyColPropertySet.setPropertyValue("Name", _fieldnames[i]); + keycolumncontainer.add(xKeyColPropertySet); + XPropertySet xColPropertySet = null; + if (hasByName(_fieldnames[i])) + { + xColPropertySet = getByName(_fieldnames[i]); + } + else + { + xColPropertySet = addPrimaryKeyColumn(_fieldnames[i]); + } + xColPropertySet.setPropertyValue("IsNullable", new Integer(com.sun.star.sdbc.ColumnValue.NO_NULLS)); + if (_bAutoincrementation) + { + int nDataType = oTypeInspector.getAutoIncrementIndex(xColPropertySet); + if (nDataType != oTypeInspector.INVALID) + { + if (xColPropertySet.getPropertySetInfo().hasPropertyByName("IsAutoIncrement")) + { + xColPropertySet.setPropertyValue("Type", new Integer(nDataType)); + xColPropertySet.setPropertyValue("IsAutoIncrement", new Boolean(_bAutoincrementation)); + } + } + } + modifyColumn(_fieldnames[i], xColPropertySet); + } + return true; + } + catch (UnknownPropertyException e) + { + e.printStackTrace(System.out); + } + catch (PropertyVetoException e) + { + e.printStackTrace(System.out); + } + catch (IllegalArgumentException e) + { + e.printStackTrace(System.out); + } + catch (WrappedTargetException e) + { + e.printStackTrace(System.out); + } + + return false; + } + + public boolean isColunnNameDuplicate(XNameAccess _xColumns, XPropertySet _xToBeAppendedPropertySet) + { + try + { + String sColumnName = (String) AnyConverter.toString(_xToBeAppendedPropertySet.getPropertyValue("Name")); + if (_xColumns.hasByName(sColumnName)) + { + String sMessage = JavaTools.replaceSubString(sColumnAlreadyExistsMessage, sColumnName, "%FIELDNAME"); + showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, sMessage); + return true; + } + return false; + } + catch (Exception ex) + { + ex.printStackTrace(System.out); + return false; + } + } + + /** + * creates the table under the passed name + * @param _catalogname + * @param _schemaname + * @param _tablename is made unique if necessary + * @param _fieldnames + * @return true or false to indicate successful creation or not + */ + public boolean createTable(String _catalogname, String _schemaname, String _tablename, String[] _fieldnames) + { + boolean breturn = true; + try + { + XAppend xAppendColumns = (XAppend) UnoRuntime.queryInterface(XAppend.class, xNameAccessColumns); + for (int i = 0; i < columncontainer.size(); i++) + { + XPropertySet xColPropertySet = getByIndex(i); + if (!isColunnNameDuplicate(xNameAccessColumns, xColPropertySet)) + { + xAppendColumns.appendByDescriptor(xColPropertySet); //xColPropertySet.setPropertyValue("Type", new Integer(32423)) + } + else + { + breturn = false; + } + } + if (breturn) + { + assignTableProperty("Name", _tablename); + assignTableProperty("CatalogName", _catalogname); + assignTableProperty("SchemaName", _schemaname); + xTableContainer = (XContainer) UnoRuntime.queryInterface(XContainer.class, getTableNamesAsNameAccess()); + xTableContainer.addContainerListener(this); + if (keycolumncontainer.size() > 0) + { + for (int i = 0; i < keycolumncontainer.size(); i++) + { + XPropertySet xKeyColPropertySet = (XPropertySet) keycolumncontainer.get(i); + if (!isColunnNameDuplicate(xKeyColumnSupplier.getColumns(), xKeyColPropertySet)) + { + xKeyColAppend.appendByDescriptor(xKeyColPropertySet); + } + else + { + breturn = false; + } + } + if (breturn) + { + xKeyAppend.appendByDescriptor(xKey); + } + } + if (breturn) + { + // TODO: LLA: describe what is he doing here. + xTableAppend.appendByDescriptor(xPropTableDataDescriptor); + } + } + } + catch (SQLException oSQLException) + { + super.callSQLErrorMessageDialog(oSQLException, xWindow); + breturn = false; + } + catch (Exception e) + { + e.printStackTrace(System.out); + breturn = false; + } + if (!breturn) + { + removeAllColumnsFromDescriptor(_tablename); + this.removePrimaryKeys(); + } + return breturn; + } + + private boolean removeAllColumnsFromDescriptor(String _tablename) + { + try + { + xPropTableDataDescriptor.setPropertyValue("Name", ""); + if ((xKeyDrop != null) && (xIndexAccessKeys != null)) + { + int icount = xIndexAccessKeys.getCount(); + if (icount > 0) + { + for (int i = xIndexAccessKeys.getCount() - 1; i >= 0; i--) + { + xKeyDrop.dropByIndex(i); + } + } + } + XDrop xColumnDrop = (XDrop) UnoRuntime.queryInterface(XDrop.class, xNameAccessColumns); + for (int i = xNameAccessColumns.getElementNames().length - 1; i >= 0; i--) + { + xColumnDrop.dropByIndex(i); + } + if (xTableDrop != null) + { + if (getTableNamesAsNameAccess().hasByName(_tablename)) + { + xTableDrop.dropByName(_tablename); + } + } + if (bIDFieldisInserted) + { + this.dropColumnbyName(this.IDFieldName); + bIDFieldisInserted = false; + } + return false; + } + catch (SQLException oSQLException) + { + super.callSQLErrorMessageDialog(oSQLException, xWindow); + } + catch (Exception e1) + { + e1.printStackTrace(System.out); + } + return false; + } + + public boolean createTable(String _catalogname, String _schemaname, String _tablename, String[] _keycolumnnames, boolean _bAutoincrementation, String[] _fieldnames) + { + if (createPrimaryKeys(_keycolumnnames, _bAutoincrementation)) + { + return createTable(_catalogname, _schemaname, _tablename, _fieldnames); + } + return false; + } + + private void assignTableProperty(String _spropname, String _svalue) + { + if (_svalue != null) + { + if (!_svalue.equals("")) + { + try + { + xPropTableDataDescriptor.setPropertyValue(_spropname, _svalue); + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + } + } + } + + public boolean modifyColumnName(String _soldname, String _snewname) + { + try + { + return modifyColumn(_soldname, "Name", _snewname); + } + catch (Exception e) + { + e.printStackTrace(System.out); + showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, e.getMessage()); + return false; + } + } + + public boolean modifyColumn(String _sname, String _spropname, Object _oValue) + { + try + { + if (this.columncontainer.size() > 0) + { + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); + if (oColumnDescriptor.Name.equals(_sname)) + { + oColumnDescriptor.xColPropertySet.setPropertyValue(_spropname, _oValue); + if (_spropname.equals("Name")) + { + oColumnDescriptor.Name = (String) _oValue; + } + columncontainer.remove(i); + columncontainer.insertElementAt(oColumnDescriptor, i); + return true; + } + } + } + } + catch (UnknownPropertyException e) + { + e.printStackTrace(System.out); + } + catch (PropertyVetoException e) + { + e.printStackTrace(System.out); + } + catch (IllegalArgumentException e) + { + e.printStackTrace(System.out); + } + catch (WrappedTargetException e) + { + e.printStackTrace(System.out); + } + return false; + } + + public boolean modifyColumn(String _sname, XPropertySet _xColPropertySet) + { + try + { + if (this.columncontainer.size() > 0) + { + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); + if (oColumnDescriptor.Name.equals(_sname)) + { + oColumnDescriptor.xColPropertySet = _xColPropertySet; + oColumnDescriptor.Name = (String) _xColPropertySet.getPropertyValue("Name"); + columncontainer.remove(i); + columncontainer.insertElementAt(oColumnDescriptor, i); + return true; + } + } + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + return false; + } + + public void dropColumnbyName(String _sname) + { + try + { + if (columncontainer.size() > 0) + { + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); + if (oColumnDescriptor != null) + { + if (oColumnDescriptor.Name.equals(_sname)) + { + columncontainer.remove(i); + } + } + } + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + } + + public String[] getColumnNames() + { + if (columncontainer.size() > 0) + { + try + { + String[] fieldnames = new String[columncontainer.size()]; + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); + fieldnames[i] = oColumnDescriptor.Name; + } + return fieldnames; + } + catch (RuntimeException e) + { + e.printStackTrace(System.out); + } + } + return new String[] + { + }; + } + + private boolean hasByName(String _fieldname) + { + try + { + if (columncontainer.size() > 0) + { + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); + if (oColumnDescriptor.Name.equals(_fieldname)) + { + return true; + } + } + } + } + catch (RuntimeException e) + { + e.printStackTrace(System.out); + } + return false; + } + + private ColumnDescriptor getColumnDescriptorByName(String _fieldname) + { + try + { + if (this.columncontainer.size() > 0) + { + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); + if (oColumnDescriptor.Name.equals(_fieldname)) + { + return oColumnDescriptor; + } + } + } + } + catch (RuntimeException e) + { + e.printStackTrace(System.out); + } + return null; + } + + public XPropertySet getByName(String _fieldname) + { + ColumnDescriptor oColumnDescriptor = getColumnDescriptorByName(_fieldname); + if (oColumnDescriptor != null) + { + return oColumnDescriptor.xColPropertySet; + } + else + { + return null; + } + } + + private XPropertySet getByIndex(int _index) + { + try + { + if (columncontainer.size() > _index) + { + ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(_index); + return oColumnDescriptor.xColPropertySet; + } + } + catch (RuntimeException e) + { + e.printStackTrace(System.out); + } + return null; + } + + public XPropertySet clonePropertySet(String _snewname, XPropertySet _xnewPropertySet) + { + XPropertySet xRetPropertySet = xColumnDataDescriptorFactory.createDataDescriptor(); + try + { + if (hasByName(_snewname)) + { + Object oColumn = getByName(_snewname); + XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oColumn); + Property[] aColProperties = xPropertySet.getPropertySetInfo().getProperties(); + for (int i = 0; i < aColProperties.length; i++) + { + String sPropName = aColProperties[i].Name; + Object oColValue = _xnewPropertySet.getPropertyValue(sPropName); + xRetPropertySet.setPropertyValue(sPropName, oColValue); + } + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + return xRetPropertySet; + } + + public boolean addColumn(PropertyValue[] _aNewPropertyValues) + { + try + { + String sname = (String) Properties.getPropertyValue(_aNewPropertyValues, "Name"); + if (!hasByName(sname)) + { + ColumnPropertySet oPropertySet = new ColumnPropertySet(oTypeInspector, xColumnDataDescriptorFactory.createDataDescriptor()); + oPropertySet.assignPropertyValues(_aNewPropertyValues, true); + ColumnDescriptor oColumnDescriptor = new ColumnDescriptor(oPropertySet.xPropertySet, sname); + this.columncontainer.add(oColumnDescriptor); + return true; + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + return false; + } + + public boolean moveColumn(int _nOldIndex, int _nNewIndex) + { + try + { + ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) this.columncontainer.get(_nOldIndex); + this.columncontainer.remove(_nOldIndex); + columncontainer.add(_nNewIndex, oColumnDescriptor); + return true; + } + catch (Exception e) + { + e.printStackTrace(System.out); + return false; + } + } + + public boolean addColumn(String _columnname, XPropertySet _xNewColPropertySet) + { + try + { + if (!hasByName(_columnname)) + { + if (_columnname.equals("")) + { + return false; + } + else + { + ColumnPropertySet oPropertySet = new ColumnPropertySet(oTypeInspector, xColumnDataDescriptorFactory.createDataDescriptor()); + oPropertySet.assignNewPropertySet(_columnname, _xNewColPropertySet); + ColumnDescriptor oColumnDescriptor = new ColumnDescriptor(oPropertySet.xPropertySet, _columnname); + columncontainer.add(oColumnDescriptor); + return true; + } + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + return false; + } + + public XPropertySet addPrimaryKeyColumn(String _columnname) + { + try + { + if (!hasByName(_columnname)) + { + try + { + XPropertySet xColPropertySet = xColumnDataDescriptorFactory.createDataDescriptor(); + IDFieldName = Desktop.getUniqueName(getColumnNames(), _columnname, ""); + xColPropertySet.setPropertyValue("Name", IDFieldName); + + int nDataType = oTypeInspector.convertDataType(com.sun.star.sdbc.DataType.INTEGER); + xColPropertySet.setPropertyValue("Type", new Integer(nDataType)); + xColPropertySet.setPropertyValue("TypeName", oTypeInspector.getDefaultTypeName(nDataType, null)); + ColumnDescriptor oColumnDescriptor = new ColumnDescriptor(xColPropertySet, IDFieldName); + this.columncontainer.add(0, oColumnDescriptor); + this.bIDFieldisInserted = true; + return xColPropertySet; + } + catch (RuntimeException e1) + { + e1.printStackTrace(System.out); + } + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + return null; + } + + public String[] getNonBinaryFieldNames() + { + Vector NonBinaryFieldNameVector = new Vector(); + try + { + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = (ColumnDescriptor) columncontainer.get(i); + XPropertySet xColPropertySet = getByName(oColumnDescriptor.Name); + Property[] aProperties = xColPropertySet.getPropertySetInfo().getProperties(); + int itype; + try + { + itype = AnyConverter.toInt(xColPropertySet.getPropertyValue("Type")); + if (!isBinaryDataType(itype)) + { + NonBinaryFieldNameVector.addElement(oColumnDescriptor.Name); + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + } + } + catch (RuntimeException e) + { + e.printStackTrace(System.out); + } + String[] sbinaryfieldnames = new String[NonBinaryFieldNameVector.size()]; + NonBinaryFieldNameVector.toArray(sbinaryfieldnames); + return sbinaryfieldnames; + } + + public String getComposedTableName(String _scatalogname, String _sschemaname, String _stablename) + { + ComposedTableName = new CommandName(this, _scatalogname, _sschemaname, _stablename, false); + return ComposedTableName.getComposedName(); + } + + public String getComposedTableName() + { + if (ComposedTableName != null) + { + return this.ComposedTableName.getComposedName(); + } + else + { + return null; + } + } + + /* (non-Javadoc) + * @see com.sun.star.container.XContainerListener#elementInserted(com.sun.star.container.ContainerEvent) + */ + public void elementInserted(ContainerEvent arg0) + { + try + { + XPropertySet xTablePropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, arg0.Element); + String stablename = AnyConverter.toString(xTablePropertySet.getPropertyValue("Name")); + String sschemaname = AnyConverter.toString(xPropTableDataDescriptor.getPropertyValue("SchemaName")); + String scatalogname = AnyConverter.toString(xPropTableDataDescriptor.getPropertyValue("CatalogName")); + ComposedTableName = new CommandName(this, scatalogname, sschemaname, stablename, false); + appendTableNameToFilter(ComposedTableName.getComposedName()); + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + } + + /* (non-Javadoc) + * @see com.sun.star.container.XContainerListener#elementRemoved(com.sun.star.container.ContainerEvent) + */ + public void elementRemoved(ContainerEvent arg0) + { + } + + /* (non-Javadoc) + * @see com.sun.star.container.XContainerListener#elementReplaced(com.sun.star.container.ContainerEvent) + */ + public void elementReplaced(ContainerEvent arg0) + { + } + + /* (non-Javadoc) + * @see com.sun.star.lang.XEventListener#disposing(com.sun.star.lang.EventObject) + */ + public void disposing(EventObject arg0) + { + } + + /** + * @param _stablename + * @return + */ + public boolean appendTableNameToFilter(String _scomposedtablename) + { + boolean bhastoinsert = true; + for (int i = 0; i < sTableFilters.length; i++) + { + if (sTableFilters[i].compareTo("%") > -1) + { + if (sTableFilters[i].endsWith("." + _scomposedtablename)) + { + bhastoinsert = false; + } + else if (sTableFilters[i].length() == 1) + { + bhastoinsert = false; + } + } + else if (sTableFilters[i].equals(_scomposedtablename)) + { + bhastoinsert = false; + } + if (!bhastoinsert) + { + break; + } + } + if (bhastoinsert) + { + String[] sNewTableFilters = new String[sTableFilters.length + 1]; + System.arraycopy(sTableFilters, 0, sNewTableFilters, 0, sTableFilters.length); + sNewTableFilters[sTableFilters.length] = _scomposedtablename; + sTableFilters = sNewTableFilters; + try + { + getDataSourcePropertySet().setPropertyValue("TableFilter", sTableFilters); + } + catch (Exception e) + { + e.printStackTrace(System.out); + bhastoinsert = false; + } + } + return bhastoinsert; + } +} + diff --git a/wizards/com/sun/star/wizards/db/TypeInspector.java b/wizards/com/sun/star/wizards/db/TypeInspector.java new file mode 100644 index 000000000000..1f22801fd8c5 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/TypeInspector.java @@ -0,0 +1,465 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.wizards.db; + +import java.util.Vector; + +import com.sun.star.beans.XPropertySet; +import com.sun.star.sdbc.ColumnSearch; +import com.sun.star.sdbc.ColumnValue; +import com.sun.star.sdbc.DataType; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbc.XResultSet; +import com.sun.star.sdbc.XRow; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.wizards.common.JavaTools; + +public class TypeInspector +{ + + private String[] sDataTypeNames; + private int[] nDataTypeInfos; + private int[] nPrecisionInfos; + private int[] nNullableInfos; + private int[] nSearchables; + private boolean[] bisAutoIncrementableInfos; + private int[] nMinScaleInfos; + private int[] nMaxScaleInfos; + private int[] nNumericFallBackList = new int[] + { + DataType.INTEGER, DataType.FLOAT, DataType.REAL, DataType.DOUBLE, DataType.NUMERIC, DataType.DECIMAL + }; + final int INVALID = 999999; + XResultSet xResultSet; + + public class TypeInfo + { + + public int nDataType; + public String sDataTypeName; + public boolean bisAutoIncrementable; + + public TypeInfo(int _nDataType, String _sDataTypeName, boolean _bisAutoIncrementable) + { + nDataType = _nDataType; + sDataTypeName = _sDataTypeName; + bisAutoIncrementable = _bisAutoIncrementable; + } + } + + public TypeInspector(XResultSet _xResultSet) + { + try + { + xResultSet = _xResultSet; + Vector<String> aTypeNameVector = new Vector<String>(); + Vector<Integer> aTypeVector = new Vector<Integer>(); + Vector<Integer> aNullableVector = new Vector<Integer>(); + Vector<Boolean> aAutoIncrementVector = new Vector<Boolean>(); + Vector<Integer> aPrecisionVector = new Vector<Integer>(); + Vector<Integer> aMinScaleVector = new Vector<Integer>(); + Vector<Integer> aMaxScaleVector = new Vector<Integer>(); + Vector<Integer> aSearchableVector = new Vector<Integer>(); + // Integer[] aIntegerDataTypes = null; +// XResultSet xResultSet = xDBMetaDagetTypeInfo(); + XRow xRow = (XRow) UnoRuntime.queryInterface(XRow.class, xResultSet); + while (xResultSet.next()) + { + aTypeNameVector.addElement(new String(xRow.getString(1))); + aTypeVector.addElement(new Integer(xRow.getShort(2))); + aPrecisionVector.addElement(new Integer(xRow.getInt(3))); + aNullableVector.addElement(new Integer(xRow.getShort(7))); + aSearchableVector.addElement(new Integer(xRow.getShort(9))); + aAutoIncrementVector.addElement(new Boolean(xRow.getBoolean(12))); + aMinScaleVector.addElement(new Integer(xRow.getShort(14))); + aMaxScaleVector.addElement(new Integer(xRow.getShort(15))); + + } + sDataTypeNames = new String[aTypeNameVector.size()]; + aTypeNameVector.toArray(sDataTypeNames); + nDataTypeInfos = JavaTools.IntegerTointList(aTypeVector); + nNullableInfos = JavaTools.IntegerTointList(aNullableVector); + nSearchables = JavaTools.IntegerTointList(aSearchableVector); + bisAutoIncrementableInfos = JavaTools.BooleanTobooleanList(aAutoIncrementVector); + nPrecisionInfos = JavaTools.IntegerTointList(aPrecisionVector); + nMinScaleInfos = JavaTools.IntegerTointList(aMinScaleVector); + nMaxScaleInfos = JavaTools.IntegerTointList(aMaxScaleVector); + } + catch (SQLException e) + { + e.printStackTrace(System.out); + } + } + + public int getScale(XPropertySet _xColPropertySet) + { + try + { + int i = getDataTypeIndex(_xColPropertySet, false); + int nScale = AnyConverter.toInt(_xColPropertySet.getPropertyValue("Scale")); + if (i == -1) + { + return nScale; + } + if (nScale > nMaxScaleInfos[i]) + { + return nMaxScaleInfos[i]; + } + else if (nScale < nMinScaleInfos[i]) + { + return nMinScaleInfos[i]; + } + else + { + return nScale; + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + return 0; + } + } + + public int getNullability(XPropertySet _xColPropertySet, int _nNullable) + { + int i = getDataTypeIndex(_xColPropertySet, false); + if (i == -1) + { + return ColumnValue.NO_NULLS; + } + int nNullable = _nNullable; + if (nNullable == ColumnValue.NULLABLE) + { + return nNullableInfos[i]; //probably nullability is not allowed + } + return nNullable; + } + + public int getNullability(XPropertySet _xColPropertySet) + { + try + { + int i = getDataTypeIndex(_xColPropertySet, false); + if (i == -1) + { + return ColumnValue.NO_NULLS; + } + int nNullable = AnyConverter.toInt(_xColPropertySet.getPropertyValue("IsNullable")); + if (nNullable == ColumnValue.NULLABLE) + { + return nNullableInfos[i]; + } + return nNullable; + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + return ColumnValue.NO_NULLS; + } + + public boolean isColumnOrderable(XPropertySet _xColPropertySet) + { + int i = getDataTypeIndex(_xColPropertySet, false); + if (i > -1) + { + return (nSearchables[i] != ColumnSearch.NONE); + } + else + { + return false; + } + } + + public int isNullable(XPropertySet _xColPropertySet) + { + int i = getDataTypeIndex(_xColPropertySet, false); + if (i > -1) + { + return nNullableInfos[i]; + } + else + { + return ColumnValue.NO_NULLS; + } + } + + private int getDataTypeIndex(XPropertySet _xColPropertySet, boolean _bCheckNumericAttributes) + { + try + { + int nPrecision = -1; + int nScale = -1; + int nDataType = AnyConverter.toInt(_xColPropertySet.getPropertyValue("Type")); + String sTypeName = AnyConverter.toString(_xColPropertySet.getPropertyValue("TypeName")); + if (_bCheckNumericAttributes) + { + nPrecision = AnyConverter.toInt(_xColPropertySet.getPropertyValue("Precision")); + nScale = AnyConverter.toInt(_xColPropertySet.getPropertyValue("Scale")); + } + boolean bleaveloop = false; + int startindex = 0; + while (!bleaveloop) + { + int i = JavaTools.FieldInIntTable(nDataTypeInfos, nDataType, startindex); + startindex = i + 1; + bleaveloop = (i < 0); + if (!bleaveloop) + { + if (sTypeName.equals(sDataTypeNames[i])) + { + if (_bCheckNumericAttributes) + { + if (nPrecision <= nPrecisionInfos[i]) + { + if ((nScale >= nMinScaleInfos[i]) && (nScale <= nMinScaleInfos[i])) + { + return i; + } + } + } + else + { + return i; + } + } + } + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + return -1; + } + + public boolean supportsDataType(int _curDataType) + { + return (JavaTools.FieldInIntTable(nDataTypeInfos, _curDataType) > -1); + } + + public int getLastConversionFallbackDataType() + { + if (supportsDataType(DataType.VARCHAR)) + { + return DataType.VARCHAR; + } + else + { + return DataType.LONGVARCHAR; + } + } + + /** + * an empty string is returned when no appropriate Typename can be found + * finds the first TypeName of the passed datatype. + * @param _curDataType + * @return + */ + public String getDefaultTypeName(int _curDataType, Integer precision) + { + String ret = ""; + for (int i = 0; i < nDataTypeInfos.length; i++) + { + if (nDataTypeInfos[i] == _curDataType) + { +// System.out.println( "Desired prec " + precision + ",nPrecisionInfos[i]="+nPrecisionInfos[i] + ",sDataTypeNames[i]="+sDataTypeNames[i] ); + + if (precision == null || nPrecisionInfos[i] >= precision.intValue()) + { + ret = sDataTypeNames[i]; // this fits best ! + break; + } + else if (ret.length() == 0) + { + // in case we dont find anything else, we at return a typename + // with the correct class + ret = sDataTypeNames[i]; + } + } + } +// System.out.println( "_curDataType="+_curDataType+",precision="+precision+",ret="+ + return ret; + } + + public int getDataType(String _sTypeName) + { + int i = JavaTools.FieldInList(sDataTypeNames, _sTypeName); + if (i > -1) + { + return nDataTypeInfos[i]; + } + else + { + return getLastConversionFallbackDataType(); + } + } + + public int convertDataType(int _curDataType) + { + int retDataType = _curDataType; + if (!supportsDataType(_curDataType)) + { + switch (_curDataType) + { + case DataType.BIT: + retDataType = convertDataType(DataType.BOOLEAN); + break; + case DataType.BOOLEAN: + retDataType = convertDataType(DataType.BIT); + break; + case DataType.TINYINT: + retDataType = convertDataType(DataType.SMALLINT); + break; + case DataType.SMALLINT: + retDataType = convertDataType(DataType.INTEGER); + break; + case DataType.INTEGER: + retDataType = convertDataType(DataType.FLOAT); + break; + case DataType.FLOAT: + retDataType = convertDataType(DataType.REAL); + break; + case DataType.DATE: + case DataType.TIME: + retDataType = convertDataType(DataType.TIMESTAMP); + break; + case DataType.TIMESTAMP: + case DataType.REAL: + case DataType.BIGINT: + retDataType = convertDataType(DataType.DOUBLE); + break; + case DataType.DOUBLE: + retDataType = convertDataType(DataType.NUMERIC); + break; + case DataType.NUMERIC: + retDataType = convertDataType(DataType.DECIMAL); + break; + case DataType.DECIMAL: + if (supportsDataType(DataType.DOUBLE)) + { + retDataType = convertDataType(DataType.DOUBLE); + } + else if (supportsDataType(DataType.NUMERIC)) + { + retDataType = DataType.NUMERIC; + } + else + { + retDataType = getLastConversionFallbackDataType(); + } + break; + case DataType.VARCHAR: + retDataType = getLastConversionFallbackDataType(); + break; + default: + retDataType = getLastConversionFallbackDataType(); + } + } + return retDataType; + } + + public int getAutoIncrementIndex(XPropertySet _xColPropertySet) + { + try + { + boolean bleaveloop = false; + int startindex = 0; + int curDataType = ((Integer) _xColPropertySet.getPropertyValue("Type")).intValue(); + while (!bleaveloop) + { + int i = JavaTools.FieldInIntTable(nDataTypeInfos, curDataType, startindex); + startindex = i + 1; + bleaveloop = (i == -1); + if (!bleaveloop) + { + if (bisAutoIncrementableInfos[i]) + { + return nDataTypeInfos[i]; + } + } + } + } + catch (Exception e) + { + e.printStackTrace(System.out); + } + return INVALID; + + } + + public boolean isAutoIncrementable(XPropertySet _xColPropertySet) + { + return (getAutoIncrementIndex(_xColPropertySet) != INVALID); + } + + /** finds the first available DataType that can be used as a primary key in a table. + * @return The first datatype that also supports Autoincrmentation is taken according to the following list: + *1) INTEGER + *2) FLOAT + *3) REAL + *4) DOUBLE + *5) NUMERIC + *6) DECIMAL * + * If no appropriate datatype is found ther first available numeric type after DataType.INTEGER + * according to the 'convertDataType' method is returned + */ + /**TODO the fallback order is the same as implemented in the method 'convertDataType'. + * It's not very elegant to have the same intelligence + * on several spots in the class!! + * + */ + public TypeInfo findAutomaticPrimaryKeyType() + { + int nDataType; + for (int n = 0; n < this.nNumericFallBackList.length; n++) + { + nDataType = nNumericFallBackList[n]; + boolean bleaveloop = false; + int startindex = 0; + while (!bleaveloop) + { + int i = JavaTools.FieldInIntTable(nDataTypeInfos, nDataType, startindex); + bleaveloop = (i < 0); + if (!bleaveloop) + { + if (this.bisAutoIncrementableInfos[i]) + { + return new TypeInfo(nDataType, this.sDataTypeNames[i], true); + } + startindex = i + 1; + } + startindex = i + 1; + } + } + // As Autoincrementation is not supported for any numeric datatype we take the first available numeric Type; + nDataType = convertDataType(DataType.INTEGER); + return new TypeInfo(nDataType, getDefaultTypeName(nDataType, null), false); + } +} |