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) 2006-2011 Pentaho 008// All Rights Reserved. 009*/ 010package mondrian.olap.fun; 011 012import mondrian.calc.*; 013import mondrian.calc.impl.AbstractStringCalc; 014import mondrian.mdx.ResolvedFunCall; 015import mondrian.olap.*; 016import mondrian.util.Format; 017 018import java.util.Locale; 019 020/** 021 * Definition of the <code>Format</code> MDX function. 022 * 023 * @author jhyde 024 * @since Mar 23, 2006 025 */ 026class FormatFunDef extends FunDefBase { 027 static final ReflectiveMultiResolver Resolver = 028 new ReflectiveMultiResolver( 029 "Format", 030 "Format(<Expression>, <String Expression>)", 031 "Formats a number or date to a string.", 032 new String[] { "fSmS", "fSnS", "fSDS" }, 033 FormatFunDef.class); 034 035 public FormatFunDef(FunDef dummyFunDef) { 036 super(dummyFunDef); 037 } 038 039 public Calc compileCall(ResolvedFunCall call, ExpCompiler compiler) { 040 final Exp[] args = call.getArgs(); 041 final Calc calc = compiler.compileScalar(call.getArg(0), true); 042 final Locale locale = compiler.getEvaluator().getConnectionLocale(); 043 if (args[1] instanceof Literal) { 044 // Constant string expression: optimize by 045 // compiling format string. 046 String formatString = (String) ((Literal) args[1]).getValue(); 047 final Format format = new Format(formatString, locale); 048 return new AbstractStringCalc(call, new Calc[] {calc}) { 049 public String evaluateString(Evaluator evaluator) { 050 final Object o = calc.evaluate(evaluator); 051 return format.format(o); 052 } 053 }; 054 } else { 055 // Variable string expression 056 final StringCalc stringCalc = 057 compiler.compileString(call.getArg(1)); 058 return new AbstractStringCalc(call, new Calc[] {calc, stringCalc}) { 059 public String evaluateString(Evaluator evaluator) { 060 final Object o = calc.evaluate(evaluator); 061 final String formatString = 062 stringCalc.evaluateString(evaluator); 063 final Format format = 064 new Format(formatString, locale); 065 return format.format(o); 066 } 067 }; 068 } 069 } 070} 071 072// End FormatFunDef.java