Search in sources :

Example 1 with Result

use of mondrian.olap.Result in project mondrian by pentaho.

the class BatchTestCase method assertQuerySqlOrNot.

/**
 * During MDX query parse and execution, checks that the query results
 * (or does not result) in a particular SQL statement being generated.
 *
 * <p>Parses and executes the MDX query once for each SQL
 * pattern in the current dialect. If there are multiple patterns, runs the
 * MDX query multiple times, and expects to see each SQL statement appear.
 * If there are no patterns in this dialect, the test trivially succeeds.
 *
 * @param testContext non-default test context if required
 * @param mdxQuery MDX query
 * @param patterns Set of patterns
 * @param negative false to assert if SQL is generated;
 *                 true to assert if SQL is NOT generated
 * @param bypassSchemaCache whether to grab a new connection and bypass the
 *        schema cache before parsing the MDX query
 * @param clearCache whether to clear cache before executing the MDX query
 */
protected void assertQuerySqlOrNot(TestContext testContext, String mdxQuery, SqlPattern[] patterns, boolean negative, boolean bypassSchemaCache, boolean clearCache) {
    Connection connection = testContext.getConnection();
    mdxQuery = testContext.upgradeQuery(mdxQuery);
    // Run the test once for each pattern in this dialect.
    // (We could optimize and run it once, collecting multiple queries, and
    // comparing all queries at the end.)
    Dialect dialect = testContext.getDialect();
    Dialect.DatabaseProduct d = dialect.getDatabaseProduct();
    boolean patternFound = false;
    for (SqlPattern sqlPattern : patterns) {
        if (!sqlPattern.hasDatabaseProduct(d)) {
            // message if required.
            continue;
        }
        patternFound = true;
        String sql = sqlPattern.getSql();
        String trigger = sqlPattern.getTriggerSql();
        sql = dialectize(d, sql);
        trigger = dialectize(d, trigger);
        // Create a dummy DataSource which will throw a 'bomb' if it is
        // asked to execute a particular SQL statement, but will otherwise
        // behave exactly the same as the current DataSource.
        final TriggerHook hook = new TriggerHook(trigger);
        RolapUtil.setHook(hook);
        Bomb bomb = null;
        try {
            if (bypassSchemaCache) {
                connection = testContext.withSchemaPool(false).getConnection();
            }
            final Query query = connection.parseQuery(mdxQuery);
            if (clearCache) {
                clearCache((RolapCube) query.getCube());
            }
            final Result result = connection.execute(query);
            Util.discard(result);
            bomb = null;
        } catch (Bomb e) {
            bomb = e;
        } catch (RuntimeException e) {
            // Walk up the exception tree and see if the root cause
            // was a SQL bomb.
            bomb = Util.getMatchingCause(e, Bomb.class);
            if (bomb == null) {
                throw e;
            }
        } finally {
            RolapUtil.setHook(null);
        }
        if (negative) {
            if (bomb != null || hook.foundMatch()) {
                fail("forbidden query [" + sql + "] detected");
            }
        } else {
            if (bomb == null && !hook.foundMatch()) {
                fail("expected query [" + sql + "] did not occur");
            }
            if (bomb != null) {
                assertEquals(replaceQuotes(sql.replaceAll("\r\n", "\n")), replaceQuotes(bomb.sql.replaceAll("\r\n", "\n")));
            }
        }
    }
    // dialect.
    if (!patternFound) {
        String warnDialect = MondrianProperties.instance().WarnIfNoPatternForDialect.get();
        if (warnDialect.equals(d.toString())) {
            System.out.println("[No expected SQL statements found for dialect \"" + dialect.toString() + "\" and test not run]");
        }
    }
}
Also used : Query(mondrian.olap.Query) SqlPattern(mondrian.test.SqlPattern) Connection(mondrian.olap.Connection) Dialect(mondrian.spi.Dialect) Result(mondrian.olap.Result)

Example 2 with Result

use of mondrian.olap.Result in project mondrian by pentaho.

the class BatchTestCase method checkNotNative.

