Search in sources :

Example 1 with Parameter

use of org.pentaho.metadata.query.model.Parameter in project pentaho-platform by pentaho.

the class SqlMetadataQueryExec method executeQuery.

public IPentahoResultSet executeQuery(Query queryObject) {
    // need to get the correct DatabaseMeta
    SqlPhysicalModel sqlModel = (SqlPhysicalModel) queryObject.getLogicalModel().getPhysicalModel();
    DatabaseMeta databaseMeta = ThinModelConverter.convertToLegacy(sqlModel.getId(), sqlModel.getDatasource());
    // this connection needs closed
    boolean closeConnection = true;
    DatabaseMeta activeDatabaseMeta = getActiveDatabaseMeta(databaseMeta);
    SQLConnection sqlConnection = getConnection(activeDatabaseMeta);
    String sql = null;
    try {
        if ((sqlConnection == null) || !sqlConnection.initialized()) {
            // $NON-NLS-1$
            logger.error(Messages.getInstance().getErrorString("SQLBaseComponent.ERROR_0007_NO_CONNECTION"));
            // TODO: throw an exception up the stack.
            return null;
        }
        // Fix for PDB-1753
        for (Parameter param : queryObject.getParameters()) {
            String pName = param.getName();
            if (parameters.containsKey(pName) && parameters.get(pName) != null && !parameters.get(pName).getClass().isArray()) {
                parameters.put(pName, this.convertParameterValue(param, parameters.get(pName)));
            }
        }
        MappedQuery mappedQuery = null;
        try {
            SqlGenerator sqlGenerator = createSqlGenerator();
            mappedQuery = sqlGenerator.generateSql(queryObject, LocaleHelper.getLocale().toString(), getMetadataDomainRepository(), activeDatabaseMeta, parameters, true);
        } catch (Exception e) {
            throw new RuntimeException(e.getLocalizedMessage(), e);
        }
        Integer timeout = getTimeout();
        if (timeout != null && timeout >= 0) {
            sqlConnection.setQueryTimeout(timeout);
        }
        Integer maxRows = getMaxRows();
        if (maxRows != null && maxRows >= 0) {
            sqlConnection.setMaxRows(maxRows);
        }
        Boolean readOnly = isReadOnly();
        if (readOnly != null && readOnly.booleanValue()) {
            sqlConnection.setReadOnly(true);
        }
        IPentahoResultSet localResultSet = null;
        sql = mappedQuery.getQuery();
        if (logger.isDebugEnabled()) {
            // $NON-NLS-1$
            logger.debug("SQL: " + sql);
        }
        if (getDoQueryLog()) {
            // $NON-NLS-1$
            logger.info("SQL: " + sql);
        }
        // populate prepared sql params
        List<Object> sqlParams = null;
        if (mappedQuery.getParamList() != null) {
            sqlParams = new ArrayList<Object>();
            for (String param : mappedQuery.getParamList()) {
                Object sqlParam = parameters.get(param);
                // lets see if the parameter is a multi valued param
                if (sqlParam instanceof Object[]) {
                    Object[] multivaluedParamValues = (Object[]) sqlParam;
                    for (Object p : multivaluedParamValues) {
                        sqlParams.add(p);
                    }
                    if (multivaluedParamValues.length == 0) {
                        sqlParams.add("");
                    }
                } else {
                    sqlParams.add(sqlParam);
                }
            }
        }
        try {
            if (!isForwardOnly()) {
                if (sqlParams != null) {
                    localResultSet = sqlConnection.prepareAndExecuteQuery(sql, sqlParams);
                } else {
                    localResultSet = sqlConnection.executeQuery(sql);
                }
            } else {
                if (sqlParams != null) {
                    localResultSet = sqlConnection.prepareAndExecuteQuery(sql, sqlParams, SQLConnection.RESULTSET_FORWARDONLY, SQLConnection.CONCUR_READONLY);
                } else {
                    localResultSet = sqlConnection.executeQuery(sql, SQLConnection.RESULTSET_FORWARDONLY, SQLConnection.CONCUR_READONLY);
                }
            }
            IPentahoMetaData metadata = mappedQuery.generateMetadata(localResultSet.getMetaData());
            ((SQLResultSet) localResultSet).setMetaData(metadata);
            closeConnection = false;
        } catch (Exception e) {
            logger.error(Messages.getInstance().getErrorString("SqlMetadataQueryExec.ERROR_0002_ERROR_EXECUTING_QUERY", e.getLocalizedMessage(), // $NON-NLS-1$
            sql));
            // $NON-NLS-1$
            logger.debug("error", e);
            return null;
        }
        return localResultSet;
    } finally {
        if (closeConnection && sqlConnection != null) {
            sqlConnection.close();
        }
    }
}
Also used : MappedQuery(org.pentaho.metadata.query.impl.sql.MappedQuery) SQLConnection(org.pentaho.platform.plugin.services.connections.sql.SQLConnection) IPentahoMetaData(org.pentaho.commons.connection.IPentahoMetaData) SqlPhysicalModel(org.pentaho.metadata.model.SqlPhysicalModel) DatabaseMeta(org.pentaho.di.core.database.DatabaseMeta) GenericDatabaseMeta(org.pentaho.di.core.database.GenericDatabaseMeta) SQLException(java.sql.SQLException) IOException(java.io.IOException) IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) SqlGenerator(org.pentaho.metadata.query.impl.sql.SqlGenerator) SQLResultSet(org.pentaho.platform.plugin.services.connections.sql.SQLResultSet) Parameter(org.pentaho.metadata.query.model.Parameter)

