⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sqldecimal.java

📁 derby database source code.good for you.
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/*   Derby - Class org.apache.derby.iapi.types.SQLDecimal   Copyright 1999, 2004 The Apache Software Foundation or its licensors, as applicable.   Licensed under the Apache License, Version 2.0 (the "License");   you may not use this file except in compliance with the License.   You may obtain a copy of the License at      http://www.apache.org/licenses/LICENSE-2.0   Unless required by applicable law or agreed to in writing, software   distributed under the License is distributed on an "AS IS" BASIS,   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   See the License for the specific language governing permissions and   limitations under the License. */package org.apache.derby.iapi.types;import org.apache.derby.iapi.reference.SQLState;import org.apache.derby.iapi.services.io.ArrayInputStream;import org.apache.derby.iapi.services.sanity.SanityManager;import org.apache.derby.iapi.services.io.StoredFormatIds;import org.apache.derby.iapi.services.io.Storable;import org.apache.derby.iapi.error.StandardException;import org.apache.derby.iapi.services.cache.ClassSize;import org.apache.derby.iapi.services.info.JVMInfo;import java.math.BigDecimal;import java.math.BigInteger;import java.lang.Math;import java.lang.reflect.Method;import java.lang.reflect.InvocationTargetException;import java.io.ObjectOutput;import java.io.ObjectInput;import java.io.IOException;import java.sql.ResultSet;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Types;/** * SQLDecimal satisfies the DataValueDescriptor * interfaces (i.e., OrderableDataType). It implements a numeric/decimal column,  * e.g. for * storing a column value; it can be specified * when constructed to not allow nulls. Nullability cannot be changed * after construction, as it affects the storage size and mechanism. * <p> * Because OrderableDataType is a subtype of DataType, * SQLDecimal can play a role in either a DataType/Row * or a OrderableDataType/Row, interchangeably. * <p> * We assume the store has a flag for nullness of the value, * and simply return a 0-length array for the stored form * when the value is null. * * @author jamie */public final class SQLDecimal extends NumberDataType implements VariableSizeDataValue{	private static final BigDecimal ZERO = BigDecimal.valueOf(0L);	private static final BigDecimal ONE = BigDecimal.valueOf(1L);	static final BigDecimal MAXLONG_PLUS_ONE = BigDecimal.valueOf(Long.MAX_VALUE).add(ONE);	static final BigDecimal MINLONG_MINUS_ONE = BigDecimal.valueOf(Long.MIN_VALUE).subtract(ONE);	/**	 * object state.  Note that scale and precision are 	 * always determined dynamically from value when	 * it is not null.       The field value can be null without the data value being null.	   In this case the value is stored in rawData and rawScale. This	   is to allow the minimal amount of work to read a SQLDecimal from disk.	   Creating the BigDecimal is expensive as it requires allocating	   three objects, the last two are a waste in the case the row does	   not qualify or the row will be written out by the sorter before being	   returned to the application.		<P>		This means that this field must be accessed for read indirectly through		the getBigDecimal() method, and when setting it the rawData field must		be set to null.	 */	private BigDecimal	value;	/**		See comments for value	*/	private byte[]		rawData;	/**		See comments for value	*/	private int			rawScale;    private static final int BASE_MEMORY_USAGE = ClassSize.estimateBaseFromCatalog( SQLDecimal.class);    private static final int BIG_DECIMAL_MEMORY_USAGE = ClassSize.estimateBaseFromCatalog( BigDecimal.class);    public int estimateMemoryUsage()    {        int sz = BASE_MEMORY_USAGE;        if( null != value)            sz += BIG_DECIMAL_MEMORY_USAGE + (value.unscaledValue().bitLength() + 8)/8;        if( null != rawData)            sz += rawData.length;        return sz;    }	////////////////////////////////////////////////////////////////////	//	// CLASS INTERFACE	//	////////////////////////////////////////////////////////////////////	/** no-arg constructor, required by Formattable */	public SQLDecimal() 	{	}	public SQLDecimal(BigDecimal val)	{		value = val;	}	public SQLDecimal(BigDecimal val, int nprecision, int scale)			throws StandardException	{				value = val;		if ((value != null) && (scale >= 0))		{			value = value.setScale(scale, 							BigDecimal.ROUND_DOWN);		}	}	public SQLDecimal(String val) 	{		value = new BigDecimal(val);	}	/*	 * DataValueDescriptor interface	 * (mostly implemented in DataType)	 *	 */	/**	 * @exception StandardException thrown on failure to convert	 */	public int	getInt() throws StandardException	{		if (isNull())			return 0;		try {			long lv = getLong();			if ((lv >= Integer.MIN_VALUE) && (lv <= Integer.MAX_VALUE))				return (int) lv;		} catch (StandardException se) {		}		throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "INTEGER");	}	/**	 * @exception StandardException thrown on failure to convert	 */	public byte	getByte() throws StandardException	{		if (isNull())			return (byte)0;		try {			long lv = getLong();			if ((lv >= Byte.MIN_VALUE) && (lv <= Byte.MAX_VALUE))				return (byte) lv;		} catch (StandardException se) {		}		throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "TINYINT");	}	/**	 * @exception StandardException thrown on failure to convert	 */	public short	getShort() throws StandardException	{		if (isNull())			return (short)0;		try {			long lv = getLong();			if ((lv >= Short.MIN_VALUE) && (lv <= Short.MAX_VALUE))				return (short) lv;		} catch (StandardException se) {		}		throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "SMALLINT");	}	/**	 * @exception StandardException thrown on failure to convert	 */	public long	getLong() throws StandardException	{		BigDecimal localValue = getBigDecimal();		if (localValue == null)			return (long)0;		// Valid range for long is		//   greater than Long.MIN_VALUE - 1		// *and*		//   less than Long.MAX_VALUE + 1		//		// This ensures that DECIMAL values with an integral value		// equal to the Long.MIN/MAX_VALUE round correctly to those values.		// e.g. 9223372036854775807.1  converts to 9223372036854775807		// this matches DB2 UDB behaviour		if (   (localValue.compareTo(SQLDecimal.MINLONG_MINUS_ONE) == 1)			&& (localValue.compareTo(SQLDecimal.MAXLONG_PLUS_ONE) == -1)) {			return localValue.longValue();		}		throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "BIGINT");	}	/**	 * @exception StandardException thrown on failure to convert	 */	public float getFloat() throws StandardException	{		BigDecimal localValue = getBigDecimal();		if (localValue == null)			return (float)0;		// If the BigDecimal is out of range for the float		// then positive or negative infinity is returned.		float value = NumberDataType.normalizeREAL(localValue.floatValue());		return value;	}	/**	 * 	 * If we have a value that is greater than the maximum double,	 * exception is thrown.  Otherwise, ok.  If the value is less	 * than can be represented by a double, ti will get set to	 * the smallest double value.	 *	 * @exception StandardException thrown on failure to convert	 */	public double getDouble() throws StandardException	{		BigDecimal localValue = getBigDecimal();		if (localValue == null)			return (double)0;		// If the BigDecimal is out of range for double		// then positive or negative infinity is returned.		double value = NumberDataType.normalizeDOUBLE(localValue.doubleValue());		return value;	}	private BigDecimal	getBigDecimal()	{		if ((value == null) && (rawData != null)) 		{			value = new BigDecimal(new BigInteger(rawData), rawScale);		}		return value;	}		/**	 * DECIMAL implementation. Convert to a BigDecimal using getObject	 * which will return a BigDecimal	 */	public int typeToBigDecimal()	{		return java.sql.Types.DECIMAL;	}    // 0 or null is false, all else is true	public boolean	getBoolean()	{		BigDecimal localValue = getBigDecimal();		if (localValue == null)			return false;		return localValue.compareTo(ZERO) != 0;	}	public String	getString()	{		BigDecimal localValue = getBigDecimal();		if (localValue == null)			return null;		else if (JVMInfo.JDK_ID < JVMInfo.J2SE_15)			return localValue.toString();        else        {            // use reflection so we can still compile using JDK1.4            // if we are prepared to require 1.5 to compile then this can be a direct call            try {                return (String) toPlainString.invoke(localValue, null);            } catch (IllegalAccessException e) {                // can't happen based on the JDK spec                throw new IllegalAccessError("toPlainString");            } catch (InvocationTargetException e) {                Throwable t = e.getTargetException();                if (t instanceof RuntimeException) {                    throw (RuntimeException) t;                } else if (t instanceof Error) {                    throw (Error) t;                } else {                    // can't happen                    throw new IncompatibleClassChangeError("toPlainString");                }            }        }	}    private static final Method toPlainString;    private static final Method bdPrecision;    static {        Method m;        try {            m = BigDecimal.class.getMethod("toPlainString", null);        } catch (NoSuchMethodException e) {            m = null;        }        toPlainString = m;        try {            m = BigDecimal.class.getMethod("precision", null);        } catch (NoSuchMethodException e) {            m = null;        }        bdPrecision = m;    }	public Object	getObject()	{		/*		** BigDecimal is immutable		*/		return getBigDecimal();	}	/**	 * @see DataValueDescriptor#setValue	 *	 */		public void setValue(Object theValue)		throws StandardException	{		rawData = null;		if ((theValue instanceof BigDecimal) ||			(theValue == null))		{			setCoreValue((BigDecimal)theValue);		}		else if (theValue instanceof Number)		{			value = new BigDecimal(Double.toString(((Number)theValue).doubleValue()));		}		else		{			genericSetObject(theValue);		}	}	protected void setFrom(DataValueDescriptor theValue) throws StandardException {		setCoreValue(SQLDecimal.getBigDecimal(theValue));	}	public int	getLength()	{		return getDecimalValuePrecision();	}	// this is for DataType's error generator

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -