Search in sources :

Example 6 with SetCondition

use of com.servoy.j2db.query.SetCondition in project servoy-client by Servoy.

the class SQLGenerator method isDynamicPKSetCondition.

static boolean isDynamicPKSetCondition(ISQLCondition condition) {
    if (condition instanceof SetCondition) {
        Object values = ((SetCondition) condition).getValues();
        if (!(values instanceof Placeholder)) {
            return false;
        }
        IPlaceholderKey key = ((Placeholder) values).getKey();
        if (!(key instanceof TablePlaceholderKey)) {
            return false;
        }
        if (!SQLGenerator.PLACEHOLDER_FOUNDSET_PKS.equals(((TablePlaceholderKey) key).getName())) {
            return false;
        }
        return true;
    }
    return false;
}
Also used : Placeholder(com.servoy.j2db.query.Placeholder) TablePlaceholderKey(com.servoy.j2db.query.TablePlaceholderKey) SetCondition(com.servoy.j2db.query.SetCondition) IPlaceholderKey(com.servoy.j2db.query.IPlaceholderKey)

Example 7 with SetCondition

use of com.servoy.j2db.query.SetCondition in project servoy-client by Servoy.

the class SQLGenerator method getEmptyDataSetForDummyQuery.

/**
 * check if the query is will never return any rows, in that case just return an empty dataset.
 */
public static IDataSet getEmptyDataSetForDummyQuery(ISQLSelect sqlSelect) {
    if (sqlSelect instanceof QuerySelect && ((QuerySelect) sqlSelect).getCondition(CONDITION_SEARCH) != null) {
        // all named conditions in QuerySelecta are AND-ed, if one always results to false, skip the query
        for (IBaseSQLCondition condition : ((QuerySelect) sqlSelect).getCondition(CONDITION_SEARCH).getConditions()) {
            boolean skipQuery = false;
            if (condition instanceof SetCondition && ((SetCondition) condition).isAndCondition()) {
                // check for EQUALS_OPERATOR
                int ncols = ((SetCondition) condition).getKeys().length;
                int[] operators = ((SetCondition) condition).getOperators();
                boolean eqop = true;
                for (int i = 0; i < ncols; i++) {
                    if (operators[i] != IBaseSQLCondition.EQUALS_OPERATOR) {
                        eqop = false;
                    }
                }
                if (eqop) {
                    Object value = ((SetCondition) condition).getValues();
                    if (value instanceof Placeholder) {
                        Object phval = ((Placeholder) value).getValue();
                        // cleared foundset
                        skipQuery = phval instanceof DynamicPkValuesArray && ((DynamicPkValuesArray) phval).getPKs().getRowCount() == 0;
                    } else if (value instanceof Object[][]) {
                        skipQuery = ((Object[][]) value).length == 0 || ((Object[][]) value)[0].length == 0;
                    }
                }
            }
            if (skipQuery) {
                // no need to query, dummy condition (where 1=2) here
                List<IQuerySelectValue> columns = ((QuerySelect) sqlSelect).getColumns();
                String[] columnNames = new String[columns.size()];
                ColumnType[] columnTypes = new ColumnType[columns.size()];
                for (int i = 0; i < columns.size(); i++) {
                    IQuerySelectValue col = columns.get(i);
                    columnNames[i] = col.getAliasOrName();
                    BaseColumnType columnType = col.getColumnType();
                    columnTypes[i] = columnType == null ? ColumnType.getInstance(Types.OTHER, 0, 0) : ColumnType.getInstance(columnType.getSqlType(), columnType.getLength(), columnType.getScale());
                }
                return BufferedDataSetInternal.createBufferedDataSet(columnNames, columnTypes, new SafeArrayList<Object[]>(0), false);
            }
        }
    }
    // query needs to be run
    return null;
}
Also used : Placeholder(com.servoy.j2db.query.Placeholder) ColumnType(com.servoy.j2db.query.ColumnType) BaseColumnType(com.servoy.base.query.BaseColumnType) IBaseSQLCondition(com.servoy.base.query.IBaseSQLCondition) SetCondition(com.servoy.j2db.query.SetCondition) QuerySelect(com.servoy.j2db.query.QuerySelect) BaseColumnType(com.servoy.base.query.BaseColumnType) IQuerySelectValue(com.servoy.j2db.query.IQuerySelectValue)

Example 8 with SetCondition

use of com.servoy.j2db.query.SetCondition in project servoy-client by Servoy.

the class SQLGenerator method createRelatedCondition.

public static ISQLCondition createRelatedCondition(IServiceProvider app, Relation relation, QueryTable foreignTable) throws RepositoryException {
    IDataProvider[] primary = relation.getPrimaryDataProviders(app.getFlattenedSolution());
    Column[] foreign = relation.getForeignColumns(app.getFlattenedSolution());
    int[] operators = relation.getOperators();
    IQuerySelectValue[] keys = new IQuerySelectValue[primary.length];
    int[] swapped = new int[primary.length];
    for (int x = 0; x < primary.length; x++) {
        // need all keys as columns on the left side......
        int operator = RelationItem.swapOperator(operators[x]);
        if (operator == -1) {
            throw new RepositoryException("Cannot swap relation operator for relation " + relation.getName());
        }
        // column = ? construct
        IQuerySelectValue key = foreign[x].queryColumn(foreignTable);
        // When we have a text and non-text column we can cast the non-text column to string
        int primaryType = primary[x].getDataProviderType();
        int foreignType = mapToDefaultType(key.getColumn().getColumnType());
        if (!"uuid".equalsIgnoreCase(key.getColumn().getNativeTypename()) && foreignType == IColumnTypes.TEXT && primaryType != IColumnTypes.TEXT && primaryType != 0) {
            // key is text, value is non-text, cast the value to text when we supply it
            operator |= IBaseSQLCondition.CAST_TO_MODIFIER;
        } else if (primaryType == IColumnTypes.TEXT && foreignType != IColumnTypes.TEXT) {
            // value is text, key is non-text, cast the key to text
            key = new QueryFunction(cast, new IQuerySelectValue[] { key, new QueryColumnValue(IQueryConstants.TYPE_STRING, null, true) }, null);
        }
        keys[x] = key;
        swapped[x] = operator;
    }
    return new SetCondition(swapped, keys, new Placeholder(createRelationKeyPlaceholderKey(foreignTable, relation.getName())), true);
}
Also used : Placeholder(com.servoy.j2db.query.Placeholder) RepositoryException(com.servoy.j2db.persistence.RepositoryException) IDataProvider(com.servoy.j2db.persistence.IDataProvider) SetCondition(com.servoy.j2db.query.SetCondition) QueryColumnValue(com.servoy.j2db.query.QueryColumnValue) QueryColumn(com.servoy.j2db.query.QueryColumn) BaseQueryColumn(com.servoy.base.query.BaseQueryColumn) IColumn(com.servoy.j2db.persistence.IColumn) Column(com.servoy.j2db.persistence.Column) QueryFunction(com.servoy.j2db.query.QueryFunction) IQuerySelectValue(com.servoy.j2db.query.IQuerySelectValue)

Example 9 with SetCondition

use of com.servoy.j2db.query.SetCondition in project servoy-client by Servoy.

the class SQLGenerator method createConditionFromFindState.

