001/*
002// This software is subject to the terms of the Eclipse Public License v1.0
003// Agreement, available at the following URL:
004// http://www.eclipse.org/legal/epl-v10.html.
005// You must accept the terms of that agreement to use this software.
006//
007// Copyright (C) 2009-2009 Pentaho and others
008// All Rights Reserved.
009*/
010package mondrian.olap.fun;
011
012import mondrian.calc.*;
013import mondrian.calc.impl.AbstractHierarchyCalc;
014import mondrian.mdx.ResolvedFunCall;
015import mondrian.olap.*;
016import mondrian.olap.type.HierarchyType;
017import mondrian.olap.type.Type;
018
019/**
020 * Definition of the <code>Dimensions(&lt;String Expression&gt;)</code>
021 * MDX builtin function.
022 *
023 * <p>NOTE: Actually returns a hierarchy. This is consistent with Analysis
024 * Services.
025 *
026 * @author jhyde
027 * @since Jul 20, 2009
028 */
029class DimensionsStringFunDef extends FunDefBase {
030    public static final FunDefBase INSTANCE = new DimensionsStringFunDef();
031
032    private DimensionsStringFunDef() {
033        super(
034            "Dimensions",
035            "Returns the hierarchy whose name is specified by a string.",
036            "fhS");
037    }
038
039    public Type getResultType(Validator validator, Exp[] args) {
040        return HierarchyType.Unknown;
041    }
042
043    public Calc compileCall(ResolvedFunCall call, ExpCompiler compiler)
044    {
045        final StringCalc stringCalc =
046            compiler.compileString(call.getArg(0));
047        return new AbstractHierarchyCalc(call, new Calc[] {stringCalc})
048        {
049            public Hierarchy evaluateHierarchy(Evaluator evaluator) {
050                String dimensionName =
051                    stringCalc.evaluateString(evaluator);
052                return findHierarchy(dimensionName, evaluator);
053            }
054        };
055    }
056
057    /**
058     * Looks up a hierarchy in the current cube with a given name.
059     *
060     * @param name Hierarchy name
061     * @param evaluator Evaluator
062     * @return Hierarchy
063     */
064    Hierarchy findHierarchy(String name, Evaluator evaluator) {
065        if (name.indexOf("[") == -1) {
066            name = Util.quoteMdxIdentifier(name);
067        }
068        OlapElement o = evaluator.getSchemaReader().lookupCompound(
069            evaluator.getCube(),
070            parseIdentifier(name),
071            false,
072            Category.Hierarchy);
073        if (o instanceof Hierarchy) {
074            return (Hierarchy) o;
075        } else if (o == null) {
076            throw newEvalException(
077                this, "Hierarchy '" + name + "' not found");
078        } else {
079            throw newEvalException(
080                this, "Hierarchy(" + name + ") found " + o);
081        }
082    }
083}
084
085// End DimensionsStringFunDef.java