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

📄 sqltime.java

📁 derby database source code.good for you.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*   Derby - Class org.apache.derby.iapi.types.SQLTime   Copyright 2001, 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.context.ContextService;import org.apache.derby.iapi.services.sanity.SanityManager;import org.apache.derby.iapi.services.io.StoredFormatIds;import org.apache.derby.iapi.error.StandardException;import org.apache.derby.iapi.db.DatabaseContext;import org.apache.derby.iapi.types.DataValueDescriptor;import org.apache.derby.iapi.types.TypeId;import org.apache.derby.iapi.types.DateTimeDataValue;import org.apache.derby.iapi.types.NumberDataValue;import org.apache.derby.iapi.types.DataType;import org.apache.derby.iapi.services.i18n.LocaleFinder;import org.apache.derby.iapi.services.cache.ClassSize;import org.apache.derby.iapi.util.StringUtil;import java.sql.Date;import java.sql.Time;import java.sql.Timestamp;import java.sql.Types;import java.sql.PreparedStatement;import java.util.Calendar;import java.util.GregorianCalendar;import java.io.ObjectOutput;import java.io.ObjectInput;import java.io.IOException;import java.sql.ResultSet;import java.sql.SQLException;import java.text.DateFormat;import java.text.ParseException;/** * This contains an instance of a SQL Time * Our current implementation doesn't implement time precision so the fractional * seconds portion of the time is always 0.  The default when no time precision * is specified is 0 fractional seconds.  A SQL Time without timezone information * is assumed to be in the local time zone.  The local time is stored as is * and doesn't change if the timezone changes. This is in conformance with the * SQL99 standard.  The SQL92 standard indicates that the time is in GMT and * changes with the timezone.  The SQL99 standard clarifies this to allow time without * timezoned to be stored as the local time. * <p> * Time is stored as two ints.  The first int represents hour, minute, second  * and the second represents fractional seconds (currently 0 since we don't support * time precision) * 	encodedTime = -1 indicates null * * PERFORMANCE OPTIMIZATION: *	The java.sql.Time object is only instantiated on demand for performance * 	reasons. */public final class SQLTime extends DataType						implements DateTimeDataValue{	private int		encodedTime;	private int		encodedTimeFraction; //currently always 0 since we don't											 //support time precision	// The cached value.toString()	private String	valueString;	/*	** DataValueDescriptor interface	** (mostly implemented in DataType)	*/    private static final int BASE_MEMORY_USAGE = ClassSize.estimateBaseFromCatalog( SQLTime.class);    public int estimateMemoryUsage()    {        return BASE_MEMORY_USAGE + ClassSize.estimateMemoryUsage( valueString);    } // end of estimateMemoryUsage	public String getString()	{		if (!isNull())		{			if (valueString == null)			{				valueString = encodedTimeToString(encodedTime);			}			return valueString;		}		else		{			if (SanityManager.DEBUG)			{				if (valueString != null)				{					SanityManager.THROWASSERT(						"valueString expected to be null, not " +						valueString);				}			}			return null;		}	}    int getEncodedTime()    {        return encodedTime;    }	/**		@exception StandardException thrown on failure	 */	public Timestamp getTimestamp( Calendar cal) throws StandardException	{		if (isNull())			return null;		else		{            if( cal == null)                cal = new GregorianCalendar();			/*			** HACK FOR SYMANTEC: in symantec 1.8, the call			** to today.getTime().getTime() will blow up 			** in GregorianCalendar because year <= 0.			** This is a bug in some sort of optimization that			** symantic is doing (not related to the JIT).  If 			** we do a reference to that field everythings works 			** fine, hence this extraneous get(Calendar.YEAR).			*/			cal.get(Calendar.YEAR);			cal.set(Calendar.HOUR_OF_DAY, getHour(encodedTime));			cal.set(Calendar.MINUTE, getMinute(encodedTime));			cal.set(Calendar.SECOND, getSecond(encodedTime));			cal.set(Calendar.MILLISECOND, 0);			return new Timestamp(cal.getTime().getTime());		}	}	public Object getObject()	{		return getTime( (Calendar) null);	}			public int getLength()	{		return 8;	}	/* this is for DataType's error generator */	public String getTypeName()	{		return "TIME";	}	/*	 * Storable interface, implies Externalizable, TypedFormat	 */	/**		Return my format identifier.		@see org.apache.derby.iapi.services.io.TypedFormat#getTypeFormatId	*/	public int getTypeFormatId() {		return StoredFormatIds.SQL_TIME_ID;	}	/** 		@exception IOException error writing data	*/	public void writeExternal(ObjectOutput out) throws IOException {		if (SanityManager.DEBUG)			SanityManager.ASSERT(!isNull(), "writeExternal() is not supposed to be called for null values.");		out.writeInt(encodedTime);		out.writeInt(encodedTimeFraction);	}	/**	 * @see java.io.Externalizable#readExternal	 *	 * @exception IOException	Thrown on error reading the object	 */	public void readExternal(ObjectInput in) throws IOException	{		encodedTime = in.readInt();		encodedTimeFraction = in.readInt();		// reset cached values		valueString = null;	}	public void readExternalFromArray(ArrayInputStream in) throws IOException	{		encodedTime = in.readInt();		encodedTimeFraction = in.readInt();		// reset cached values		valueString = null;	}	/*	 * DataValueDescriptor interface	 */	/** @see DataValueDescriptor#getClone */	public DataValueDescriptor getClone()	{		// Call constructor with all of our info		return new SQLTime(encodedTime, encodedTimeFraction);	}	/**	 * @see DataValueDescriptor#getNewNull	 */	public DataValueDescriptor getNewNull()	{		return new SQLTime();	}	/**	 * @see org.apache.derby.iapi.services.io.Storable#restoreToNull	 *	 */	public void restoreToNull()	{		encodedTime = -1;		encodedTimeFraction = 0;		// clear cached valueString		valueString = null;	}	/*	 * DataValueDescriptor interface	 */	/** 	 * @see DataValueDescriptor#setValueFromResultSet 	 *	 * @exception SQLException		Thrown on error	 */	public void setValueFromResultSet(ResultSet resultSet, int colNumber,									  boolean isNullable)		throws SQLException, StandardException	{			restoreToNull();			encodedTime = computeEncodedTime(resultSet.getTime(colNumber));			//need to set encodedTimeFraction when we implement time precision	}	/**	 * Orderable interface	 *	 *	 * @see org.apache.derby.iapi.types.Orderable	 *	 * @exception StandardException thrown on failure	 */	public int compare(DataValueDescriptor other)		throws StandardException	{		/* Use compare method from dominant type, negating result		 * to reflect flipping of sides.		 */		if (typePrecedence() < other.typePrecedence())		{			return - (other.compare(this));		}		boolean thisNull, otherNull;		thisNull = this.isNull();		otherNull = other.isNull();		/*		 * thisNull otherNull	return		 *	T		T		 	0	(this == other)		 *	F		T		 	-1 	(this < other)		 *	T		F		 	1	(this > other)		 */		if (thisNull || otherNull)		{			if (!thisNull)		// otherNull must be true				return -1;			if (!otherNull)		// thisNull must be true				return 1;			return 0;		}		/*			Neither are null compare them 		 */		int comparison;		/* get the comparison time values */		int otherEncodedTime = 0;		/* if the argument is another Time look up the value		 * we have already taken care of Null		 * ignoring encodedTimeFraction for now since it is always 0		 * - need to change this when we support TIME(precision)		 */		if (other instanceof SQLTime)		{			otherEncodedTime=((SQLTime)other).encodedTime;		}		else 		{			/* O.K. have to do it the hard way and calculate the numeric value			 * from the value			 */			otherEncodedTime = computeEncodedTime(other.getTime( (Calendar) null));		}		if (encodedTime < otherEncodedTime)			comparison = -1;		else if (encodedTime > otherEncodedTime)			comparison = 1;		else			comparison = 0;		return comparison;	}	/**		@exception StandardException thrown on error	 */	public boolean compare(int op,						   DataValueDescriptor other,						   boolean orderedNulls,						   boolean unknownRV)		throws StandardException	{		if (!orderedNulls)		// nulls are unordered		{			if (this.isNull() || other.isNull())				return unknownRV;		}		/* Do the comparison */		return super.compare(op, other, orderedNulls, unknownRV);	}	/*	** Class interface	*/	/*	** Constructors	*/	/** no-arg constructor required by Formattable */	public SQLTime() 	{ 		encodedTime = -1;	//null value	}	public SQLTime(Time value) throws StandardException	{		parseTime(value);	}    private void parseTime(java.util.Date value) throws StandardException	{		encodedTime = computeEncodedTime(value);	}	private SQLTime(int encodedTime, int encodedTimeFraction) {		this.encodedTime = encodedTime;		this.encodedTimeFraction = encodedTimeFraction;	}    /**     * Construct a time from a string. The allowed time formats are:     *<ol>     *<li>old ISO and IBM European standard: hh.mm[.ss]     *<li>IBM USA standard: hh[:mm] {AM | PM}     *<li>JIS & current ISO: hh:mm[:ss]     *</ol>     *      * @param dateStr     * @param localFinder     *     * @return the internal DataValueDescriptor for the value     *     * @exception Standard exception if the syntax is invalid or the value is out of range.     */    public SQLTime( String timeStr, boolean isJdbcEscape, LocaleFinder localeFinder)        throws StandardException    {        parseTime( timeStr, isJdbcEscape, localeFinder, (Calendar) null);    }        /**     * Construct a time from a string. The allowed time formats are:     *<ol>     *<li>old ISO and IBM European standard: hh.mm[.ss]     *<li>IBM USA standard: hh[:mm] {AM | PM}     *<li>JIS & current ISO: hh:mm[:ss]     *</ol>     *      * @param dateStr     * @param localFinder     *     * @return the internal DataValueDescriptor for the value     *     * @exception Standard exception if the syntax is invalid or the value is out of range.     */    public SQLTime( String timeStr, boolean isJdbcEscape, LocaleFinder localeFinder, Calendar cal)        throws StandardException    {        parseTime( timeStr, isJdbcEscape, localeFinder, cal);    }    private static final char IBM_EUR_SEPARATOR = '.';    private static final char[] IBM_EUR_SEPARATOR_OR_END = {IBM_EUR_SEPARATOR, (char) 0};    static final char JIS_SEPARATOR = ':';    private static final char[] US_OR_JIS_MINUTE_END = {JIS_SEPARATOR, ' ', (char) 0};    private static final char[] ANY_SEPARATOR = { '.', ':', ' '};    private static final String[] AM_PM = {"AM", "PM"};    private static final char[] END_OF_STRING = {(char) 0};        private void parseTime( String timeStr, boolean isJdbcEscape, LocaleFinder localeFinder, Calendar cal)        throws StandardException    {        boolean validSyntax = true;        DateTimeParser parser = new DateTimeParser( timeStr);        StandardException thrownSE = null;        int hour = 0;        int minute = 0;        int second = 0;        int amPm = -1;        try        {            if( parser.nextSeparator() == SQLTimestamp.DATE_SEPARATOR)            {                    encodedTime = SQLTimestamp.parseDateOrTimestamp( parser, true)[1];                    valueString = parser.getTrimmedString();                    return;            }            hour = parser.parseInt( 2, true, ANY_SEPARATOR, false);            switch( parser.getCurrentSeparator())            {            case IBM_EUR_SEPARATOR:                if( isJdbcEscape)                {                    validSyntax = false;                    break;                }                minute = parser.parseInt( 2, false, IBM_EUR_SEPARATOR_OR_END, false);                if( parser.getCurrentSeparator() == IBM_EUR_SEPARATOR)                    second = parser.parseInt( 2, false, END_OF_STRING, false);                break;            case ':':                // IBM USA or JIS (new ISO)                minute = parser.parseInt( 2, false, US_OR_JIS_MINUTE_END, false);                switch( parser.getCurrentSeparator())                {                case ' ':                    // IBM USA with minutes                    if( isJdbcEscape)                    {                        validSyntax = false;                        break;                    }                    amPm = parser.parseChoice( AM_PM);                    parser.checkEnd();                    break;                case JIS_SEPARATOR:                    second = parser.parseInt( 2, false, END_OF_STRING, false);                    break;                    // default is end of string, meaning that the seconds part is zero.                }                break;            case ' ':                // IBM USA with minutes omitted                if( isJdbcEscape)                {                    validSyntax = false;                    break;                }

⌨️ 快捷键说明

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