Search in sources :

Example 1 with LiteralDataprovider

use of com.servoy.j2db.persistence.LiteralDataprovider in project servoy-client by Servoy.

the class UsedDataProviderTracker method usedFromRecord.

/**
 * Used name from Record,
 * @param record may be null (for global relations)
 * @param name
 */
protected void usedFromRecord(IRecordInternal record, String name) {
    IRecordInternal currentRecord = record;
    try {
        // $NON-NLS-1$
        String[] parts = name.split("\\.");
        for (String part : parts) {
            Relation relation = flattenedSolution.getRelation(part);
            if (relation != null) {
                // calc depends on the relation, add a dependency for the primary data providers for the relation
                IDataProvider[] primaryDataProviders = relation.getPrimaryDataProviders(flattenedSolution);
                for (IDataProvider prim : primaryDataProviders) {
                    if (prim instanceof LiteralDataprovider)
                        continue;
                    String primdp = prim.getDataProviderID();
                    if (ScopesUtils.isVariableScope(primdp)) {
                        // global
                        usedGlobal(primdp);
                    } else {
                        // column
                        if (currentRecord != null) {
                            if (currentRecord.getRawData() == null) {
                                if (currentRecord instanceof PrototypeState) {
                                    Debug.trace("Calculation '" + name + "' depends on field '" + part + "' from PrototypeState " + currentRecord);
                                } else {
                                    // should not happen
                                    Debug.error("Unexpected state: calculation '" + name + "' depends on column '" + part + "' from record without pk: " + currentRecord, new IllegalStateException());
                                }
                            } else {
                                usedColumn(currentRecord.getParentFoundSet().getDataSource(), currentRecord.getRawData().getPKHashKey(), primdp);
                            }
                        }
                    }
                }
                IFoundSetInternal foundSet = null;
                if (currentRecord != null)
                    foundSet = currentRecord.getRelatedFoundSet(relation.getName());
                currentRecord = null;
                if (foundSet instanceof RelatedFoundSet) {
                    usedRelatedFoundSet(relation.getName(), (RelatedFoundSet) foundSet);
                    currentRecord = foundSet.getRecord(foundSet.getSelectedIndex());
                }
            } else {
                if (currentRecord != null) {
                    IFoundSetInternal foundSet = currentRecord.getParentFoundSet();
                    if (foundSet.getSQLSheet().containsAggregate(part)) {
                        // aggregate
                        usedAggregate(foundSet, part);
                    } else {
                        // field or calc
                        if (currentRecord.has(part)) {
                            if (currentRecord.getRawData() == null) {
                                if (currentRecord instanceof PrototypeState) {
                                    Debug.trace("Calculation '" + name + "' depends on field '" + part + "' from PrototypeState " + currentRecord);
                                } else {
                                    // should not happen
                                    Debug.error("Unexpected state: calculation '" + name + "' depends on field '" + part + "' from record without pk: " + currentRecord, new IllegalStateException());
                                }
                            } else {
                                usedColumn(foundSet.getDataSource(), currentRecord.getRawData().getPKHashKey(), part);
                            }
                        }
                    }
                }
                return;
            }
            if (currentRecord == null) {
                return;
            }
        }
    } catch (RepositoryException e) {
        Debug.error(e);
    }
}
Also used : Relation(com.servoy.j2db.persistence.Relation) IRecordInternal(com.servoy.j2db.dataprocessing.IRecordInternal) RelatedFoundSet(com.servoy.j2db.dataprocessing.RelatedFoundSet) IFoundSetInternal(com.servoy.j2db.dataprocessing.IFoundSetInternal) RepositoryException(com.servoy.j2db.persistence.RepositoryException) IDataProvider(com.servoy.j2db.persistence.IDataProvider) LiteralDataprovider(com.servoy.j2db.persistence.LiteralDataprovider) PrototypeState(com.servoy.j2db.dataprocessing.PrototypeState)

Example 2 with LiteralDataprovider

use of com.servoy.j2db.persistence.LiteralDataprovider in project servoy-client by Servoy.

the class SQLGenerator method createJoin.

/**
 * Join clause for this relation.
 */
