Search in sources :

Example 21 with Query

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

the class BasicQueryTest method runMondrian1506.

private void runMondrian1506(Mondrian1506Lambda lambda) throws Exception {
    if (getTestContext().getDialect().getDatabaseProduct() != Dialect.DatabaseProduct.MYSQL) {
        // This only works on MySQL because of Sleep()
        return;
    }
    final TestContext context = getTestContext().withSchema("<Schema name=\"Foo\">\n" + "  <Cube name=\"Bar\">\n" + "    <Table name=\"warehouse\">\n" + "      <SQL>sleep(0.1) = 0</SQL>\n" + "    </Table>   \n" + " <Dimension name=\"Dim\">\n" + "   <Hierarchy hasAll=\"true\">\n" + "     <Level name=\"Level\" column=\"warehouse_id\"/>\n" + "      </Hierarchy>\n" + " </Dimension>\n" + " <Measure name=\"Measure\" aggregator=\"sum\">\n" + "   <MeasureExpression>\n" + "     <SQL>1</SQL>\n" + "   </MeasureExpression>\n" + " </Measure>\n" + "  </Cube>\n" + "</Schema>\n");
    final String mdx = "select {[Measures].[Measure]} on columns from [Bar]";
    // A service to execute stuff in the background.
    final ExecutorService exec = Util.getExecutorService(2, 2, 1000, "BasicQueryTest.testMondrian1506", new RejectedExecutionHandler() {

        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            throw new RuntimeException();
        }
    });
    // We are testing the old Query API.
    final Connection connection = context.getConnection();
    final Query q1 = connection.parseQuery(mdx);
    final Query q2 = connection.parseQuery(mdx);
    // Some flags to test.
    final AtomicBoolean fail = new AtomicBoolean(false);
    final AtomicBoolean success = new AtomicBoolean(false);
    final Runnable r1 = new Runnable() {

        public void run() {
            try {
                connection.execute(q1);
            } catch (Throwable t) {
                fail.set(true);
            }
        }
    };
    final Runnable r2 = new Runnable() {

        public void run() {
            try {
                connection.execute(q2);
                success.set(true);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    };
    try {
        lambda.run(exec, q1, fail, success, r1, r2);
    } finally {
        exec.shutdownNow();
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Query(mondrian.olap.Query) RejectedExecutionHandler(java.util.concurrent.RejectedExecutionHandler) ExecutorService(java.util.concurrent.ExecutorService) RolapConnection(mondrian.rolap.RolapConnection) OlapConnection(org.olap4j.OlapConnection) Connection(mondrian.olap.Connection) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 22 with Query

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

the class BasicQueryTest method testUnparse.

public void testUnparse() {
    Connection connection = getConnection();
    Query query = connection.parseQuery("with member [Measures].[Rendite] as \n" + " '(([Measures].[Store Sales] - [Measures].[Store Cost])) / [Measures].[Store Cost]',\n" + " format_string = iif(([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost] * 100 " + "> \n" + "     Parameter (\"UpperLimit\", NUMERIC, 151, \"Obere Grenze\"), \n" + "   \"|#.00%|arrow='up'\",\n" + "   iif(([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost] * 100 < \n" + "       Parameter(\"LowerLimit\", NUMERIC, 150, \"Untere Grenze\"),\n" + "     \"|#.00%|arrow='down'\",\n" + "     \"|#.00%|arrow='right'\"))\n" + "select {[Measures].members} on columns\n" + "from Sales");
    final String s = Util.unparse(query);
    // Parentheses are added to reflect operator precedence, but that's ok.
    // Note that the doubled parentheses in line #2 of the query have been
    // reduced to a single level.
    TestContext.assertEqualsVerbose("with member [Measures].[Rendite] as '(([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store" + " Cost])', " + "format_string = IIf((((([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost]) * " + "100) > Parameter(\"UpperLimit\", NUMERIC, 151, \"Obere Grenze\")), " + "\"|#.00%|arrow='up'\", " + "IIf((((([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost]) * 100) < Parameter" + "(\"LowerLimit\", NUMERIC, 150, \"Untere Grenze\")), " + "\"|#.00%|arrow='down'\", \"|#.00%|arrow='right'\"))\n" + "select {[Measures].Members} ON COLUMNS\n" + "from [Sales]\n", s);
}
Also used : Query(mondrian.olap.Query) RolapConnection(mondrian.rolap.RolapConnection) OlapConnection(org.olap4j.OlapConnection) Connection(mondrian.olap.Connection)

Example 23 with Query

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

the class BasicQueryTest method testMembersOfLargeDimensionTheHardWay.

public void testMembersOfLargeDimensionTheHardWay() {
    // Avoid this test if memory is scarce.
    if (Bug.avoidMemoryOverflow(TestContext.instance().getDialect())) {
        return;
    }
    final Connection connection = TestContext.instance().getConnection();
    String queryString = "select {[Measures].[Unit Sales]} on columns,\n" + "{[Customers].members} on rows\n" + "from Sales";
    Query query = connection.parseQuery(queryString);
    Result result = connection.execute(query);
    assertEquals(10407, result.getAxes()[1].getPositions().size());
}
Also used : Query(mondrian.olap.Query) RolapConnection(mondrian.rolap.RolapConnection) OlapConnection(org.olap4j.OlapConnection) Connection(mondrian.olap.Connection) Result(mondrian.olap.Result)

Example 24 with Query

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

the class BasicQueryTest method testUnparse2.

public void testUnparse2() {
    Connection connection = getConnection();
    Query query = connection.parseQuery("with member [Measures].[Foo] as '1', " + "format_string='##0.00', " + "funny=IIf(1=1,\"x\"\"y\",\"foo\") " + "select {[Measures].[Foo]} on columns from Sales");
    final String s = query.toString();
    // The "format_string" property, a string literal, is now delimited by
    // double-quotes. This won't work in MSOLAP, but for Mondrian it's
    // consistent with the fact that property values are expressions,
    // not enclosed in single-quotes.
    TestContext.assertEqualsVerbose("with member [Measures].[Foo] as '1', " + "format_string = \"##0.00\", " + "funny = IIf((1 = 1), \"x\"\"y\", \"foo\")\n" + "select {[Measures].[Foo]} ON COLUMNS\n" + "from [Sales]\n", s);
}
Also used : Query(mondrian.olap.Query) RolapConnection(mondrian.rolap.RolapConnection) OlapConnection(org.olap4j.OlapConnection) Connection(mondrian.olap.Connection)

Example 25 with Query

use of mondrian.olap.Query in project pentaho-platform by pentaho.

the class MondrianModelComponent method getInitialQuery.

public static String getInitialQuery(final Connection connection, final String cubeName) throws Throwable {
    String measuresMdx = null;
    String columnsMdx = null;
    // $NON-NLS-1$
    String whereMdx = "";
    StringBuffer rowsMdx = new StringBuffer();
    // Get catalog info, if exists
    String catalog = connection.getCatalogName();
    MondrianCatalogComplementInfo catalogComplementInfo = MondrianCatalogHelper.getInstance().getCatalogComplementInfoMap(catalog);
    try {
        Schema schema = connection.getSchema();
        if (schema == null) {
            Logger.error("MondrianModelComponent", Messages.getInstance().getErrorString("MondrianModel.ERROR_0002_INVALID_SCHEMA", // $NON-NLS-1$ //$NON-NLS-2$
            connection.getConnectString()));
            return null;
        }
        Cube[] cubes = schema.getCubes();
        if ((cubes == null) || (cubes.length == 0)) {
            Logger.error("MondrianModelComponent", Messages.getInstance().getErrorString("MondrianModel.ERROR_0003_NO_CUBES", // $NON-NLS-1$ //$NON-NLS-2$
            connection.getConnectString()));
            return null;
        }
        if ((cubes.length > 1) && (cubeName == null)) {
            Logger.error("MondrianModelComponent", Messages.getInstance().getErrorString("MondrianModel.ERROR_0004_CUBE_NOT_SPECIFIED", // $NON-NLS-1$ //$NON-NLS-2$
            connection.getConnectString()));
            return null;
        }
        Cube cube = null;
        if (cubes.length == 1) {
            cube = cubes[0];
        } else {
            for (Cube element : cubes) {
                if (element.getName().equals(cubeName)) {
                    cube = element;
                    break;
                }
            }
        }
        if (cube == null) {
            Logger.error("MondrianModelComponent", Messages.getInstance().getErrorString("MondrianModel.ERROR_0005_CUBE_NOT_FOUND", cubeName, // $NON-NLS-1$ //$NON-NLS-2$
            connection.getConnectString()));
            return null;
        }
        // If we have any whereConditions block, we need to find which hierarchies they are in
        // and not include them in the rows
        HashSet<Hierarchy> whereHierarchies = new HashSet<Hierarchy>();
        if (catalogComplementInfo != null && catalogComplementInfo.getWhereCondition(cube.getName()) != null && !catalogComplementInfo.getWhereCondition(cube.getName()).equals("")) {
            // $NON-NLS-1$
            final String rawString = catalogComplementInfo.getWhereCondition(cube.getName());
            try {
                // According to Julian, the better way to resolve the names is to build a query
                final String queryStr = // $NON-NLS-1$ //$NON-NLS-2$
                "select " + rawString + " on columns, {} on rows from " + cube.getName();
                final Query query = connection.parseQuery(queryStr);
                final Hierarchy[] hierarchies = query.getMdxHierarchiesOnAxis(AxisOrdinal.StandardAxisOrdinal.COLUMNS);
                boolean isWhereValid = true;
                for (int i = 0; i < hierarchies.length && isWhereValid; i++) {
                    final Hierarchy hierarchy = hierarchies[i];
                    if (connection.getRole().canAccess(hierarchy)) {
                        whereHierarchies.add(hierarchy);
                    } else {
                        isWhereValid = false;
                        whereHierarchies.clear();
                    }
                }
                if (isWhereValid) {
                    // $NON-NLS-1$
                    whereMdx = " WHERE " + rawString;
                }
            } catch (Exception e) {
                // We found an error in the where slicer, so we'll just act like it wasn't here
                whereHierarchies.clear();
            }
        }
        Dimension[] dimensions = cube.getDimensions();
        if ((dimensions == null) || (dimensions.length == 0)) {
            Logger.error("MondrianModelComponent", Messages.getInstance().getErrorString("MondrianModel.ERROR_0006_NO_DIMENSIONS", cubeName, // $NON-NLS-1$ //$NON-NLS-2$
            connection.getConnectString()));
            return null;
        }
        for (Dimension element : dimensions) {
            final Hierarchy hierarchy = element.getHierarchy();
            if (hierarchy == null) {
                Logger.error("MondrianModelComponent", Messages.getInstance().getErrorString("MondrianModel.ERROR_0007_NO_HIERARCHIES", element.getName(), cubeName, // $NON-NLS-1$ //$NON-NLS-2$
                connection.getConnectString()));
                return null;
            }
            if (!connection.getRole().canAccess(hierarchy)) {
                // We can't access this element
                continue;
            }
            if (whereHierarchies.contains(hierarchy)) {
                // We have it on the where condition - skip it
                continue;
            }
            Member member = Locus.execute((RolapConnection) connection, "Retrieving default members in plugin", new Locus.Action<Member>() {

                public Member execute() {
                    return connection.getSchemaReader().getHierarchyDefaultMember(hierarchy);
                }
            });
            if (member == null) {
                Logger.error("MondrianModelComponent", Messages.getInstance().getErrorString("MondrianModel.ERROR_0008_NO_DEFAULT_MEMBER", element.getName(), cubeName, // $NON-NLS-1$ //$NON-NLS-2$
                connection.getConnectString()));
                return null;
            }
            if (element.isMeasures()) {
                // measuresMdx = "with member "+ member.getUniqueName();
                // //$NON-NLS-1$
                // $NON-NLS-1$
                measuresMdx = "";
                // $NON-NLS-1$ //$NON-NLS-2$
                columnsMdx = " select NON EMPTY {" + member.getUniqueName() + "} ON columns, ";
            } else {
                if (rowsMdx.length() > 0) {
                    // $NON-NLS-1$
                    rowsMdx.append(", ");
                }
                rowsMdx.append(member.getUniqueName());
            }
        }
        if ((measuresMdx != null) && (columnsMdx != null) && (rowsMdx.length() > 0)) {
            StringBuffer result = new StringBuffer(measuresMdx.length() + columnsMdx.length() + rowsMdx.length() + 50);
            // $NON-NLS-1$
            result.append(measuresMdx).append(columnsMdx).append("NON EMPTY {(").append(rowsMdx).append(// $NON-NLS-1$
            ")} ON rows ").append(// $NON-NLS-1$ //$NON-NLS-2$
            "from [" + cube.getName() + "]").append(whereMdx);
            return result.toString();
        }
        return null;
    } catch (Throwable t) {
        if (t instanceof MondrianException) {
            // pull the cause out, otherwise it never gets logged
            Throwable cause = ((MondrianException) t).getCause();
            if (cause != null) {
                throw cause;
            } else {
                throw t;
            }
        } else {
            throw t;
        }
    }
}
Also used : Query(mondrian.olap.Query) Schema(mondrian.olap.Schema) Dimension(mondrian.olap.Dimension) MondrianException(mondrian.olap.MondrianException) Hierarchy(mondrian.olap.Hierarchy) Cube(mondrian.olap.Cube) MondrianCatalogComplementInfo(org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCatalogComplementInfo) Locus(mondrian.server.Locus) MondrianException(mondrian.olap.MondrianException) Member(mondrian.olap.Member) HashSet(java.util.HashSet)

Aggregations

Query (mondrian.olap.Query)26 Connection (mondrian.olap.Connection)17 OlapConnection (org.olap4j.OlapConnection)14 Result (mondrian.olap.Result)9 RolapConnection (mondrian.rolap.RolapConnection)7 Member (mondrian.olap.Member)6 Exp (mondrian.olap.Exp)5 ArrayList (java.util.ArrayList)3 MemberExpr (mondrian.mdx.MemberExpr)3 MondrianException (mondrian.olap.MondrianException)3 SqlQuery (mondrian.rolap.sql.SqlQuery)3 Execution (mondrian.server.Execution)3 HashSet (java.util.HashSet)2 TupleList (mondrian.calc.TupleList)2 ListTupleList (mondrian.calc.impl.ListTupleList)2 Formula (mondrian.olap.Formula)2 Hierarchy (mondrian.olap.Hierarchy)2 QueryAxis (mondrian.olap.QueryAxis)2 TestMember (mondrian.olap.fun.TestMember)2 Dialect (mondrian.spi.Dialect)2