/**
 * Makes sure the MDX runs correctly and not in native mode.
 *
 * @param rowCount       Number of rows returned
 * @param mdx            Query
 * @param expectedResult Expected result string
 */
protected void checkNotNative(int rowCount, String mdx, String expectedResult) {
    getConnection().getCacheControl(null).flushSchemaCache();
    Connection con = getTestContext().withSchemaPool(false).getConnection();
    RolapNativeRegistry reg = getRegistry(con);
    reg.setListener(new Listener() {

        public void foundEvaluator(NativeEvent e) {
            fail("should not be executed native");
        }

        public void foundInCache(TupleEvent e) {
        }

        public void executingSql(TupleEvent e) {
        }
    });
    TestCase c = new TestCase(con, 0, rowCount, mdx);
    Result result = c.run();
    if (expectedResult != null) {
        String nonNativeResult = TestContext.toString(result);
        if (!nonNativeResult.equals(expectedResult)) {
            TestContext.assertEqualsVerbose(expectedResult, nonNativeResult, false, "Non Native implementation returned different result than " + "expected; MDX=" + mdx);
        }
    }
}
Also used : FoodMartTestCase(mondrian.test.FoodMartTestCase) Connection(mondrian.olap.Connection) Result(mondrian.olap.Result)

Example 3 with Result

use of mondrian.olap.Result in project mondrian by pentaho.

the class BatchTestCase method checkNative.

/**
 * Runs a query twice, with native crossjoin optimization enabled and
 * disabled. If both results are equal,and both aggree with the expected
 * result, it is considered correct.
 *
 * <p>Optionally the query can be run with
 * fresh connection. This is useful if the test case sets its certain
 * mondrian properties, e.g. native properties like:
 * mondrian.native.filter.enable
 *
 * @param resultLimit     Maximum result size of all the MDX operations in
 *                        this query. This might be hard to estimate as it
 *                        is usually larger than the rowCount of the final
 *                        result. Setting it to 0 will cause this limit to
 *                        be ignored.
 * @param rowCount        Number of rows returned. (That is, the number
 *                        of positions on the last axis of the query.)
 * @param mdx             Query
 * @param expectedResult  Expected result string
 * @param freshConnection Whether fresh connection is required
 */
protected void checkNative(int resultLimit, int rowCount, String mdx, String expectedResult, boolean freshConnection) {
    // 'level.getMembers()' which create false negatives in this test.
    if (MondrianProperties.instance().TestExpDependencies.get() > 0) {
        return;
    }
    getConnection().getCacheControl(null).flushSchemaCache();
    try {
        LogManager.getLogger(getClass()).debug("*** Native: " + mdx);
        boolean reuseConnection = !freshConnection;
        Connection con = getTestContext().withSchemaPool(reuseConnection).getConnection();
        RolapNativeRegistry reg = getRegistry(con);
        reg.useHardCache(true);
        TestListener listener = new TestListener();
        reg.setListener(listener);
        reg.setEnabled(true);
        TestCase c = new TestCase(con, resultLimit, rowCount, mdx);
        Result result = c.run();
        String nativeResult = TestContext.toString(result);
        if (!listener.isFoundEvaluator()) {
            fail("expected native execution of " + mdx);
        }
        if (!listener.isExecuteSql()) {
            fail("cache is empty: expected SQL query to be executed");
        }
        if (MondrianProperties.instance().EnableRolapCubeMemberCache.get()) {
            // run once more to make sure that the result comes from cache
            // now
            listener.setExecuteSql(false);
            c.run();
            if (listener.isExecuteSql()) {
                fail("expected result from cache when query runs twice");
            }
        }
        con.close();
        LogManager.getLogger(getClass()).debug("*** Interpreter: " + mdx);
        getConnection().getCacheControl(null).flushSchemaCache();
        con = getTestContext().withSchemaPool(false).getConnection();
        reg = getRegistry(con);
        listener.setFoundEvaluator(false);
        reg.setListener(listener);
        // disable RolapNativeSet
        reg.setEnabled(false);
        result = executeQuery(mdx, con);
        String interpretedResult = TestContext.toString(result);
        if (listener.isFoundEvaluator()) {
            fail("did not expect native executions of " + mdx);
        }
        if (expectedResult != null) {
            TestContext.assertEqualsVerbose(expectedResult, nativeResult, false, "Native implementation returned different result than " + "expected; MDX=" + mdx);
            TestContext.assertEqualsVerbose(expectedResult, interpretedResult, false, "Interpreter implementation returned different result than " + "expected; MDX=" + mdx);
        }
        if (!nativeResult.equals(interpretedResult)) {
            TestContext.assertEqualsVerbose(interpretedResult, nativeResult, false, "Native implementation returned different result than " + "interpreter; MDX=" + mdx);
        }
    } finally {
        Connection con = getConnection();
        RolapNativeRegistry reg = getRegistry(con);
        reg.setEnabled(true);
        reg.useHardCache(false);
    }
}
Also used : FoodMartTestCase(mondrian.test.FoodMartTestCase) Connection(mondrian.olap.Connection) Result(mondrian.olap.Result)

