Search in sources :

Example 1 with ArrayImpl

use of org.teiid.core.types.ArrayImpl in project teiid by teiid.

the class ObjectToAnyTransform method transform.

@Override
public Object transform(Object value, Class<?> targetType) throws TransformationException {
    if (value == null) {
        return null;
    }
    if (targetType.isAssignableFrom(value.getClass())) {
        return value;
    }
    Transform transform = DataTypeManager.getTransform(value.getClass(), targetType);
    boolean valid = true;
    if (transform instanceof ObjectToAnyTransform) {
        Object v1 = DataTypeManager.convertToRuntimeType(value, true);
        if (v1 != value) {
            try {
                return transform(v1, targetType);
            } catch (TransformationException e) {
                throw new TransformationException(CorePlugin.Event.TEIID10076, e, CorePlugin.Util.gs(CorePlugin.Event.TEIID10076, getSourceType(), targetClass, value));
            }
        }
        if (targetType.isArray()) {
            if (value instanceof Array) {
                try {
                    // TODO: need to use the base type information for non-ArrayImpl values
                    Object array = ((Array) value).getArray();
                    if (targetType.isAssignableFrom(array.getClass())) {
                        if (!(value instanceof ArrayImpl)) {
                            return new ArrayImpl((Object[]) array);
                        }
                        return value;
                    }
                    value = array;
                } catch (SQLException e) {
                    throw new TransformationException(e);
                }
            }
            if (value.getClass().isArray()) {
                if (value.getClass().getComponentType().isPrimitive() && targetType.getComponentType().isAssignableFrom(convertPrimitiveToObject(value.getClass().getComponentType()))) {
                    Object[] result = (Object[]) java.lang.reflect.Array.newInstance(targetType.getComponentType(), java.lang.reflect.Array.getLength(value));
                    for (int i = 0; i < result.length; i++) {
                        result[i] = java.lang.reflect.Array.get(value, i);
                    }
                    return new ArrayImpl(result);
                }
                Class<?> targetComponentType = targetType.getComponentType();
                Object[] result = (Object[]) java.lang.reflect.Array.newInstance(targetComponentType, java.lang.reflect.Array.getLength(value));
                for (int i = 0; i < result.length; i++) {
                    Object v = java.lang.reflect.Array.get(value, i);
                    if (v.getClass() == targetComponentType || DefaultDataClasses.OBJECT == targetComponentType) {
                        result[i] = v;
                    } else {
                        Transform subTransform = DataTypeManager.getTransform(v.getClass(), targetComponentType);
                        if (subTransform == null) {
                            valid = false;
                            break;
                        }
                        result[i] = subTransform.transform(v, targetComponentType);
                    }
                }
                if (valid) {
                    return new ArrayImpl(result);
                }
            }
        }
        valid = false;
    }
    if (transform == null || !valid) {
        Object[] params = new Object[] { getSourceType(), targetType, value };
        throw new TransformationException(CorePlugin.Event.TEIID10076, CorePlugin.Util.gs(CorePlugin.Event.TEIID10076, params));
    }
    try {
        return transform.transform(value, targetType);
    } catch (TransformationException e) {
        Object[] params = new Object[] { getSourceType(), targetType, value };
        throw new TransformationException(CorePlugin.Event.TEIID10076, e, CorePlugin.Util.gs(CorePlugin.Event.TEIID10076, params));
    }
}
Also used : Array(java.sql.Array) TransformationException(org.teiid.core.types.TransformationException) SQLException(java.sql.SQLException) ArrayImpl(org.teiid.core.types.ArrayImpl) Transform(org.teiid.core.types.Transform)

Example 2 with ArrayImpl

use of org.teiid.core.types.ArrayImpl in project teiid by teiid.

the class TestArray method testArrayValueCompare.

