View Javadoc
1   /*
2    *    Copyright 2016-2025 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.mybatis.dynamic.sql.select.function;
17  
18  import java.util.Objects;
19  import java.util.Optional;
20  
21  import org.jspecify.annotations.Nullable;
22  import org.mybatis.dynamic.sql.BasicColumn;
23  import org.mybatis.dynamic.sql.render.RenderingContext;
24  import org.mybatis.dynamic.sql.util.FragmentAndParameters;
25  
26  public class Cast implements BasicColumn {
27      private final BasicColumn column;
28      private final String targetType;
29      private final @Nullable String alias;
30  
31      private Cast(Builder builder) {
32          column = Objects.requireNonNull(builder.column);
33          targetType = Objects.requireNonNull(builder.targetType);
34          alias = builder.alias;
35      }
36  
37      @Override
38      public Optional<String> alias() {
39          return Optional.ofNullable(alias);
40      }
41  
42      @Override
43      public Cast as(String alias) {
44          return new Builder().withColumn(column)
45                  .withTargetType(targetType)
46                  .withAlias(alias)
47                  .build();
48      }
49  
50      @Override
51      public FragmentAndParameters render(RenderingContext renderingContext) {
52          return column.render(renderingContext).mapFragment(this::applyCast);
53      }
54  
55      private String applyCast(String in) {
56          return "cast(" + in + " as " + targetType + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
57      }
58  
59      public static class Builder {
60          private @Nullable BasicColumn column;
61          private @Nullable String targetType;
62          private @Nullable String alias;
63  
64          public Builder withColumn(BasicColumn column) {
65              this.column = column;
66              return this;
67          }
68  
69          public Builder withTargetType(String targetType) {
70              this.targetType = targetType;
71              return this;
72          }
73  
74          public Builder withAlias(String alias) {
75              this.alias = alias;
76              return this;
77          }
78  
79          public Cast build() {
80              return new Cast(this);
81          }
82      }
83  }