Example 4 with Result

use of mondrian.olap.Result in project mondrian by pentaho.

the class FunctionTest method testFirstInLevel5.

public void testFirstInLevel5() {
    Result result = executeQuery("select {[Time].[1997].[Q2].[4].Parent} on columns," + "{[Gender].[M]} on rows from Sales");
    assertEquals("Q2", result.getAxes()[0].getPositions().get(0).get(0).getName());
}
Also used : Result(mondrian.olap.Result)

Example 5 with Result

use of mondrian.olap.Result in project mondrian by pentaho.

the class FunctionTest method testPropertyInCalculatedMember.

public void testPropertyInCalculatedMember() {
    Result result = executeQuery("WITH MEMBER [Measures].[Store Sales per Sqft]\n" + "AS '[Measures].[Store Sales] / " + "  [Store].CurrentMember.Properties(\"Store Sqft\")'\n" + "SELECT \n" + "  {[Measures].[Unit Sales], [Measures].[Store Sales per Sqft]} ON COLUMNS,\n" + "  {[Store].[Store Name].members} ON ROWS\n" + "FROM Sales");
    Member member;
    Cell cell;
    member = result.getAxes()[1].getPositions().get(18).get(0);
    Assert.assertEquals("[Store].[USA].[WA].[Bellingham].[Store 2]", member.getUniqueName());
    cell = result.getCell(new int[] { 0, 18 });
    Assert.assertEquals("2,237", cell.getFormattedValue());
    cell = result.getCell(new int[] { 1, 18 });
    Assert.assertEquals(".17", cell.getFormattedValue());
    member = result.getAxes()[1].getPositions().get(3).get(0);
    Assert.assertEquals("[Store].[Mexico].[DF].[San Andres].[Store 21]", member.getUniqueName());
    cell = result.getCell(new int[] { 0, 3 });
    Assert.assertEquals("", cell.getFormattedValue());
    cell = result.getCell(new int[] { 1, 3 });
    Assert.assertEquals("", cell.getFormattedValue());
}
Also used : Member(mondrian.olap.Member) Cell(mondrian.olap.Cell) Result(mondrian.olap.Result)

Aggregations

Result (mondrian.olap.Result)113 Axis (mondrian.olap.Axis)24 Member (mondrian.olap.Member)10 Test (org.junit.Test)10 Cell (mondrian.olap.Cell)9 Connection (mondrian.olap.Connection)9 Query (mondrian.olap.Query)9 Position (mondrian.olap.Position)8 TestContext (mondrian.test.TestContext)7 ArrayList (java.util.ArrayList)5 MondrianProperties (mondrian.olap.MondrianProperties)5 OlapElement (mondrian.olap.OlapElement)5 RolapCell (mondrian.rolap.RolapCell)5 NonEmptyResult (mondrian.rolap.RolapConnection.NonEmptyResult)5 Execution (mondrian.server.Execution)5 Dialect (mondrian.spi.Dialect)5 OlapConnection (org.olap4j.OlapConnection)5 List (java.util.List)4 ResultBase (mondrian.olap.ResultBase)4 Evaluator (mondrian.olap.Evaluator)3