@Test
public void testArrayValueCompare() {
    ArrayImpl a1 = new ArrayImpl(new Object[] { 1, 2, 3 });
    UnitTestUtil.helpTestEquivalence(0, a1, a1);
    ArrayImpl a2 = new ArrayImpl(new Object[] { 1, 2 });
    UnitTestUtil.helpTestEquivalence(1, a1, a2);
}
Also used : ArrayImpl(org.teiid.core.types.ArrayImpl) Test(org.junit.Test)

Example 3 with ArrayImpl

use of org.teiid.core.types.ArrayImpl in project teiid by teiid.

the class TestArray method testIndexOutOfBounds.

/**
 * This is for compatibility with array_get
 * @throws Exception
 */
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBounds() throws Exception {
    ArrayImpl a1 = new ArrayImpl((Object[]) new Integer[] { 1, 2, 3 });
    a1.getArray(-1, 1);
}
Also used : ArrayImpl(org.teiid.core.types.ArrayImpl) Test(org.junit.Test)

Example 4 with ArrayImpl

use of org.teiid.core.types.ArrayImpl in project teiid by teiid.

the class DataTierManagerImpl method processSystemQuery.

/**
 * @param command
 * @param workItem
 * @return
 * @throws TeiidComponentException
 * @throws TeiidProcessingException
 */
