ExtractExpression.java

  1. /*
  2. Copyright (c) 2017 Andrey Karepin

  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at

  6.     http://www.apache.org/licenses/LICENSE-2.0

  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */

  13. package com.healthmarketscience.sqlbuilder;

  14. import java.io.IOException;
  15. import com.healthmarketscience.common.util.AppendableExt;


  16. /**
  17.  * Outputs an extract expression like:
  18.  * <code>"EXTRACT(&lt;datePart&gt; FROM &lt;dateExpression&gt;)"</code>
  19.  *
  20.  * @see "SQL 2003"
  21.  * @author Andrey Karepin
  22.  */
  23. public class ExtractExpression extends Expression
  24. {
  25.   /**
  26.    * The SQL defined date parts for the extract expression.  Many databases
  27.    * have extensions to these choices which can be found in the relevant
  28.    * extensions module.
  29.    *
  30.    * @see com.healthmarketscience.sqlbuilder.custom.postgresql.PgExtractDatePart
  31.    * @see com.healthmarketscience.sqlbuilder.custom.mysql.MysExtractDatePart
  32.    * @see com.healthmarketscience.sqlbuilder.custom.oracle.OraExtractDatePart
  33.    */
  34.   public enum DatePart
  35.   {
  36.     YEAR,
  37.     MONTH,
  38.     DAY,
  39.     HOUR,
  40.     MINUTE,
  41.     SECOND,
  42.     TIMEZONE_HOUR,
  43.     TIMEZONE_MINUTE;
  44.   }

  45.   private final Object _datePart;
  46.   private final SqlObject _dateExpression;

  47.   public ExtractExpression(DatePart datePart, Object dateExpression) {
  48.     this((Object)datePart, dateExpression);
  49.   }

  50.   public ExtractExpression(Object datePart, Object dateExpression) {
  51.     _datePart = datePart;
  52.     _dateExpression = Converter.toColumnSqlObject(dateExpression);
  53.   }

  54.   @Override
  55.   public boolean hasParens() { return false; }

  56.   @Override
  57.   protected void collectSchemaObjects(ValidationContext vContext) {
  58.     _dateExpression.collectSchemaObjects(vContext);
  59.   }

  60.   @Override
  61.   public void appendTo(AppendableExt app) throws IOException {
  62.     app.append("EXTRACT(")
  63.       .append(_datePart)
  64.       .append(" FROM ")
  65.       .append(_dateExpression)
  66.       .append(")");
  67.   }
  68. }