public static ISQLTableJoin createJoin(IDataProviderHandler flattenedSolution, IRelation relation, BaseQueryTable primaryTable, BaseQueryTable foreignTable, boolean permanentJoin, final IGlobalValueEntry provider) throws RepositoryException {
    if (relation instanceof AbstractBase) {
        ISQLTableJoin queryJoin = ((AbstractBase) relation).getRuntimeProperty(Relation.RELATION_JOIN);
        if (queryJoin != null) {
            // a query join was defined for this relation, just relink the tables for the first and last in the joins
            queryJoin = deepClone(queryJoin);
            queryJoin = AbstractBaseQuery.relinkTable(queryJoin.getPrimaryTable(), primaryTable, queryJoin);
            queryJoin = AbstractBaseQuery.relinkTable(queryJoin.getForeignTable(), foreignTable, queryJoin);
            // update the placeholders for globals
            queryJoin.acceptVisitor(new IVisitor() {

                public Object visit(Object o) {
                    if (o instanceof Placeholder && ((Placeholder) o).getKey() instanceof ObjectPlaceholderKey) {
                        Object value = provider.getDataProviderValue(((ObjectPlaceholderKey<int[]>) ((Placeholder) o).getKey()).getName());
                        int[] args = ((ObjectPlaceholderKey<int[]>) ((Placeholder) o).getKey()).getObject();
                        int dataProviderType = args[0];
                        int flags = args[1];
                        if (value == null) {
                            return ValueFactory.createNullValue(dataProviderType);
                        }
                        return Column.getAsRightType(dataProviderType, flags, value, Integer.MAX_VALUE, false, false);
                    }
                    return o;
                }
            });
            return queryJoin;
        }
    }
    // build a join from the relation items
    IDataProvider[] primary = relation.getPrimaryDataProviders(flattenedSolution);
    Column[] foreign = relation.getForeignColumns(flattenedSolution);
    int[] operators = relation.getOperators();
    AndCondition joinCondition = new AndCondition();
    for (int x = 0; x < primary.length; x++) {
        Column primaryColumn = null;
        // check if stored script calc or table column
        if (primary[x] instanceof ScriptCalculation) {
            ScriptCalculation sc = ((ScriptCalculation) primary[x]);
            // null when not stored
            primaryColumn = sc.getTable().getColumn(sc.getName());
        } else if (primary[x] instanceof Column) {
            primaryColumn = (Column) primary[x];
        }
        QueryColumn foreignColumn = foreign[x].queryColumn(foreignTable);
        Object value;
        if (primaryColumn == null) {
            if (primary[x] instanceof LiteralDataprovider) {
                value = ((LiteralDataprovider) primary[x]).getValue();
                value = foreign[x].getAsRightType(value);
            } else {
                value = provider.getDataProviderValue(primary[x].getDataProviderID());
                if (value == null) {
                    value = ValueFactory.createNullValue(primary[x].getDataProviderType());
                } else if (value instanceof Placeholder) {
                    if (((Placeholder) value).getKey() instanceof ObjectPlaceholderKey<?>) {
                        ((ObjectPlaceholderKey) ((Placeholder) value).getKey()).setObject(new int[] { primary[x].getDataProviderType(), primary[x].getFlags() });
                    }
                } else {
                    value = Column.getAsRightType(primary[x].getDataProviderType(), primary[x].getFlags(), value, Integer.MAX_VALUE, false, false);
                }
            }
        } else // table type, can be stored calc
        {
            value = primaryColumn.queryColumn(primaryTable);
        }
        // all operators are swappable because only relation operators in RelationItem.RELATION_OPERATORS can be defined.
        // NOTE: elements in joinCondition MUST be CompareConditions (expected in QueryGenerator and SQLGenerator.createConditionFromFindState)
        joinCondition.addCondition(new CompareCondition(RelationItem.swapOperator(operators[x]), foreignColumn, value));
    }
    if (joinCondition.getConditions().size() == 0) {
        // $NON-NLS-1$
        throw new RepositoryException("Missing join condition in relation " + relation.getName());
    }
    return new QueryJoin(relation.getName(), primaryTable, foreignTable, joinCondition, relation.getJoinType(), permanentJoin);
}
Also used : Placeholder(com.servoy.j2db.query.Placeholder) IVisitor(com.servoy.j2db.util.visitor.IVisitor) AbstractBase(com.servoy.j2db.persistence.AbstractBase) QueryJoin(com.servoy.j2db.query.QueryJoin) RepositoryException(com.servoy.j2db.persistence.RepositoryException) IDataProvider(com.servoy.j2db.persistence.IDataProvider) LiteralDataprovider(com.servoy.j2db.persistence.LiteralDataprovider) AndCondition(com.servoy.j2db.query.AndCondition) ScriptCalculation(com.servoy.j2db.persistence.ScriptCalculation) ISQLTableJoin(com.servoy.j2db.query.ISQLTableJoin) 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) CompareCondition(com.servoy.j2db.query.CompareCondition) ObjectPlaceholderKey(com.servoy.j2db.query.ObjectPlaceholderKey)

Example 3 with LiteralDataprovider

use of com.servoy.j2db.persistence.LiteralDataprovider in project servoy-client by Servoy.

the class JSRelation method newRelationItem.

