KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > daffodilwoods > daffodildb > server > sql99 > expression > datetimevalueexpression > truncfunction


1 package com.daffodilwoods.daffodildb.server.sql99.expression.
2     datetimevalueexpression;
3
4 import com.daffodilwoods.daffodildb.server.serversystem.*;
5 import com.daffodilwoods.daffodildb.server.sql99.common.*;
6 import com.daffodilwoods.daffodildb.server.sql99.expression.rowvalueexpression.*;
7 import com.daffodilwoods.daffodildb.server.sql99.expression.stringvalueexpression.*;
8 import com.daffodilwoods.daffodildb.server.sql99.token.*;
9 import com.daffodilwoods.daffodildb.server.sql99.utils.*;
10 import com.daffodilwoods.daffodildb.utils.*;
11 import com.daffodilwoods.daffodildb.utils.field.*;
12 import com.daffodilwoods.database.resource.*;
13 import java.sql.*;
14 import com.daffodilwoods.daffodildb.server.sql99.expression.numericvalueexpression.*;
15 import java.math.BigDecimal JavaDoc;
16
17 public class truncfunction
18     extends AbstractDateTimeValueFunction
19     implements com.daffodilwoods.daffodildb.utils.parser.StatementExecuter,
20     datetimevaluefunction, numericvaluefunction{
21
22   public Srightparen_1874859514 _Srightparen_18748595140;
23   public Scomma94843605characterstringliteral
24       _OptScomma94843605characterstringliteral1;
25   public datetimevalueexpression _datetimevalueexpression2;
26   public Sleftparen653880241 _Sleftparen6538802413;
27   public SNONRESERVEDWORD136444255 _SNONRESERVEDWORD1364442554;
28   int type1=-1, type2=-1;
29
30   public Object JavaDoc run(Object JavaDoc object) throws DException {
31     FieldBase expression = (FieldBase) _datetimevalueexpression2.run(object);
32     if (expression.isNull()) {
33       return new FieldTimeStampLiteral(FieldUtility.NULLBUFFERRANGE);
34     }
35     FieldBase truncFormat = null;
36     String JavaDoc foramt = "";
37     if (_OptScomma94843605characterstringliteral1 != null) {
38       truncFormat = (FieldBase) _OptScomma94843605characterstringliteral1.run(object);
39      type2 = getDataTypeForByte(_OptScomma94843605characterstringliteral1.getByteComparison(object));
40       foramt = truncFormat.getObject().toString();
41     }
42    type1 = getDataTypeForByte(_datetimevalueexpression2.getByteComparison(object));
43     return getResult(expression.getObject(), foramt, type1, type2);
44   }
45
46   /**
47    Trunc Function (with Timestamp)
48    --------------------------------------------------------------------------------
49    The trunc function returns a date truncated to a specific unit of measure.
50    The syntax for the trunc function is:
51    trunc ( date, [ format ] )
52    date is the date to truncate.
53    format is the unit of measure to apply for truncating.
54    If the format parameter is omitted, the trunc function will truncate the date to the nearest day.
55    Below are the valid format parameters:
56    Unit Valid format parameters
57    Year SYYYY, YYYY, YEAR, SYEAR, YYY, YY, Y
58    ISO Year IYYY, IY, I
59    Quarter Q
60    Month MONTH, MON, MM, RM
61    Week WW
62    IW IW
63    W W
64    Day DDD, DD, J
65    Start day of the week DAY, DY, D
66
67    Hour HH, HH12, HH24
68    Trunc to the beginning of the current hour:
69
70    TO_CHAR (TRUNC (TO_DATE ('11-SEP-1994 4:17 PM',
71                       'DD-MON-YYYY HH:MI AM'), 'HH'),
72        'DD-MON-YYYY HH:MI AM')
73    ==> 11-SEP-1994 04:00 PM
74
75    Minute MI
76    Trunc to the beginning of the current minute
77    For example:
78    trunc (date '22-AUG-03', 'YEAR') would return '01-JAN-03'
79    trunc (to_date ('22-AUG-03'), 'Q') would return '01-JUL-03'
80    trunc (to_date ('22-AUG-03'), 'MONTH') would return '01-AUG-03'
81    trunc (to_date ('22-AUG-03'), 'DDD') would return '22-AUG-03'
82    trunc (to_date ('22-AUG-03'), 'DAY') would return '17-AUG-03'
83    */

84
85   /**
86    *
87    * To handle the date value
88    * @param date Date
89    * @param format String
90    * @return Date
91    */

92   private Date trunc(Date date, String JavaDoc format) {
93     format = format.trim();
94     if (checkForYear(format)) {
95       return getYearDate(date);
96     }
97     else if (checkForQuarter(format)) {
98       return getQuarterDate(date);
99     }
100     else if (checkForMonth(format)) {
101       return getMonthDate(date);
102     }
103     else if (checkForDay(format)) {
104       return getDayDate(date);
105     }
106     return date;
107   }
108
109   /**
110    * This method is implemented to handle the timestamp data type
111    * @param timestamp Timestamp
112    * @param format String
113    * @return Timestamp
114    */

115   private Timestamp trunc(Timestamp timestamp, String JavaDoc format) {
116     format =format.trim();
117     if (checkForYear(format)) {
118       return truncateYear(timestamp);
119     }
120     else if (checkForQuarter(format)) {
121       return truncateQuarter(timestamp);
122     }
123     else if (checkForMonth(format)) {
124       return truncateMonth(timestamp);
125     }
126     else if (checkForDay(format)) {
127       return truncateDay(timestamp);
128     } else if(checkForHour(format)) {
129       return truncHour(timestamp);
130     }else if(checkForMinute(format)) {
131        return truncMinute(timestamp);
132     }
133     return timestamp;
134   }
135
136   /*
137    Trunc to the first of the current year:
138    TRUNC (TO_DATE ('01-MAR-1994'), 'YYYY') ==> 01-JAN-1994
139    TRUNC (TO_DATE ('01-SEP-1994'), 'YEAR') ==> 01-JAN-1994
140    */

141
142   private Date getYearDate(Date date) {
143     String JavaDoc YYYY = String.valueOf(date.getYear() + 1900);
144     return Date.valueOf(YYYY + "-01-01");
145   }
146
147
148  /*
149  Trunc to the first of the current year:
150  TRUNC (TO_DATE ('01-MAR-1994'), 'YYYY') ==> 01-JAN-1994
151  TRUNC (TO_DATE ('01-SEP-1994'), 'YEAR') ==> 01-JAN-1994
152  */

153
154   private Timestamp truncateYear(Timestamp timestamp) {
155     String JavaDoc YYYY = String.valueOf(timestamp.getYear() + 1900);
156     return Timestamp.valueOf(YYYY + "-01-01 " + timestamp.getHours() + ":" +
157                              timestamp.getMinutes() + ":" +
158                              timestamp.getSeconds()+"."+timestamp.getNanos());
159   }
160   /*
161   Trunc to the first day of the quarter:
162   TRUNC (TO_DATE ('01-MAR-1994'), 'Q') ==> 01-JAN-1994
163   TRUNC (TO_DATE ('15-APR-1994'), 'Q') ==> 01-APR-1994
164   */

165
166   private Date getQuarterDate(Date dates) {
167     String JavaDoc year = String.valueOf(dates.getYear() + 1900);
168     int mm = dates.getMonth() + 1;
169     if (mm <= 3) {
170       mm = 1;
171     }
172     else if (mm <= 6) {
173       mm = 4;
174     }
175     else if (mm <= 9) {
176       mm = 7;
177     }
178     else if (mm <= 12) {
179       mm = 10;
180     }
181     return Date.valueOf(year + "-" + mm + "-01");
182   }
183
184   private Timestamp truncateQuarter(Timestamp timestamp) {
185     String JavaDoc year = String.valueOf(timestamp.getYear() + 1900);
186     int mm = timestamp.getMonth() + 1;
187     if (mm <= 3) {
188       mm = 1;
189     }
190     else if (mm <= 6) {
191       mm = 4;
192     }
193     else if (mm <= 9) {
194       mm = 7;
195     }
196     else if (mm <= 12) {
197       mm = 10;
198     }
199     return Timestamp.valueOf(year + "-" + mm + "-01 " + timestamp.getHours() +
200                              ":" + timestamp.getMinutes() + ":" +
201                              timestamp.getSeconds()+"."+timestamp.getNanos());
202   }
203
204
205
206   private boolean checkForYear(String JavaDoc year) {
207     if (year.equalsIgnoreCase("SYYYY") || year.equalsIgnoreCase("YYYY") ||
208         year.equalsIgnoreCase("YEAR") || year.equalsIgnoreCase("SYEAR") ||
209         year.equalsIgnoreCase("YYY") || year.equalsIgnoreCase("YY") ||
210         year.equalsIgnoreCase("Y")) {
211       return true;
212     }
213     else {
214       return false;
215     }
216   }
217
218
219   private boolean checkForQuarter(String JavaDoc year) {
220     if (year.equalsIgnoreCase("Quarter") || year.equalsIgnoreCase("Q")) {
221       return true;
222     }
223     else {
224       return false;
225     }
226   }
227
228   private boolean checkForMonth(String JavaDoc year) {
229     if (year.equalsIgnoreCase("Month") || year.equalsIgnoreCase("MONTH") ||
230         year.equalsIgnoreCase("MON") || year.equalsIgnoreCase("MM") ||
231         year.equalsIgnoreCase("RM")) {
232       return true;
233     }
234     else {
235       return false;
236     }
237   }
238
239
240   private boolean checkForDay(String JavaDoc year) {
241     if (year.equalsIgnoreCase("Day") || year.equalsIgnoreCase("DDD") ||
242         year.equalsIgnoreCase("DD") || year.equalsIgnoreCase("J")||year.equalsIgnoreCase("DY")) {
243       return true;
244     }
245     else {
246       return false;
247
248     }
249   }
250
251   private boolean checkForHour(String JavaDoc hour) {
252     if (hour.equalsIgnoreCase("Hour") || hour.equalsIgnoreCase("HH") ||
253         hour.equalsIgnoreCase("HH12") || hour.equalsIgnoreCase("HH24")) {
254       return true;
255     }
256     else {
257       return false;
258
259     }
260   }
261
262
263
264   private boolean checkForMinute(String JavaDoc minute) {
265     if (minute.equalsIgnoreCase("Minute") || minute.equalsIgnoreCase("MI")) {
266       return true;
267     }
268     else {
269       return false;
270
271     }
272   }
273
274
275
276   private Date getMonthDate(Date date) {
277     String JavaDoc YYYY = String.valueOf(date.getYear() + 1900);
278     String JavaDoc MM = String.valueOf(date.getMonth() + 1);
279     return Date.valueOf(YYYY + "-" + MM + "-01");
280   }
281
282   /*
283   Trunc to the first of the month:
284   TRUNC (TO_DATE ('12-MAR-1994'), 'MONTH') ==> 01-MAR-1994
285   TRUNC (TO_DATE ('17-MAR-1994'), 'MM') ==> 01-APR-1994
286   */

287
288   private Timestamp truncateMonth(Timestamp timestamp) {
289     String JavaDoc YYYY = String.valueOf(timestamp.getYear() + 1900);
290     String JavaDoc MM = String.valueOf(timestamp.getMonth() + 1);
291     String JavaDoc times =YYYY + "-" + MM + "-01 " +timestamp.getHours() +":" + timestamp.getMinutes() + ":" +timestamp.getSeconds()+"."+timestamp.getNanos();
292     return Timestamp.valueOf(times);
293
294   }
295
296    /*
297      Trunc back to the beginning of the current day (time is always midnight):
298     */

299
300   private Date getDayDate(Date date) {
301     String JavaDoc YYYY = String.valueOf(date.getYear() + 1900);
302     String JavaDoc MM = String.valueOf(date.getMonth() + 1);
303     String JavaDoc DD = String.valueOf(date.getDate());
304     int dates = date.getDate();
305     java.util.GregorianCalendar JavaDoc calendar = new java.util.GregorianCalendar JavaDoc();
306     calendar.setTime(date);
307     int dayofWeek = calendar.get(java.util.Calendar.DAY_OF_WEEK);
308     dates = dates - (dayofWeek - 1);
309     return Date.valueOf(YYYY + "-" + MM + "-" + dates);
310   }
311
312   /*
313      Trunc back to the beginning of the current day (time is always midnight):
314    TO_CHAR (TRUNC (TO_DATE ('11-SEP-1994 10:00 AM',
315                       'DD-MON-YYYY HH:MI AM'), 'DD'),
316          'DD-MON-YYYY HH:MI AM')
317      ==> 11-SEP-1994 12:00 AM
318
319     TO_CHAR (TRUNC (TO_DATE ('11-SEP-1994 4:00 PM',
320                       'DD-MON-YYYY HH:MI AM'), 'DD'),
321          'DD-MON-YYYY HH:MI AM')
322     ==> 11-SEP-1994 12:00 AM
323
324     */

325
326   private Timestamp truncateDay(Timestamp timestamp) {
327     String JavaDoc YYYY = String.valueOf(timestamp.getYear() + 1900);
328     String JavaDoc MM = String.valueOf(timestamp.getMonth() + 1);
329     String JavaDoc DD = String.valueOf(timestamp.getDate());
330     int dates = timestamp.getDate();
331     java.util.GregorianCalendar JavaDoc calendar = new java.util.GregorianCalendar JavaDoc();
332     calendar.setTime(timestamp);
333     int dayofWeek = calendar.get(java.util.Calendar.DAY_OF_WEEK);
334     dates = dates - (dayofWeek - 1);
335     return Timestamp.valueOf(YYYY + "-" + MM + "-" + dates +" "+timestamp.getHours() +
336                              ":" + timestamp.getMinutes() + ":" +timestamp.getSeconds()+"."+timestamp.getNanos());
337
338   }
339
340   /*
341   Trunc to the beginning of the current hour:
342     TO_CHAR (TRUNC (TO_DATE ('11-SEP-1994 4:17 PM',
343                        'DD-MON-YYYY HH:MI AM'), 'HH'),
344         'DD-MON-YYYY HH:MI AM')
345     ==> 11-SEP-1994 04:00 PM
346    */

347
348   private Timestamp truncHour(Timestamp timestamp) {
349      String JavaDoc YYYY = String.valueOf(timestamp.getYear() + 1900);
350      String JavaDoc MM = String.valueOf(timestamp.getMonth() + 1);
351      String JavaDoc DD = String.valueOf(timestamp.getDate());
352      String JavaDoc HH = String.valueOf(timestamp.getHours());
353      return Timestamp.valueOf(YYYY + "-" + MM + "-" + DD +" "+HH+":00:00.0");
354    }
355    /*
356    Trunc to the beginning of the current minute
357     */

358    private Timestamp truncMinute(Timestamp timestamp) {
359    String JavaDoc YYYY = String.valueOf(timestamp.getYear() + 1900);
360    String JavaDoc MM = String.valueOf(timestamp.getMonth() + 1);
361    String JavaDoc DD = String.valueOf(timestamp.getDate());
362    String JavaDoc HH = String.valueOf(timestamp.getHours());
363    String JavaDoc mm = String.valueOf(timestamp.getMinutes());
364    return Timestamp.valueOf(YYYY + "-" + MM + "-" + DD +" "+HH+":"+mm+":00.0");
365
366  }
367
368
369
370   protected ParameterInfo[] getThisParameterInfo() throws DException {
371     return new ParameterInfo[0];
372     /* ParameterInfo parameterInfo = new ParameterInfo();
373      parameterInfo.setName(toString());
374      parameterInfo.setDataType(INTEGER);
375      return new ParameterInfo[] {parameterInfo};*/

376   }
377
378   protected Object JavaDoc getResult(Object JavaDoc expression, String JavaDoc truncfromat0, int type1,
379                               int type2) throws DException {
380
381      int count = 0;
382      switch (type1) {
383        case DATE:
384          Date dt = (Date) expression;
385          if(type2==-1)
386               return new FieldDateLiteral(dt);
387          switch (type2) {
388            case CHARACTER:
389            case VARCHAR:
390            case CHAR:
391            case CHARACTERVARYING:
392              return new FieldDateLiteral(trunc(dt, truncfromat0));
393            default:
394              throw new DException("DSE4108",
395                                   new Object JavaDoc[] {StaticClass.
396                                   getDataTypeName(type2), "TRUNC"});
397          }
398        case TIMESTAMP:
399          Timestamp tm = (Timestamp) expression;
400          if(type2==-1)
401               return new FieldTimeStampLiteral(tm);
402          switch (type2) {
403             case CHARACTER:
404             case VARCHAR:
405             case CHAR:
406             case CHARACTERVARYING:
407             return new FieldTimeStampLiteral(trunc(tm, truncfromat0));
408             default:
409              throw new DException("DSE4108",new Object JavaDoc[] {StaticClass.getDataTypeName(type2), "TRUNC"});
410          }
411          case TINYINT:
412          case BYTE:
413          case SHORT:
414          case SMALLINT:
415          case INT:
416          case INTEGER:
417            Number JavaDoc number = (Number JavaDoc) expression;
418            if(!truncfromat0.equalsIgnoreCase(""))
419            count = getCount(truncfromat0).intValue();
420            return new FieldLiteral(new Integer JavaDoc(number.intValue()), INTEGER);
421          case BIGINT:
422          case LONG:
423             Long JavaDoc longV = (Long JavaDoc) expression;
424             if(!truncfromat0.equalsIgnoreCase(""))
425            count = getCount(truncfromat0).intValue();
426             return new FieldLiteral(longV, LONG);
427          case REAL:
428             if(!truncfromat0.equalsIgnoreCase(""))
429             count = getCount(truncfromat0).intValue();
430             Float JavaDoc floatV = (Float JavaDoc) expression;
431             return new FieldLiteral(new Float JavaDoc(truncate(floatV.doubleValue(), count)), FLOAT);
432          case DOUBLE:
433          case FLOAT:
434          case DOUBLEPRECISION:
435             Double JavaDoc doubleV = (Double JavaDoc) expression;
436             if(!truncfromat0.equalsIgnoreCase(""))
437            count = getCount(truncfromat0).intValue();
438             return new FieldLiteral(new Double JavaDoc(truncate(doubleV.doubleValue(), count)), DOUBLE);
439          case BIGDECIMAL:
440          case DEC:
441          case DECIMAL:
442          case NUMERIC:
443             BigDecimal JavaDoc bigDecimal = (BigDecimal JavaDoc) expression;
444             if(!truncfromat0.equalsIgnoreCase(""))
445             count = getCount(truncfromat0).intValue();
446             return new FieldLiteral(truncate(bigDecimal, count), BIGDECIMAL);
447        default:
448          throw new DException("DSE4108",
449                               new Object JavaDoc[] {StaticClass.getDataTypeName(type1),
450                               "TRUNC"});
451      }
452    }
453
454    public double truncate(double number, int places) throws DException {
455         double d = Math.pow(10, places);
456         return Math.floor(number * d) / d;
457      }
458
459      public BigDecimal JavaDoc truncate(BigDecimal JavaDoc number, int places) throws DException {
460        return number.setScale(places,BigDecimal.ROUND_DOWN);
461      }
462
463
464      private Integer JavaDoc getCount(String JavaDoc object) throws DException {
465                Double JavaDoc d = null;
466                 try {
467                   String JavaDoc string = (String JavaDoc) object;
468                    d = new Double JavaDoc(string);
469                 } catch (Exception JavaDoc e) {
470                    throw new DException("DSE4104", null);
471                 }
472                 return new Integer JavaDoc(d.intValue());
473        }
474
475   public AbstractRowValueExpression[] getChilds() {
476
477     if (_OptScomma94843605characterstringliteral1 == null) {
478       return new AbstractRowValueExpression[] {
479           (AbstractRowValueExpression) (_datetimevalueexpression2)};
480     }
481     else {
482       return new AbstractRowValueExpression[] {
483           (AbstractRowValueExpression) (_datetimevalueexpression2),
484           (AbstractRowValueExpression)
485           _OptScomma94843605characterstringliteral1
486       };
487
488     }
489   }
490
491   public int getFunctionType() {
492     return TIMESTAMPFUNCTION;
493   }
494
495   public Object JavaDoc clone() throws CloneNotSupportedException JavaDoc {
496     truncfunction tempClass = new truncfunction();
497     tempClass._Srightparen_18748595140 = (Srightparen_1874859514)
498         _Srightparen_18748595140.clone();
499     tempClass._datetimevalueexpression2 = (datetimevalueexpression)
500         _datetimevalueexpression2.clone();
501     if (_OptScomma94843605characterstringliteral1 != null) {
502       tempClass._OptScomma94843605characterstringliteral1 = (
503           Scomma94843605characterstringliteral)
504           _OptScomma94843605characterstringliteral1.clone();
505     }
506     tempClass._Sleftparen6538802413 = (Sleftparen653880241)
507         _Sleftparen6538802413.clone();
508     tempClass._SNONRESERVEDWORD1364442554 = (SNONRESERVEDWORD136444255)
509         _SNONRESERVEDWORD1364442554.clone();
510     return tempClass;
511   }
512
513   public ByteComparison getByteComparison(Object JavaDoc object) throws DException {
514     int dt = getDataTypeForByte(_datetimevalueexpression2.getByteComparison(object));
515     ByteComparison byteComparison = new ByteComparison(false, new int[] {dt});
516     byteComparison.setSize(getColumnSize(object));
517     return byteComparison;
518   }
519
520   public String JavaDoc getType() throws DException {
521     return (String JavaDoc) _SNONRESERVEDWORD1364442554.run(null);
522   }
523
524   public _Reference[] checkSemantic(_ServerSession parent) throws DException {
525     _Reference[] ref = super.checkSemantic(parent);
526     if (ref != null) {
527       return ref;
528     }
529     int type = _datetimevalueexpression2.getByteComparison(parent).getDataTypes()[
530         0];
531     switch (type) {
532       case -1:
533       case DATE:
534       case TIMESTAMP :
535         return ref;
536       default:
537         throw new DException("DSE4108",
538                              new Object JavaDoc[] {StaticClass.getDataTypeName(type),
539                              "Trunc"});
540     }
541
542   }
543
544   public ParameterInfo[] getParameterInfo() throws DException {
545     return new ParameterInfo[0];
546   }
547
548   public int getColumnSize(Object JavaDoc object) throws DException {
549     return Datatypes.TIMESTAMPSIZE;
550   }
551
552   public String JavaDoc toString() {
553     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
554     sb.append(" ");
555     sb.append(_SNONRESERVEDWORD1364442554);
556     sb.append(" ");
557     sb.append(_Sleftparen6538802413);
558     sb.append(" ");
559     sb.append(_datetimevalueexpression2);
560     sb.append(" ");
561     if (_OptScomma94843605characterstringliteral1 != null) {
562       sb.append(_OptScomma94843605characterstringliteral1);
563     }
564     sb.append(" ");
565     sb.append(_Srightparen_18748595140);
566     return sb.toString();
567   }
568
569
570 }
571
Popular Tags