private ISQLCondition createConditionFromFindState(FindState s, QuerySelect sqlSelect, IGlobalValueEntry provider, List<IQuerySelectValue> pkQueryColumns) throws RepositoryException {
    ISQLCondition and = null;
    List<RelatedFindState> relatedFindStates = s.createFindStateJoins(sqlSelect, Collections.<IRelation>emptyList(), sqlSelect.getTable(), provider);
    for (int i = 0; relatedFindStates != null && i < relatedFindStates.size(); i++) {
        RelatedFindState rfs = relatedFindStates.get(i);
        FindState state = rfs.getFindState();
        BaseQueryTable columnTable = rfs.getPrimaryTable();
        SQLSheet sheet = state.getParentFoundSet().getSQLSheet();
        Table table = sheet.getTable();
        Iterator<Map.Entry<String, Object>> it = state.getColumnData().entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> elem = it.next();
            final String dataProviderID = elem.getKey();
            Object raw = elem.getValue();
            if (raw == null)
                continue;
            int dataProviderType = -1;
            ConverterInfo columnConverterInfo = null;
            IColumnConverter columnConverter = null;
            IQuerySelectValue qCol = null;
            IColumn c = table.getColumn(dataProviderID);
            if (c != null) {
                dataProviderType = c.getDataProviderType();
                columnConverterInfo = sheet.getColumnConverterInfo(dataProviderID);
                if (columnConverterInfo != null) {
                    columnConverter = application.getFoundSetManager().getColumnConverterManager().getConverter(columnConverterInfo.converterName);
                    if (columnConverter instanceof ITypedColumnConverter) {
                        int convType = ((ITypedColumnConverter) columnConverter).getToObjectType(columnConverterInfo.props);
                        if (convType != Integer.MAX_VALUE) {
                            dataProviderType = mapToDefaultType(convType);
                        }
                    }
                }
                // a column
                qCol = ((Column) c).queryColumn(columnTable);
            } else {
                // not a column, check for aggregates
                Iterator<AggregateVariable> aggregateVariables = application.getFlattenedSolution().getAggregateVariables(sheet.getTable(), false);
                while (c == null && aggregateVariables.hasNext()) {
                    AggregateVariable agg = aggregateVariables.next();
                    if (dataProviderID.equals(agg.getDataProviderID())) {
                        // found aggregate
                        c = agg;
                    }
                }
                if (c != null) {
                    dataProviderType = c.getDataProviderType();
                    Map<String, QuerySelect> aggregates = sheet.getAggregates();
                    if (aggregates != null) {
                        QuerySelect aggregateSelect = aggregates.get(dataProviderID);
                        if (aggregateSelect != null) {
                            qCol = ((List<IQuerySelectValue>) AbstractBaseQuery.relinkTable(aggregateSelect.getTable(), columnTable, aggregateSelect.getColumnsClone())).get(0);
                        }
                    }
                }
            }
            if (qCol == null) {
                // not a column and not an aggregate
                // $NON-NLS-1$ //$NON-NLS-2$
                Debug.log("Ignoring search on unknown/unsupported data provider '" + dataProviderID + "'");
                continue;
            }
            ParsedFormat format = state.getFormat(dataProviderID);
            String formatString = null;
            if (format != null) {
                formatString = format.getEditFormat();
                if (formatString == null) {
                    formatString = format.getDisplayFormat();
                }
            }
            if (Utils.stringIsEmpty(formatString)) {
                formatString = TagResolver.getDefaultFormatForType(application, dataProviderType);
            }
            ISQLCondition or = null;
            if (raw.getClass().isArray()) {
                int length = Array.getLength(raw);
                Object[] elements = new Object[length];
                for (int e = 0; e < length; e++) {
                    Object obj = Array.get(raw, e);
                    if (obj instanceof Wrapper) {
                        obj = ((Wrapper) obj).unwrap();
                    }
                    // Have to use getAsRightType twice here, once to parse using format (getAsType(dataProviderType, formatString))
                    // and once to convert for query (getAsType(c.getDataProviderType(), null))
                    Object converted = convertFromObject(application, columnConverter, columnConverterInfo, dataProviderID, c.getDataProviderType(), Column.getAsRightType(dataProviderType, c.getFlags(), obj, formatString, c.getLength(), null, false, false), false);
                    elements[e] = Column.getAsRightType(c.getDataProviderType(), c.getFlags(), converted, null, c.getLength(), null, false, false);
                }
                // where qCol in (e1, e2, ..., en)
                or = new SetCondition(IBaseSQLCondition.EQUALS_OPERATOR, new IQuerySelectValue[] { qCol }, new Object[][] { elements }, true);
            } else {
                final IColumnConverter fColumnConverter = columnConverter;
                final ConverterInfo fColumnConverterInfo = columnConverterInfo;
                final int fDataProviderType = c.getDataProviderType();
                or = (ISQLCondition) BaseSQLGenerator.parseFindExpression(QueryFactory.INSTANCE, raw, qCol, columnTable, dataProviderType, formatString, c, rfs.getRelations().size() > 0 && relatedNullSearchAddPkCondition(), new IValueConverter() {

                    @Override
                    public Object convertFromObject(Object value) {
                        return SQLGenerator.convertFromObject(application, fColumnConverter, fColumnConverterInfo, dataProviderID, fDataProviderType, value, false);
                    }
                }, new ITypeConverter() {

                    @Override
                    public Object getAsRightType(int type, int flags, Object obj, int l, boolean throwOnFail) {
                        return Column.getAsRightType(type, flags, obj, l, throwOnFail, false);
                    }

                    @Override
                    public Object getAsRightType(int type, int flags, Object obj, String format, int l, boolean throwOnFail) {
                        return Column.getAsRightType(type, flags, obj, format, l, null, throwOnFail, false);
                    }
                }, table.getRowIdentColumns().get(0), Debug.LOGGER);
            }
            if (or != null) {
                ISQLCondition condition;
                if (c instanceof AggregateVariable) {
                    condition = createExistsCondition(application.getFlattenedSolution(), sqlSelect, or, rfs.getRelations(), columnTable, provider, pkQueryColumns.toArray(new QueryColumn[pkQueryColumns.size()]));
                } else {
                    condition = or;
                }
                and = AndCondition.and(and, condition);
            }
        }
    }
    return and;
}
Also used : ConverterInfo(com.servoy.j2db.dataprocessing.SQLSheet.ConverterInfo) SetCondition(com.servoy.j2db.query.SetCondition) RelatedFindState(com.servoy.j2db.dataprocessing.FindState.RelatedFindState) RelatedFindState(com.servoy.j2db.dataprocessing.FindState.RelatedFindState) IValueConverter(com.servoy.base.dataprocessing.IValueConverter) ParsedFormat(com.servoy.j2db.util.FormatParser.ParsedFormat) Wrapper(org.mozilla.javascript.Wrapper) BaseQueryTable(com.servoy.base.query.BaseQueryTable) QueryTable(com.servoy.j2db.query.QueryTable) ITable(com.servoy.j2db.persistence.ITable) Table(com.servoy.j2db.persistence.Table) ITypeConverter(com.servoy.base.dataprocessing.ITypeConverter) ISQLCondition(com.servoy.j2db.query.ISQLCondition) AggregateVariable(com.servoy.j2db.persistence.AggregateVariable) QuerySelect(com.servoy.j2db.query.QuerySelect) BaseQueryTable(com.servoy.base.query.BaseQueryTable) IColumn(com.servoy.j2db.persistence.IColumn) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) IQuerySelectValue(com.servoy.j2db.query.IQuerySelectValue)