/**
 * Creates a new relation item for this relation. The primary dataprovider, the foreign data provider
 * and one relation operators (like '=' '!=' '>' '<') must be provided.
 *
 * @sample
 * var relation = solutionModel.newRelation('parentToChild', 'db:/example_data/parent_table', 'db:/example_data/child_table', JSRelation.INNER_JOIN);
 * relation.newRelationItem('another_parent_table_id', '=', 'another_child_table_parent_id');
 * // for literals use a prefix
 * relation.newRelationItem(JSRelationItem.LITERAL_PREFIX + "'hello'",'=', 'mytextfield');
 *
 * @param dataprovider The name of the primary dataprovider.
 *
 * @param operator The operator used to relate the primary and the foreign dataproviders.
 *
 * @param foreinColumnName The name of the foreign dataprovider.
 *
 * @return A JSRelationItem instance representing the newly added relation item.
 */
@JSFunction
public JSRelationItem newRelationItem(String dataprovider, String operator, String foreinColumnName) {
    if (dataprovider == null) {
        // $NON-NLS-1$
        throw new IllegalArgumentException("dataprovider cannot be null");
    }
    if (foreinColumnName == null) {
        // $NON-NLS-1$
        throw new IllegalArgumentException("foreinColumnName cannot be null");
    }
    int validOperator = RelationItem.getValidOperator(operator, RelationItem.RELATION_OPERATORS, null);
    if (validOperator == -1) {
        // $NON-NLS-1$//$NON-NLS-2$
        throw new IllegalArgumentException("operator " + operator + " is not a valid relation operator");
    }
    checkModification();
    try {
        IDataProvider primaryDataProvider = null;
        if (ScopesUtils.isVariableScope(dataprovider)) {
            primaryDataProvider = application.getFlattenedSolution().getGlobalDataProvider(dataprovider);
        } else if (dataprovider.startsWith(LiteralDataprovider.LITERAL_PREFIX)) {
            primaryDataProvider = new LiteralDataprovider(dataprovider);
            if (((LiteralDataprovider) primaryDataProvider).getValue() == null) {
                // $NON-NLS-1$
                throw new IllegalArgumentException("primary data provider " + dataprovider + " is not a valid relation primary data provider");
            }
        } else {
            primaryDataProvider = application.getFlattenedSolution().getDataProviderForTable((Table) application.getFoundSetManager().getTable(relation.getPrimaryDataSource()), dataprovider);
        }
        if (primaryDataProvider == null) {
            // $NON-NLS-1$
            throw new IllegalArgumentException("cant create relation item primary dataprovider not found: " + dataprovider);
        }
        IDataProvider dp = application.getFlattenedSolution().getDataProviderForTable((Table) application.getFoundSetManager().getTable(relation.getForeignDataSource()), foreinColumnName);
        if (!(dp instanceof Column)) {
            // $NON-NLS-1$ //$NON-NLS-2$
            throw new IllegalArgumentException("Foreign columnname " + foreinColumnName + " is not a valid column");
        }
        RelationItem result = relation.createNewRelationItem(application.getFoundSetManager(), primaryDataProvider, validOperator, (Column) dp);
        if (result != null)
            return new JSRelationItem(result, this, isCopy);
        return null;
    } catch (RepositoryException e) {
        throw new RuntimeException(e);
    }
}
Also used : RelationItem(com.servoy.j2db.persistence.RelationItem) Column(com.servoy.j2db.persistence.Column) RepositoryException(com.servoy.j2db.persistence.RepositoryException) IDataProvider(com.servoy.j2db.persistence.IDataProvider) LiteralDataprovider(com.servoy.j2db.persistence.LiteralDataprovider) JSFunction(org.mozilla.javascript.annotations.JSFunction)

Example 4 with LiteralDataprovider

use of com.servoy.j2db.persistence.LiteralDataprovider in project servoy-client by Servoy.

the class DataAdapterList method addDataAdaptersForRelationSequence.

/**
 * Walk over the relation sequence to add data adapters.
 *
 * @param dataAdapter
 * @param relations
 * @param rel
 * @throws RepositoryException
 */
protected void addDataAdaptersForRelationSequence(IDataAdapter dataAdapter, Relation[] relations, int rel) throws RepositoryException {
    Relation relation = relations[rel];
    IDataProvider[] dps = relation.getPrimaryDataProviders(application.getFlattenedSolution());
    if (dps != null) {
        for (IDataProvider dp : dps) {
            if (dp instanceof LiteralDataprovider)
                continue;
            StringBuilder prefix = new StringBuilder();
            for (int r = 0; r < rel; r++) {
                prefix.append(relations[r].getName());
                prefix.append('.');
            }
            String dataProviderID;
            if (ScopesUtils.isVariableScope(dp.getDataProviderID())) {
                dataProviderID = dp.getDataProviderID();
            } else {
                dataProviderID = prefix.toString() + dp.getDataProviderID();
            }
            IDataAdapter da = dataAdapters.get(dataProviderID);
            if (da == null) {
                da = new DataAdapter(dataProviderID);
                dataAdapters.put(dataProviderID, da);
            }
            da.addDataListener(dataAdapter);
            if (rel > 0) {
                addDataAdaptersForRelationSequence(da, relations, rel - 1);
            }
        }
    }
}
Also used : Relation(com.servoy.j2db.persistence.Relation) IDataProvider(com.servoy.j2db.persistence.IDataProvider) LiteralDataprovider(com.servoy.j2db.persistence.LiteralDataprovider)