Example 2 with Parameter

use of org.pentaho.metadata.query.model.Parameter in project pentaho-platform by pentaho.

the class MetadataQueryComponent method execute.

public boolean execute() {
    // get the xml parser
    QueryXmlHelper helper = null;
    try {
        helper = createQueryXmlHelper();
    } catch (Exception e) {
        // $NON-NLS-1$
        logger.error("error", e);
        return false;
    }
    // parse the metadata query
    IMetadataDomainRepository repo = PentahoSystem.get(IMetadataDomainRepository.class, null);
    if (queryObject == null) {
        // there is no query model, so create one from the query string
        // apply templates to the query
        String templatedQuery = null;
        if (inputs != null) {
            Properties properties = new Properties();
            for (String name : inputs.keySet()) {
                if (!(inputs.get(name) == null)) {
                    properties.put(name, inputs.get(name).toString());
                }
            }
            templatedQuery = TemplateUtil.applyTemplate(query, properties, null);
        } else {
            templatedQuery = query;
        }
        try {
            queryObject = helper.fromXML(repo, templatedQuery);
        } catch (Exception e) {
            // $NON-NLS-1$
            logger.error("error", e);
            return false;
        }
    }
    if (queryObject == null) {
        // $NON-NLS-1$
        logger.error("error query object null");
        return false;
    }
    // Can still be overridden in the action sequence
    if (timeout == null) {
        // $NON-NLS-1$
        Object timeoutProperty = queryObject.getLogicalModel().getProperty("timeout");
        if (timeoutProperty != null && timeoutProperty instanceof Number) {
            int timeoutVal = ((Number) timeoutProperty).intValue();
            this.setTimeout(timeoutVal);
        }
    }
    if (maxRows == null) {
        // $NON-NLS-1$
        Object maxRowsProperty = queryObject.getLogicalModel().getProperty("max_rows");
        if (maxRowsProperty != null && maxRowsProperty instanceof Number) {
            int maxRowsVal = ((Number) maxRowsProperty).intValue();
            this.setMaxRows(maxRowsVal);
        }
    }
    String queryExecName = queryObject.getLogicalModel().getPhysicalModel().getQueryExecName();
    String queryExecDefault = queryObject.getLogicalModel().getPhysicalModel().getDefaultQueryClassname();
    // String modelType = (String) inputs.get("modeltype");
    IMetadataQueryExec executor = PentahoSystem.get(IMetadataQueryExec.class, queryExecName, session);
    if (executor == null) {
        // get the executor from a plugin possibly?
        Class clazz;
        try {
            clazz = Class.forName(queryExecDefault, true, queryObject.getLogicalModel().getPhysicalModel().getClass().getClassLoader());
            executor = (IMetadataQueryExec) clazz.getConstructor(new Class[] {}).newInstance(new Object[] {});
        } catch (Exception e) {
            logger.warn(Messages.getInstance().getErrorString("MetadataQueryComponent.ERROR_0002_NO_EXECUTOR", // $NON-NLS-1$
            queryExecName));
        }
    }
    if (executor == null) {
        // the query exec class is not defined thru configuration, go with the default
        Class clazz;
        try {
            clazz = Class.forName(queryExecDefault);
            executor = (IMetadataQueryExec) clazz.getConstructor(new Class[] {}).newInstance(new Object[] {});
        } catch (Exception e) {
            logger.error(Messages.getInstance().getErrorString("MetadataQueryComponent.ERROR_0002_NO_EXECUTOR", // $NON-NLS-1$
            queryExecName));
            return false;
        }
    }
    // determine parameter values
    if (queryObject.getParameters() != null) {
        for (Parameter param : queryObject.getParameters()) {
            Object value = null;
            if (inputs != null) {
                value = inputs.get(param.getName());
            }
            executor.setParameter(param, value);
        }
    }
    try {
        executor.setDoQueryLog(logSql);
        executor.setForwardOnly(this.useForwardOnlyResultSet);
        executor.setMaxRows(this.maxRows);
        executor.setMetadataDomainRepository(repo);
        executor.setReadOnly(this.readOnly);
        executor.setTimeout(this.timeout);
        if (this.inputs != null) {
            executor.setInputs(this.inputs);
        }
        resultSet = executor.executeQuery(queryObject);
        if (resultSet != null && !live && executor.isLive()) {
            // read the results and cache them
            IPentahoResultSet cachedResultSet = resultSet.memoryCopy();
            resultSet.close();
            resultSet.closeConnection();
            resultSet = cachedResultSet;
        }
        return resultSet != null;
    } catch (Exception e) {
        // $NON-NLS-1$
        logger.error("error", e);
        throw new RuntimeException(e.getLocalizedMessage(), e);
    }
}
Also used : QueryXmlHelper(org.pentaho.metadata.query.model.util.QueryXmlHelper) IMetadataDomainRepository(org.pentaho.metadata.repository.IMetadataDomainRepository) Properties(java.util.Properties) IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) Parameter(org.pentaho.metadata.query.model.Parameter) IMetadataQueryExec(org.pentaho.metadata.model.IMetadataQueryExec)

