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

📄 sqldate.java

📁 derby database source code.good for you.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            valueString = dateStr;        }    } // end of parseDate	public void setValue(Object theValue) throws StandardException	{		if (theValue == null)		{			setToNull();		}		else if (theValue instanceof Date)		{			setValue((Date)theValue, (Calendar) null);		}		else if (theValue instanceof Timestamp)		{			setValue((Timestamp)theValue, (Calendar) null);		}		else		{			genericSetObject(theValue);		}	}	protected void setFrom(DataValueDescriptor theValue) throws StandardException {		// Same format means same type SQLDate		if (theValue instanceof SQLDate) {			restoreToNull();			encodedDate = ((SQLDate) theValue).encodedDate;		}        else        {            Calendar cal = new GregorianCalendar();			setValue(theValue.getDate( cal), cal);        }	}	/**		@see DateTimeDataValue#setValue	 */	public void setValue(Date value, Calendar cal) throws StandardException	{		restoreToNull();		encodedDate = computeEncodedDate((java.util.Date) value, cal);	}	/**		@see DateTimeDataValue#setValue	 */	public void setValue(Timestamp value, Calendar cal) throws StandardException	{		restoreToNull();		encodedDate = computeEncodedDate((java.util.Date) value, cal);	}	public void setValue(String theValue)	    throws StandardException	{		restoreToNull();		if (theValue != null)		{            DatabaseContext databaseContext = (DatabaseContext) ContextService.getContext(DatabaseContext.CONTEXT_ID);            parseDate( theValue,                       false,                       (databaseContext == null) ? null : databaseContext.getDatabase(),                       (Calendar) null);        }	}	/*	** SQL Operators	*/	/**	 * @see DateTimeDataValue#getYear	 * 	 * @exception StandardException		Thrown on error	 */	public NumberDataValue getYear(NumberDataValue result)							throws StandardException	{		if (SanityManager.DEBUG)		{			SanityManager.ASSERT(!isNull(), "getYear called on a null");		}		return SQLDate.setSource(getYear(encodedDate), result);	}	/**	 * @see DateTimeDataValue#getMonth	 * 	 * @exception StandardException		Thrown on error	 */	public NumberDataValue getMonth(NumberDataValue result)							throws StandardException	{		if (SanityManager.DEBUG)		{			SanityManager.ASSERT(!isNull(), "getMonth called on a null");		}		return SQLDate.setSource(getMonth(encodedDate), result);	}	/**	 * @see DateTimeDataValue#getDate	 * 	 * @exception StandardException		Thrown on error	 */	public NumberDataValue getDate(NumberDataValue result)							throws StandardException	{		if (SanityManager.DEBUG)		{			SanityManager.ASSERT(!isNull(), "getDate called on a null");		}		return SQLDate.setSource(getDay(encodedDate), result);	}	/**	 * @see DateTimeDataValue#getHours	 * 	 * @exception StandardException		Thrown on error	 */	public NumberDataValue getHours(NumberDataValue result)							throws StandardException	{		if (SanityManager.DEBUG)		{			SanityManager.ASSERT(!isNull(), "getHours called on null.");		}		throw StandardException.newException(SQLState.LANG_UNARY_FUNCTION_BAD_TYPE, 						"getHours", "Date");	}	/**	 * @see DateTimeDataValue#getMinutes	 * 	 * @exception StandardException		Thrown on error	 */	public NumberDataValue getMinutes(NumberDataValue result)							throws StandardException	{		if (SanityManager.DEBUG)		{			SanityManager.ASSERT(!isNull(), "getMinutes called on null.");		}		throw StandardException.newException(SQLState.LANG_UNARY_FUNCTION_BAD_TYPE, 						"getMinutes", "Date");	}	/**	 * @see DateTimeDataValue#getSeconds	 * 	 * @exception StandardException		Thrown on error	 */	public NumberDataValue getSeconds(NumberDataValue result)							throws StandardException	{		if (SanityManager.DEBUG)		{			SanityManager.ASSERT(!isNull(), "getSeconds called on null.");		}		throw StandardException.newException(SQLState.LANG_UNARY_FUNCTION_BAD_TYPE, 						"getSeconds", "Date");	}	/*	** String display of value	*/	public String toString()	{		if (isNull())		{			return "NULL";		}		else		{			return getDate( (Calendar) null).toString();		}	}	/*	 * Hash code	 */	public int hashCode()	{		return encodedDate;	}	/** @see DataValueDescriptor#typePrecedence */	public int	typePrecedence()	{		return TypeId.DATE_PRECEDENCE;	}	/**	 * Check if the value is null.  	 * encodedDate is 0 if the value is null	 *	 * @return Whether or not value is logically null.	 */	public final boolean isNull()	{		return (encodedDate == 0);	}	/**	 * Get the value field.  We instantiate the field	 * on demand.	 *	 * @return	The value field.	 */	public Date getDate( Calendar cal)	{		if (encodedDate != 0)            return new Date( getTimeInMillis( cal));		return null;	}	/**	 * Get the year from the encodedDate.	 *	 * @param encodedDate	the encoded date	 * @return	 			year value.	 */	static int getYear(int encodedDate)	{		return (encodedDate >>> 16);	}	/**	 * Get the month from the encodedDate.	 *	 * @param encodedDate	the encoded date	 * @return	 			month value.	 */	static int getMonth(int encodedDate)	{		return ((encodedDate >>> 8) & 0x00ff);	}	/**	 * Get the day from the encodedDate.	 *	 * @param encodedDate	the encoded date	 * @return	 			day value.	 */	static int getDay(int encodedDate)	{		return (encodedDate & 0x00ff);	}	/**	 *	computeEncodedDate extracts the year, month and date from	 *	a Calendar value and encodes them as	 *		year << 16 + month << 8 + date	 *	Use this function will help to remember to add 1 to month	 *  which is 0 based in the Calendar class	 *	@param value	the Calendar 	 *	@return 		the encodedDate     *     *  @exception StandardException if the value is out of the DB2 date range	 */	static int computeEncodedDate(Calendar cal) throws StandardException	{		return computeEncodedDate(cal.get(Calendar.YEAR),                                  cal.get(Calendar.MONTH) + 1,                                  cal.get(Calendar.DATE));	}    static int computeEncodedDate( int y, int m, int d) throws StandardException    {        int maxDay = 31;        switch( m)        {        case 4:        case 6:        case 9:        case 11:            maxDay = 30;            break;                        case 2:            // leap years are every 4 years except for century years not divisble by 400.            maxDay = ((y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0)) ? 29 : 28;            break;        }        if( y < 1 || y > 9999            || m < 1 || m > 12            || d < 1 || d > maxDay)            throw StandardException.newException( SQLState.LANG_DATE_RANGE_EXCEPTION);        return (y << 16) + (m << 8) + d;    }    /**     * Convert a date to the JDBC representation and append it to a string buffer.     *     * @param year     * @param month 1 based (January == 1)     * @param day     * @param sb The string representation is appended to this StringBuffer     */    static void dateToString( int year, int month, int day, StringBuffer sb)    {        String yearStr = Integer.toString( year);        for( int i = yearStr.length(); i < 4; i++)            sb.append( '0');		sb.append(yearStr);		sb.append(ISO_SEPARATOR);		String monthStr = Integer.toString( month);		String dayStr = Integer.toString( day);		if (monthStr.length() == 1)			sb.append('0');		sb.append(monthStr);		sb.append(ISO_SEPARATOR);		if (dayStr.length() == 1)			sb.append('0');		sb.append(dayStr);    } // end of dateToString    	/**	 * Get the String version from the encodedDate.	 *	 * @return	 string value.	 */	static String encodedDateToString(int encodedDate)	{		StringBuffer vstr = new StringBuffer();        dateToString( getYear(encodedDate), getMonth(encodedDate), getDay(encodedDate), vstr);		return vstr.toString();	}	// International Support	/**	 * International version of getString(). Overrides getNationalString	 * in DataType for date, time, and timestamp.	 *	 * @exception StandardException		Thrown on error	 */	protected String getNationalString(LocaleFinder localeFinder) throws StandardException	{		if (isNull())		{			return getString();		}		return localeFinder.getDateFormat().format(getDate(new GregorianCalendar()));	}	/**		This helper routine tests the nullability of various parameters		and sets up the result appropriately.		If source is null, a new NumberDataValue is built. 		@exception StandardException	Thrown on error	 */	static NumberDataValue setSource(int value,										NumberDataValue source)									throws StandardException {		/*		** NOTE: Most extract operations return int, so the generation of		** a SQLInteger is here.  Those extract operations that return		** something other than int must allocate the source NumberDataValue		** themselves, so that we do not allocate a SQLInteger here.		*/		if (source == null)			source = new SQLInteger();		source.setValue(value);		return source;	}	/**     * Compute the encoded date given a date	 *	 */	private static int computeEncodedDate(java.util.Date value) throws StandardException	{        return computeEncodedDate( value, null);    }    static int computeEncodedDate(java.util.Date value, Calendar currentCal) throws StandardException    {		if (value == null)			return 0;			//encoded dates have a 0 value for null        if( currentCal == null)            currentCal = new GregorianCalendar();		currentCal.setTime(value);		return SQLDate.computeEncodedDate(currentCal);	}        /**         * Implement the date SQL function: construct a SQL date from a string, number, or timestamp.         *         * @param operand Must be a date or a string convertible to a date.         * @param dvf the DataValueFactory         *         * @exception StandardException standard error policy         */    public static DateTimeDataValue computeDateFunction( DataValueDescriptor operand,                                                         DataValueFactory dvf) throws StandardException    {        try        {            if( operand.isNull())                return new SQLDate();            if( operand instanceof SQLDate)                return (SQLDate) operand.getClone();            if( operand instanceof SQLTimestamp)            {                DateTimeDataValue retVal = new SQLDate();                retVal.setValue( operand);                return retVal;            }            if( operand instanceof NumberDataValue)            {                int daysSinceEpoch = operand.getInt();                if( daysSinceEpoch <= 0 || daysSinceEpoch > 3652059)                    throw StandardException.newException( SQLState.LANG_INVALID_FUNCTION_ARGUMENT,                                                          operand.getString(), "date");                Calendar cal = new GregorianCalendar( 1970, 0, 1, 12, 0, 0);                cal.add( Calendar.DATE, daysSinceEpoch - 1);                return new SQLDate( computeEncodedDate( cal.get( Calendar.YEAR),                                                        cal.get( Calendar.MONTH) + 1,                                                        cal.get( Calendar.DATE)));            }            String str = operand.getString();            if( str.length() == 7)            {                // yyyyddd where ddd is the day of the year                int year = SQLTimestamp.parseDateTimeInteger( str, 0, 4);                int dayOfYear = SQLTimestamp.parseDateTimeInteger( str, 4, 3);                if( dayOfYear < 1 || dayOfYear > 366)                    throw StandardException.newException( SQLState.LANG_INVALID_FUNCTION_ARGUMENT,                                                          operand.getString(), "date");                Calendar cal = new GregorianCalendar( year, 0, 1, 2, 0, 0);                cal.add( Calendar.DAY_OF_YEAR, dayOfYear - 1);                int y = cal.get( Calendar.YEAR);                if( y != year)                    throw StandardException.newException( SQLState.LANG_INVALID_FUNCTION_ARGUMENT,                                                          operand.getString(), "date");                return new SQLDate( computeEncodedDate( year,                                                        cal.get( Calendar.MONTH) + 1,                                                        cal.get( Calendar.DATE)));            }            // Else use the standard cast.            return dvf.getDateValue( str, false);        }        catch( StandardException se)        {            if( SQLState.LANG_DATE_SYNTAX_EXCEPTION.startsWith( se.getSQLState()))                throw StandardException.newException( SQLState.LANG_INVALID_FUNCTION_ARGUMENT,                                                      operand.getString(), "date");            throw se;        }    } // end of computeDateFunction    /** Adding this method to ensure that super class' setInto method doesn't get called      * that leads to the violation of JDBC spec( untyped nulls ) when batching is turned on.      */         public void setInto(PreparedStatement ps, int position) throws SQLException, StandardException {                  ps.setDate(position, getDate((Calendar) null));     }    /**     * Add a number of intervals to a datetime value. Implements the JDBC escape TIMESTAMPADD function.     *     * @param intervalType One of FRAC_SECOND_INTERVAL, SECOND_INTERVAL, MINUTE_INTERVAL, HOUR_INTERVAL,     *                     DAY_INTERVAL, WEEK_INTERVAL, MONTH_INTERVAL, QUARTER_INTERVAL, or YEAR_INTERVAL     * @param intervalCount The number of intervals to add     * @param currentDate Used to convert time to timestamp     * @param resultHolder If non-null a DateTimeDataValue that can be used to hold the result. If null then     *                     generate a new holder     *     * @return startTime + intervalCount intervals, as a timestamp     *     * @exception StandardException     */    public DateTimeDataValue timestampAdd( int intervalType,                                           NumberDataValue intervalCount,                                           java.sql.Date currentDate,                                           DateTimeDataValue resultHolder)        throws StandardException    {        return toTimestamp().timestampAdd( intervalType, intervalCount, currentDate, resultHolder);    }    private SQLTimestamp toTimestamp() throws StandardException    {        return new SQLTimestamp( getEncodedDate(), 0, 0);    }        /**     * Finds the difference between two datetime values as a number of intervals. Implements the JDBC     * TIMESTAMPDIFF escape function.     *     * @param intervalType One of FRAC_SECOND_INTERVAL, SECOND_INTERVAL, MINUTE_INTERVAL, HOUR_INTERVAL,     *                     DAY_INTERVAL, WEEK_INTERVAL, MONTH_INTERVAL, QUARTER_INTERVAL, or YEAR_INTERVAL     * @param time1     * @param currentDate Used to convert time to timestamp     * @param resultHolder If non-null a NumberDataValue that can be used to hold the result. If null then     *                     generate a new holder     *     * @return the number of intervals by which this datetime is greater than time1     *     * @exception StandardException     */    public NumberDataValue timestampDiff( int intervalType,                                          DateTimeDataValue time1,                                          java.sql.Date currentDate,                                          NumberDataValue resultHolder)        throws StandardException    {        return toTimestamp().timestampDiff( intervalType, time1, currentDate, resultHolder);    }}

⌨️ 快捷键说明

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