Example 10 with SetCondition

use of com.servoy.j2db.query.SetCondition in project servoy-client by Servoy.

the class SQLGenerator method createTableSQL.

private SQLSheet createTableSQL(String dataSource, boolean cache) throws ServoyException {
    if (dataSource == null) {
        return createNoTableSQL(cache);
    }
    Table table = (Table) application.getFoundSetManager().getTable(dataSource);
    if (table == null) {
        // $NON-NLS-1$
        throw new RepositoryException("Cannot create sql: table not found for data source '" + dataSource + '\'');
    }
    SQLSheet retval = new SQLSheet(application, table.getServerName(), table);
    // never remove this line, due to recursive behaviour, register a state when immediately!
    if (cache)
        cachedDataSourceSQLSheets.put(dataSource, retval);
    QueryTable queryTable = new QueryTable(table.getSQLName(), table.getDataSource(), table.getCatalog(), table.getSchema());
    QuerySelect select = new QuerySelect(queryTable);
    QueryDelete delete = new QueryDelete(queryTable);
    QueryInsert insert = new QueryInsert(queryTable);
    QueryUpdate update = new QueryUpdate(queryTable);
    List<Column> columns = new ArrayList<Column>();
    Iterator<Column> it1 = table.getColumns().iterator();
    while (it1.hasNext()) {
        Column c = it1.next();
        ColumnInfo ci = c.getColumnInfo();
        if (ci != null && ci.isExcluded()) {
            continue;
        }
        columns.add(c);
    }
    List<String> requiredDataProviderIDs = new ArrayList<String>();
    Iterator<Column> pks = table.getRowIdentColumns().iterator();
    if (!pks.hasNext()) {
        throw new RepositoryException(ServoyException.InternalCodes.PRIMARY_KEY_NOT_FOUND, new Object[] { table.getName() });
    }
    List<QueryColumn> pkQueryColumns = new ArrayList<QueryColumn>();
    while (pks.hasNext()) {
        Column column = pks.next();
        if (!columns.contains(column))
            columns.add(column);
        requiredDataProviderIDs.add(column.getDataProviderID());
        pkQueryColumns.add(column.queryColumn(queryTable));
    }
    Iterator<Column> it2 = columns.iterator();
    select.setColumns(makeQueryColumns(it2, queryTable, insert));
    SetCondition pkSelect = new SetCondition(IBaseSQLCondition.EQUALS_OPERATOR, pkQueryColumns.toArray(new QueryColumn[pkQueryColumns.size()]), new Placeholder(new TablePlaceholderKey(queryTable, PLACEHOLDER_PRIMARY_KEY)), true);
    select.setCondition(CONDITION_SEARCH, pkSelect);
    delete.setCondition(deepClone(pkSelect));
    update.setCondition(deepClone(pkSelect));
    // fill dataprovider map
    List<String> dataProviderIDsDilivery = new ArrayList<String>();
    for (Column col : columns) {
        dataProviderIDsDilivery.add(col.getDataProviderID());
    }
    retval.addSelect(select, dataProviderIDsDilivery, requiredDataProviderIDs, null);
    retval.addDelete(delete, requiredDataProviderIDs);
    retval.addInsert(insert, dataProviderIDsDilivery);
    retval.addUpdate(update, dataProviderIDsDilivery, requiredDataProviderIDs);
    // related stuff
    createAggregates(retval, queryTable);
    return retval;
}
Also used : Placeholder(com.servoy.j2db.query.Placeholder) BaseQueryTable(com.servoy.base.query.BaseQueryTable) QueryTable(com.servoy.j2db.query.QueryTable) ITable(com.servoy.j2db.persistence.ITable) Table(com.servoy.j2db.persistence.Table) QueryDelete(com.servoy.j2db.query.QueryDelete) TablePlaceholderKey(com.servoy.j2db.query.TablePlaceholderKey) ArrayList(java.util.ArrayList) SafeArrayList(com.servoy.j2db.util.SafeArrayList) ColumnInfo(com.servoy.j2db.persistence.ColumnInfo) RepositoryException(com.servoy.j2db.persistence.RepositoryException) SetCondition(com.servoy.j2db.query.SetCondition) QuerySelect(com.servoy.j2db.query.QuerySelect) BaseQueryTable(com.servoy.base.query.BaseQueryTable) QueryTable(com.servoy.j2db.query.QueryTable) QueryColumn(com.servoy.j2db.query.QueryColumn) BaseQueryColumn(com.servoy.base.query.BaseQueryColumn) IColumn(com.servoy.j2db.persistence.IColumn) Column(com.servoy.j2db.persistence.Column) QueryColumn(com.servoy.j2db.query.QueryColumn) BaseQueryColumn(com.servoy.base.query.BaseQueryColumn) QueryInsert(com.servoy.j2db.query.QueryInsert) QueryUpdate(com.servoy.j2db.query.QueryUpdate)