Aggregations

IPentahoResultSet (org.pentaho.commons.connection.IPentahoResultSet)2 Parameter (org.pentaho.metadata.query.model.Parameter)2 IOException (java.io.IOException)1 SQLException (java.sql.SQLException)1 Properties (java.util.Properties)1 IPentahoMetaData (org.pentaho.commons.connection.IPentahoMetaData)1 DatabaseMeta (org.pentaho.di.core.database.DatabaseMeta)1 GenericDatabaseMeta (org.pentaho.di.core.database.GenericDatabaseMeta)1 IMetadataQueryExec (org.pentaho.metadata.model.IMetadataQueryExec)1 SqlPhysicalModel (org.pentaho.metadata.model.SqlPhysicalModel)1 MappedQuery (org.pentaho.metadata.query.impl.sql.MappedQuery)1 SqlGenerator (org.pentaho.metadata.query.impl.sql.SqlGenerator)1 QueryXmlHelper (org.pentaho.metadata.query.model.util.QueryXmlHelper)1 IMetadataDomainRepository (org.pentaho.metadata.repository.IMetadataDomainRepository)1 SQLConnection (org.pentaho.platform.plugin.services.connections.sql.SQLConnection)1 SQLResultSet (org.pentaho.platform.plugin.services.connections.sql.SQLResultSet)1