private TupleSource processSystemQuery(CommandContext context, Command command, DQPWorkContext workContext) throws TeiidComponentException, TeiidProcessingException {
    String vdbName = workContext.getVdbName();
    String vdbVersion = workContext.getVdbVersion();
    final VDBMetaData vdb = workContext.getVDB();
    TransformationMetadata indexMetadata = vdb.getAttachment(TransformationMetadata.class);
    CompositeMetadataStore metadata = indexMetadata.getMetadataStore();
    if (command instanceof Query) {
        Query query = (Query) command;
        UnaryFromClause ufc = (UnaryFromClause) query.getFrom().getClauses().get(0);
        GroupSymbol group = ufc.getGroup();
        if (StringUtil.startsWithIgnoreCase(group.getNonCorrelationName(), CoreConstants.SYSTEM_ADMIN_MODEL)) {
            final SystemAdminTables sysTable = SystemAdminTables.valueOf(group.getNonCorrelationName().substring(CoreConstants.SYSTEM_ADMIN_MODEL.length() + 1).toUpperCase());
            BaseExtractionTable<?> et = systemAdminTables.get(sysTable);
            return et.processQuery(query, vdb, indexMetadata, context);
        }
        final SystemTables sysTable = SystemTables.valueOf(group.getNonCorrelationName().substring(CoreConstants.SYSTEM_MODEL.length() + 1).toUpperCase());
        BaseExtractionTable<?> et = systemTables.get(sysTable);
        return et.processQuery(query, vdb, indexMetadata, context);
    }
    Collection<List<?>> rows = new ArrayList<List<?>>();
    StoredProcedure proc = (StoredProcedure) command;
    if (StringUtil.startsWithIgnoreCase(proc.getProcedureCallableName(), CoreConstants.SYSTEM_ADMIN_MODEL)) {
        final SystemAdminProcs sysProc = SystemAdminProcs.valueOf(proc.getProcedureCallableName().substring(CoreConstants.SYSTEM_ADMIN_MODEL.length() + 1).toUpperCase());
        switch(sysProc) {
            case LOGMSG:
            case ISLOGGABLE:
                String level = (String) ((Constant) proc.getParameter(2).getExpression()).getValue();
                String logContext = (String) ((Constant) proc.getParameter(3).getExpression()).getValue();
                Object message = null;
                if (sysProc == SystemAdminProcs.LOGMSG) {
                    message = ((Constant) proc.getParameter(4).getExpression()).getValue();
                }
                int msgLevel = getLevel(level);
                boolean logged = false;
                if (LogManager.isMessageToBeRecorded(logContext, msgLevel)) {
                    if (message != null) {
                        LogManager.log(msgLevel, logContext, message);
                    }
                    logged = true;
                }
                if (proc.returnParameters()) {
                    rows.add(Arrays.asList(logged));
                }
                return new CollectionTupleSource(rows.iterator());
            case SETPROPERTY:
                try {
                    String uuid = (String) ((Constant) proc.getParameter(2).getExpression()).getValue();
                    String key = (String) ((Constant) proc.getParameter(3).getExpression()).getValue();
                    Clob value = (Clob) ((Constant) proc.getParameter(4).getExpression()).getValue();
                    key = MetadataFactory.resolvePropertyKey(null, key);
                    String strVal = null;
                    String result = null;
                    if (value != null) {
                        if (value.length() > MAX_VALUE_LENGTH) {
                            throw new TeiidProcessingException(QueryPlugin.Event.TEIID30548, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30548, MAX_VALUE_LENGTH));
                        }
                        strVal = ObjectConverterUtil.convertToString(value.getCharacterStream());
                    }
                    final AbstractMetadataRecord target = getByUuid(metadata, uuid);
                    if (target == null) {
                        throw new TeiidProcessingException(QueryPlugin.Event.TEIID30549, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30549, uuid));
                    }
                    AbstractMetadataRecord schema = target;
                    while (!(schema instanceof Schema) && schema.getParent() != null) {
                        schema = schema.getParent();
                    }
                    if (schema instanceof Schema && vdb.getImportedModels().contains(((Schema) schema).getName())) {
                        // $NON-NLS-1$
                        throw new TeiidProcessingException(QueryPlugin.Event.TEIID31098, QueryPlugin.Util.getString("ValidationVisitor.invalid_alter", uuid));
                    }
                    if (getMetadataRepository(target, vdb) != null) {
                        getMetadataRepository(target, vdb).setProperty(vdbName, vdbVersion, target, key, strVal);
                    }
                    result = DdlPlan.setProperty(vdb, target, key, strVal);
                    if (eventDistributor != null) {
                        eventDistributor.setProperty(vdbName, vdbVersion, uuid, key, strVal);
                    }
                    // materialization depends upon the property values
                    // $NON-NLS-1$
                    indexMetadata.addToMetadataCache(target, "transformation/matview", null);
                    if (proc.returnParameters()) {
                        if (result == null) {
                            rows.add(Arrays.asList((Clob) null));
                        } else {
                            rows.add(Arrays.asList(new ClobType(new ClobImpl(result))));
                        }
                    }
                    return new CollectionTupleSource(rows.iterator());
                } catch (SQLException e) {
                    throw new TeiidProcessingException(QueryPlugin.Event.TEIID30550, e);
                } catch (IOException e) {
                    throw new TeiidProcessingException(QueryPlugin.Event.TEIID30551, e);
                }
        }
        final Table table = indexMetadata.getGroupID((String) ((Constant) proc.getParameter(1).getExpression()).getValue());
        switch(sysProc) {
            case SETCOLUMNSTATS:
                final String columnName = (String) ((Constant) proc.getParameter(2).getExpression()).getValue();
                Column c = null;
                for (Column col : table.getColumns()) {
                    if (col.getName().equalsIgnoreCase(columnName)) {
                        c = col;
                        break;
                    }
                }
                if (c == null) {
                    throw new TeiidProcessingException(QueryPlugin.Event.TEIID30552, columnName + TransformationMetadata.NOT_EXISTS_MESSAGE);
                }
                Number distinctVals = (Number) ((Constant) proc.getParameter(3).getExpression()).getValue();
                Number nullVals = (Number) ((Constant) proc.getParameter(4).getExpression()).getValue();
                String max = (String) ((Constant) proc.getParameter(5).getExpression()).getValue();
                String min = (String) ((Constant) proc.getParameter(6).getExpression()).getValue();
                final ColumnStats columnStats = new ColumnStats();
                columnStats.setDistinctValues(distinctVals);
                columnStats.setNullValues(nullVals);
                columnStats.setMaximumValue(max);
                columnStats.setMinimumValue(min);
                if (getMetadataRepository(table, vdb) != null) {
                    getMetadataRepository(table, vdb).setColumnStats(vdbName, vdbVersion, c, columnStats);
                }
                DdlPlan.setColumnStats(vdb, c, columnStats);
                if (eventDistributor != null) {
                    eventDistributor.setColumnStats(vdbName, vdbVersion, table.getParent().getName(), table.getName(), columnName, columnStats);
                }
                break;
            case SETTABLESTATS:
                Constant val = (Constant) proc.getParameter(2).getExpression();
                final Number cardinality = (Number) val.getValue();
                TableStats tableStats = new TableStats();
                tableStats.setCardinality(cardinality);
                if (getMetadataRepository(table, vdb) != null) {
                    getMetadataRepository(table, vdb).setTableStats(vdbName, vdbVersion, table, tableStats);
                }
                DdlPlan.setTableStats(vdb, table, tableStats);
                if (eventDistributor != null) {
                    eventDistributor.setTableStats(vdbName, vdbVersion, table.getParent().getName(), table.getName(), tableStats);
                }
                break;
        }
        return new CollectionTupleSource(rows.iterator());
    }
    final SystemProcs sysTable = SystemProcs.valueOf(proc.getProcedureCallableName().substring(CoreConstants.SYSTEM_MODEL.length() + 1).toUpperCase());
    switch(sysTable) {
        case GETXMLSCHEMAS:
            try {
                Object groupID = indexMetadata.getGroupID((String) ((Constant) proc.getParameter(1).getExpression()).getValue());
                List<SQLXMLImpl> schemas = indexMetadata.getXMLSchemas(groupID);
                for (SQLXMLImpl schema : schemas) {
                    rows.add(Arrays.asList(new XMLType(schema)));
                }
            } catch (QueryMetadataException e) {
                throw new TeiidProcessingException(QueryPlugin.Event.TEIID30553, e);
            }
            break;
        case ARRAYITERATE:
            Object array = ((Constant) proc.getParameter(1).getExpression()).getValue();
            if (array != null) {
                final Object[] vals;
                if (array instanceof Object[]) {
                    vals = (Object[]) array;
                } else {
                    ArrayImpl arrayImpl = (ArrayImpl) array;
                    vals = arrayImpl.getValues();
                }
                return new CollectionTupleSource(new Iterator<List<?>>() {

                    int index = 0;

                    @Override
                    public boolean hasNext() {
                        return index < vals.length;
                    }

                    @Override
                    public List<?> next() {
                        if (!hasNext()) {
                            throw new NoSuchElementException();
                        }
                        return Arrays.asList(vals[index++]);
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                });
            }
    }
    return new CollectionTupleSource(rows.iterator());
}
Also used : Query(org.teiid.query.sql.lang.Query) UnaryFromClause(org.teiid.query.sql.lang.UnaryFromClause) SQLException(java.sql.SQLException) Constant(org.teiid.query.sql.symbol.Constant) ArrayImpl(org.teiid.core.types.ArrayImpl) ArrayList(java.util.ArrayList) CollectionTupleSource(org.teiid.query.processor.CollectionTupleSource) TeiidProcessingException(org.teiid.core.TeiidProcessingException) ArrayList(java.util.ArrayList) List(java.util.List) ClobImpl(org.teiid.core.types.ClobImpl) TransformationMetadata(org.teiid.query.metadata.TransformationMetadata) SQLXMLImpl(org.teiid.core.types.SQLXMLImpl) IOException(java.io.IOException) QueryMetadataException(org.teiid.api.exception.query.QueryMetadataException) ClobType(org.teiid.core.types.ClobType) XMLType(org.teiid.core.types.XMLType) CompositeMetadataStore(org.teiid.query.metadata.CompositeMetadataStore) StoredProcedure(org.teiid.query.sql.lang.StoredProcedure) VDBMetaData(org.teiid.adminapi.impl.VDBMetaData) GroupSymbol(org.teiid.query.sql.symbol.GroupSymbol) Clob(java.sql.Clob) NoSuchElementException(java.util.NoSuchElementException)

