01 /*
02 * SPDX-License-Identifier: Apache-2.0
03 *
04 * Copyright 2020-2022 Agorapulse.
05 *
06 * Licensed under the Apache License, Version 2.0 (the "License");
07 * you may not use this file except in compliance with the License.
08 * You may obtain a copy of the License at
09 *
10 * https://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package com.agorapulse.micronaut.bigquery.mock;
19
20 import com.agorapulse.micronaut.bigquery.RowResult;
21 import java.sql.ResultSet;
22 import java.sql.SQLException;
23 import java.time.Instant;
24 import java.util.Optional;
25
26 public class SqlRowResult implements RowResult {
27
28 @FunctionalInterface
29 private interface Extractor<R> {
30
31 R extract(String key) throws SQLException;
32
33 }
34
35 private final ResultSet result;
36
37 public SqlRowResult(ResultSet result) {
38 this.result = result;
39 }
40
41 @Override
42 public boolean isNull(String key) {
43 return getValue(key, k -> result.getObject(key) == null);
44 }
45
46 @Override
47 public Boolean getBooleanValue(String key) {
48 return getValue(key, result::getBoolean);
49 }
50
51 @Override
52 public Double getDoubleValue(String key) {
53 return getValue(key, result::getDouble);
54 }
55
56 @Override
57 public String getStringValue(String key) {
58 return getValue(key, result::getString);
59 }
60
61 @Override
62 public Long getLongValue(String key) {
63 return getValue(key, result::getLong);
64 }
65
66 @Override
67 public Instant getTimestampValue(String key) {
68 return getValue(key, k -> Optional.ofNullable(result.getTimestamp(k)).map(date -> Instant.ofEpochMilli(date.getTime())).orElse(null));
69 }
70
71 private <R> R getValue(String key, Extractor<R> extractor) {
72 try {
73 return extractor.extract(key);
74 } catch (SQLException e) {
75 throw new IllegalArgumentException("Cannot read value " + key, e);
76 }
77 }
78
79
80
81 }
|