View Javadoc
1   /*
2    * Tentackle - https://tentackle.org
3    *
4    * This library is free software; you can redistribute it and/or
5    * modify it under the terms of the GNU Lesser General Public
6    * License as published by the Free Software Foundation; either
7    * version 2.1 of the License, or (at your option) any later version.
8    *
9    * This library is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12   * Lesser General Public License for more details.
13   *
14   * You should have received a copy of the GNU Lesser General Public
15   * License along with this library; if not, write to the Free Software
16   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17   */
18  
19  package org.tentackle.dbms.dsl;
20  
21  import org.tentackle.sql.Backend;
22  import org.tentackle.sql.DataType;
23  
24  import java.util.Objects;
25  
26  /**
27   * A value bound to the prepared statement.
28   * <p>
29   * The value never becomes part of the SQL code but is applied to the statement
30   * by {@link org.tentackle.dbms.Query#applyParameters}. Since a value may span more than
31   * one column, a question mark is emitted per column, but the value is registered only once.
32   *
33   * @param <T> the java type of the value
34   * @author harald
35   */
36  public class BindValue<T> implements Expression<T> {
37  
38    private final T value;                // the value, never null
39    private final DataType<T> dataType;   // the datatype; may be null if unknown
40  
41  
42    /**
43     * Creates a bind value.
44     *
45     * @param value the value, never null
46     * @param dataType the datatype, null to determine it from the value's class
47     */
48    public BindValue(T value, DataType<T> dataType) {
49      this.value = Objects.requireNonNull(value, "value must be provided, use isNull() or isNotNull() instead");
50      this.dataType = dataType;
51    }
52  
53  
54    /**
55     * Gets the value.
56     *
57     * @return the value, never null
58     */
59    public T getValue() {
60      return value;
61    }
62  
63    @Override
64    public DataType<T> getDataType() {
65      return dataType;
66    }
67  
68    @Override
69    public void render(RenderContext context, int columnIndex) {
70      if (columnIndex == 0) {
71        // the parameter is applied to as many question marks as its datatype spans columns
72        context.addParameter(value);
73      }
74      context.append(Backend.SQL_PAR);
75    }
76  
77  }