Example 5 with ArrayImpl

use of org.teiid.core.types.ArrayImpl in project teiid by teiid.

the class LanguageBridgeFactory method translate.

/* Execute */
Call translate(StoredProcedure sp) {
    Procedure proc = null;
    if (sp.getProcedureID() != null) {
        try {
            proc = this.metadataFactory.getProcedure(sp.getGroup().getName());
        } catch (TranslatorException e) {
            throw new TeiidRuntimeException(QueryPlugin.Event.TEIID30486, e);
        }
    }
    Class<?> returnType = null;
    List<Argument> translatedParameters = new ArrayList<Argument>();
    for (SPParameter param : sp.getParameters()) {
        Direction direction = Direction.IN;
        switch(param.getParameterType()) {
            case ParameterInfo.IN:
                direction = Direction.IN;
                break;
            case ParameterInfo.INOUT:
                direction = Direction.INOUT;
                break;
            case ParameterInfo.OUT:
                direction = Direction.OUT;
                break;
            case ParameterInfo.RESULT_SET:
                // already part of the metadata
                continue;
            case ParameterInfo.RETURN_VALUE:
                returnType = param.getClassType();
                continue;
        }
        if (param.isUsingDefault() && BaseColumn.OMIT_DEFAULT.equalsIgnoreCase(metadataFactory.getMetadata().getExtensionProperty(param.getMetadataID(), BaseColumn.DEFAULT_HANDLING, false))) {
            continue;
        }
        ProcedureParameter metadataParam = metadataFactory.getParameter(param);
        // we can assume for now that all arguments will be literals, which may be multivalued
        org.teiid.language.Expression value = null;
        if (direction != Direction.OUT) {
            if (param.isVarArg()) {
                ArrayImpl av = (ArrayImpl) ((Constant) param.getExpression()).getValue();
                if (av != null) {
                    for (Object obj : av.getValues()) {
                        Argument arg = new Argument(direction, new Literal(obj, param.getClassType().getComponentType()), param.getClassType().getComponentType(), metadataParam);
                        translatedParameters.add(arg);
                    }
                }
                break;
            }
            value = translate(param.getExpression());
        }
        Argument arg = new Argument(direction, value, param.getClassType(), metadataParam);
        translatedParameters.add(arg);
    }
    Call call = new Call(removeSchemaName(sp.getProcedureName()), translatedParameters, proc);
    call.setReturnType(returnType);
    return call;
}
Also used : ProcedureParameter(org.teiid.metadata.ProcedureParameter) ArrayImpl(org.teiid.core.types.ArrayImpl) org.teiid.language(org.teiid.language) TeiidRuntimeException(org.teiid.core.TeiidRuntimeException) Direction(org.teiid.language.Argument.Direction) Procedure(org.teiid.metadata.Procedure) TranslatorException(org.teiid.translator.TranslatorException)

Aggregations

ArrayImpl (org.teiid.core.types.ArrayImpl)31 Test (org.junit.Test)15 ArrayList (java.util.ArrayList)7 List (java.util.List)7 SQLException (java.sql.SQLException)3 Array (org.teiid.query.sql.symbol.Array)3 Constant (org.teiid.query.sql.symbol.Constant)3 IOException (java.io.IOException)2 ObjectOutputStream (java.io.ObjectOutputStream)2 Array (java.sql.Array)2 TeiidProcessingException (org.teiid.core.TeiidProcessingException)2 TeiidRuntimeException (org.teiid.core.TeiidRuntimeException)2 TransformationException (org.teiid.core.types.TransformationException)2 XMLType (org.teiid.core.types.XMLType)2 ProcedureParameter (org.teiid.metadata.ProcedureParameter)2 LanguageObject (org.teiid.query.sql.LanguageObject)2 Command (org.teiid.query.sql.lang.Command)2 Expression (org.teiid.query.sql.symbol.Expression)2 GroupSymbol (org.teiid.query.sql.symbol.GroupSymbol)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1