Example 5 with LiteralDataprovider

use of com.servoy.j2db.persistence.LiteralDataprovider in project servoy-client by Servoy.

the class FoundSetManager method getRelationWhereArgs.

/**
 * Get relation where-args, not using column converters
 * @param state
 * @param relation
 * @param testForCalcs
 * @return
 * @throws RepositoryException
 */
public Object[] getRelationWhereArgs(IRecordInternal state, Relation relation, boolean testForCalcs) throws RepositoryException {
    boolean isNull = true;
    IDataProvider[] args = relation.getPrimaryDataProviders(application.getFlattenedSolution());
    Column[] columns = relation.getForeignColumns(application.getFlattenedSolution());
    Object[] array = new Object[args.length];
    for (int i = 0; i < args.length; i++) {
        Object value = null;
        if (args[i] instanceof LiteralDataprovider) {
            value = ((LiteralDataprovider) args[i]).getValue();
        } else if (args[i] instanceof EnumDataProvider) {
            value = getScopesScopeProvider().getDataProviderValue(args[i].getDataProviderID());
        } else {
            String dataProviderID = args[i].getDataProviderID();
            if (testForCalcs && state.getRawData().containsCalculation(dataProviderID) && state.getRawData().mustRecalculate(dataProviderID, true)) {
                // else this can just cascade through..
                return null;
            }
            // unconverted (todb value)
            value = state.getValue(dataProviderID, false);
        }
        if (value != Scriptable.NOT_FOUND) {
            array[i] = columns[i].getAsRightType(value);
        }
        if (array[i] != null) {
            isNull = false;
        } else {
            // Because null columns can't have a relation.
            if (args[i] instanceof IColumn) {
                return null;
            }
            if (isNull) {
                isNull = !(args[i] instanceof ScriptVariable);
            }
        }
    }
    // optimize for null keys (multiple all null!) but not empty pk (db ident)
    if (isNull)
        return null;
    return array;
}
Also used : IDataProvider(com.servoy.j2db.persistence.IDataProvider) LiteralDataprovider(com.servoy.j2db.persistence.LiteralDataprovider) Column(com.servoy.j2db.persistence.Column) IColumn(com.servoy.j2db.persistence.IColumn) IBaseColumn(com.servoy.base.persistence.IBaseColumn) IColumn(com.servoy.j2db.persistence.IColumn) EnumDataProvider(com.servoy.j2db.persistence.EnumDataProvider) ScriptVariable(com.servoy.j2db.persistence.ScriptVariable) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject)

Aggregations

IDataProvider (com.servoy.j2db.persistence.IDataProvider)5 LiteralDataprovider (com.servoy.j2db.persistence.LiteralDataprovider)5 Column (com.servoy.j2db.persistence.Column)3 RepositoryException (com.servoy.j2db.persistence.RepositoryException)3 IColumn (com.servoy.j2db.persistence.IColumn)2 Relation (com.servoy.j2db.persistence.Relation)2 IBaseColumn (com.servoy.base.persistence.IBaseColumn)1 BaseQueryColumn (com.servoy.base.query.BaseQueryColumn)1 IFoundSetInternal (com.servoy.j2db.dataprocessing.IFoundSetInternal)1 IRecordInternal (com.servoy.j2db.dataprocessing.IRecordInternal)1 PrototypeState (com.servoy.j2db.dataprocessing.PrototypeState)1 RelatedFoundSet (com.servoy.j2db.dataprocessing.RelatedFoundSet)1 AbstractBase (com.servoy.j2db.persistence.AbstractBase)1 EnumDataProvider (com.servoy.j2db.persistence.EnumDataProvider)1 RelationItem (com.servoy.j2db.persistence.RelationItem)1 ScriptCalculation (com.servoy.j2db.persistence.ScriptCalculation)1 ScriptVariable (com.servoy.j2db.persistence.ScriptVariable)1 AndCondition (com.servoy.j2db.query.AndCondition)1 CompareCondition (com.servoy.j2db.query.CompareCondition)1 ISQLTableJoin (com.servoy.j2db.query.ISQLTableJoin)1