Aggregations

SetCondition (com.servoy.j2db.query.SetCondition)13 Column (com.servoy.j2db.persistence.Column)10 QueryColumn (com.servoy.j2db.query.QueryColumn)9 QuerySelect (com.servoy.j2db.query.QuerySelect)9 QueryTable (com.servoy.j2db.query.QueryTable)8 IColumn (com.servoy.j2db.persistence.IColumn)7 IQuerySelectValue (com.servoy.j2db.query.IQuerySelectValue)7 BaseQueryColumn (com.servoy.base.query.BaseQueryColumn)5 BaseQueryTable (com.servoy.base.query.BaseQueryTable)5 Placeholder (com.servoy.j2db.query.Placeholder)5 SafeArrayList (com.servoy.j2db.util.SafeArrayList)5 ArrayList (java.util.ArrayList)5 ITable (com.servoy.j2db.persistence.ITable)4 Table (com.servoy.j2db.persistence.Table)4 IDataSet (com.servoy.j2db.dataprocessing.IDataSet)3 RepositoryException (com.servoy.j2db.persistence.RepositoryException)3 CompareCondition (com.servoy.j2db.query.CompareCondition)3 QueryColumnValue (com.servoy.j2db.query.QueryColumnValue)3 TablePlaceholderKey (com.servoy.j2db.query.TablePlaceholderKey)3 ISQLCondition (com.servoy.j2db.query.ISQLCondition)2