|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License |
| 4 | + * 2.0; you may not use this file except in compliance with the Elastic License |
| 5 | + * 2.0. |
| 6 | + */ |
| 7 | + |
| 8 | +package org.elasticsearch.xpack.sql.qa.single_node; |
| 9 | + |
| 10 | +import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; |
| 11 | +import org.elasticsearch.common.CheckedConsumer; |
| 12 | +import org.elasticsearch.common.UUIDs; |
| 13 | +import org.elasticsearch.common.collect.Tuple; |
| 14 | +import org.elasticsearch.xpack.sql.qa.jdbc.JdbcIntegrationTestCase; |
| 15 | + |
| 16 | +import java.io.IOException; |
| 17 | +import java.nio.file.Files; |
| 18 | +import java.nio.file.Path; |
| 19 | +import java.sql.ResultSet; |
| 20 | +import java.util.ArrayList; |
| 21 | +import java.util.LinkedHashMap; |
| 22 | +import java.util.LinkedHashSet; |
| 23 | +import java.util.List; |
| 24 | +import java.util.Locale; |
| 25 | +import java.util.Map; |
| 26 | +import java.util.Objects; |
| 27 | +import java.util.Set; |
| 28 | + |
| 29 | +import static java.lang.String.join; |
| 30 | +import static java.util.Arrays.asList; |
| 31 | +import static java.util.stream.Collectors.joining; |
| 32 | +import static java.util.stream.Collectors.toList; |
| 33 | +import static org.elasticsearch.common.collect.Tuple.tuple; |
| 34 | +import static org.hamcrest.collection.IsEmptyCollection.empty; |
| 35 | + |
| 36 | +/** |
| 37 | + * <p>This test was introduced because of the inconsistencies regarding NULL argument handling. NULL literal vs NULL field |
| 38 | + * value as function arguments in some case result in different function return values.</p> |
| 39 | + * |
| 40 | + * <p>Functions should return with the same value no matter if the argument(s) came from a field or from a literal.</p> |
| 41 | + * |
| 42 | + * <p>The test class based on the example function calls (and argument specifications) generates all the |
| 43 | + * permutations of the function arguments (4 options per argument: value/NULL as literal/field) and tests that the |
| 44 | + * function calls with the same argument values provide the same result regardless of the source (literal, field) |
| 45 | + * of the arguments.</p> |
| 46 | + * |
| 47 | + * <p>To ignore any of the tests, add an .ignore() method call after the Fn ctors in the FUNCTION_CALLS_TO_TEST list below, like: |
| 48 | + * <code> new Fn("ASCII", "foobar").ignore()</code></p> |
| 49 | + */ |
| 50 | +public class ConsistentFunctionArgHandlingIT extends JdbcIntegrationTestCase { |
| 51 | + |
| 52 | + private static final List<Fn> FUNCTION_CALLS_TO_TEST = asList( |
| 53 | + new Fn("ASCII", "foobar"), |
| 54 | + new Fn("BIT_LENGTH", "foobar"), |
| 55 | + new Fn("CHAR", 66), |
| 56 | + new Fn("CHAR_LENGTH", "foobar").aliases("CHARACTER_LENGTH"), |
| 57 | + new Fn("CONCAT", "foo", "bar"), |
| 58 | + new Fn("INSERT", "foobar", 2, 3, "replacement"), |
| 59 | + new Fn("LCASE", "STRING"), |
| 60 | + new Fn("LEFT", "foobar", 3), |
| 61 | + new Fn("LENGTH", "foobar"), |
| 62 | + new Fn("LOCATE", "ob", "foobar", 1), |
| 63 | + new Fn("LTRIM", " foobar"), |
| 64 | + new Fn("OCTET_LENGTH", "foobar"), |
| 65 | + new Fn("POSITION", "foobar", "ob"), |
| 66 | + new Fn("REPEAT", "foobar", 10), |
| 67 | + new Fn("REPLACE", "foo", "o", "bar"), |
| 68 | + new Fn("RIGHT", "foobar", 3), |
| 69 | + new Fn("RTRIM", "foobar "), |
| 70 | + new Fn("SPACE", 5), |
| 71 | + new Fn("STARTS_WITH", "foobar", "foo"), |
| 72 | + new Fn("SUBSTRING", "foobar", 1, 2), |
| 73 | + new Fn("TRIM", " foobar "), |
| 74 | + new Fn("UCASE", "foobar") |
| 75 | + ); |
| 76 | + |
| 77 | + private static final List<String> NON_TESTED_FUNCTIONS; |
| 78 | + static { |
| 79 | + try { |
| 80 | + Class<?> c = ConsistentFunctionArgHandlingIT.class; |
| 81 | + NON_TESTED_FUNCTIONS = Files.readAllLines(Path.of(c.getResource(c.getSimpleName() + "-non-tested-functions.txt").toURI())); |
| 82 | + } catch (Exception ex) { |
| 83 | + throw new RuntimeException(ex); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + private enum Source { |
| 88 | + FIELD, |
| 89 | + LITERAL |
| 90 | + } |
| 91 | + |
| 92 | + private static class Fn { |
| 93 | + private final String name; |
| 94 | + private final List<Argument> arguments; |
| 95 | + private List<String> aliases = new ArrayList<>(); |
| 96 | + private boolean ignored = false; |
| 97 | + |
| 98 | + private Fn(String name, Object... arguments) { |
| 99 | + this.name = name; |
| 100 | + this.arguments = new ArrayList<>(); |
| 101 | + for (Object a : arguments) { |
| 102 | + this.arguments.add(new Argument(a)); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + public Fn aliases(String... aliases) { |
| 107 | + this.aliases = asList(aliases); |
| 108 | + return this; |
| 109 | + } |
| 110 | + |
| 111 | + public Fn ignore() { |
| 112 | + this.ignored = true; |
| 113 | + return this; |
| 114 | + } |
| 115 | + |
| 116 | + @Override |
| 117 | + public String toString() { |
| 118 | + return name + "(" + arguments.stream().map(a -> String.valueOf(a.exampleValue)).collect(joining(", ")) + ")"; |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + private static class Argument { |
| 123 | + private final Object exampleValue; |
| 124 | + private final Source[] acceptedSources; |
| 125 | + |
| 126 | + private Argument(Object exampleValue, Source... acceptedSources) { |
| 127 | + this.exampleValue = exampleValue; |
| 128 | + this.acceptedSources = acceptedSources.length == 0 ? Source.values() : acceptedSources; |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + @ParametersFactory |
| 133 | + public static Iterable<Object[]> testFactory() { |
| 134 | + List<Object[]> tests = new ArrayList<>(); |
| 135 | + tests.add(new Object[] { null }); |
| 136 | + FUNCTION_CALLS_TO_TEST.forEach(f -> tests.add(new Object[] { f })); |
| 137 | + return tests; |
| 138 | + } |
| 139 | + |
| 140 | + private final Fn fn; |
| 141 | + |
| 142 | + public ConsistentFunctionArgHandlingIT(Fn fn) { |
| 143 | + this.fn = fn; |
| 144 | + } |
| 145 | + |
| 146 | + public void test() throws Exception { |
| 147 | + if (fn == null) { |
| 148 | + checkScalarFunctionCoverage(); |
| 149 | + return; |
| 150 | + } |
| 151 | + |
| 152 | + assumeFalse("Ignored", fn.ignored); |
| 153 | + |
| 154 | + // create a record for the function, where all the example (non-null) argument values are stored in fields |
| 155 | + // so the field mapping is automatically set up |
| 156 | + final String functionName = fn.name; |
| 157 | + final String indexName = "test"; |
| 158 | + final String argPrefix = "arg_" + functionName + "_"; |
| 159 | + final String nullArgPrefix = "arg_null_" + functionName + "_"; |
| 160 | + final String testDocId = functionName + "_" + UUIDs.base64UUID(); |
| 161 | + |
| 162 | + indexTestDocForFunction(functionName, indexName, argPrefix, nullArgPrefix, testDocId); |
| 163 | + |
| 164 | + List<List<Object>> possibleValuesPerArguments = fn.arguments.stream().map(a -> asList(a.exampleValue, null)).collect(toList()); |
| 165 | + List<List<Source>> acceptedSourcesPerArguments = fn.arguments.stream().map(a -> asList(a.acceptedSources)).collect(toList()); |
| 166 | + |
| 167 | + iterateAllPermutations(possibleValuesPerArguments, argValues -> { |
| 168 | + // we only want to check the function calls that have at least a single NULL argument |
| 169 | + if (argValues.stream().noneMatch(Objects::isNull)) { |
| 170 | + return; |
| 171 | + } |
| 172 | + |
| 173 | + List<Tuple<String, Object>> results = new ArrayList<>(); |
| 174 | + |
| 175 | + iterateAllPermutations(acceptedSourcesPerArguments, argSources -> { |
| 176 | + List<String> functionCallArgs = new ArrayList<>(); |
| 177 | + List<String> functionCallArgsForAssert = new ArrayList<>(); |
| 178 | + for (int argIndex = 0; argIndex < argValues.size(); argIndex++) { |
| 179 | + final Object argValue = argValues.get(argIndex); |
| 180 | + final Source argSource = argSources.get(argIndex); |
| 181 | + final String valueAsLiteral = asLiteralInQuery(argValue); |
| 182 | + switch (argSource) { |
| 183 | + case LITERAL: |
| 184 | + functionCallArgs.add(valueAsLiteral); |
| 185 | + break; |
| 186 | + case FIELD: |
| 187 | + final String argFieldName = (argValue == null ? nullArgPrefix : argPrefix) + (argIndex + 1); |
| 188 | + functionCallArgs.add(argFieldName); |
| 189 | + break; |
| 190 | + } |
| 191 | + functionCallArgsForAssert.add(valueAsLiteral + "{" + argSource.name().charAt(0) + "}"); |
| 192 | + } |
| 193 | + |
| 194 | + final String functionCall = functionName + "(" + join(", ", functionCallArgs) + ")"; |
| 195 | + final String query = "SELECT " + functionCall + " FROM " + indexName + " WHERE docId = '" + testDocId + "'"; |
| 196 | + ResultSet retVal = esJdbc().createStatement().executeQuery(query); |
| 197 | + |
| 198 | + assertTrue(retVal.next()); |
| 199 | + results.add(tuple(functionName + "(" + join(", ", functionCallArgsForAssert) + ")", retVal.getObject(1))); |
| 200 | + // only a single row should be returned |
| 201 | + assertFalse(retVal.next()); |
| 202 | + |
| 203 | + if (results.stream().map(Tuple::v2).distinct().count() > 1) { |
| 204 | + int maxResultWidth = results.stream().map(Tuple::v2).mapToInt(o -> asLiteralInQuery(o).length()).max().orElse(20); |
| 205 | + String resultsAsString = results.stream() |
| 206 | + .map(r -> String.format(Locale.ROOT, "%2$-" + maxResultWidth + "s // %1$s", r.v1(), asLiteralInQuery(r.v2()))) |
| 207 | + .collect(joining("\n")); |
| 208 | + fail("The result of the last call differs from the other calls:\n" + resultsAsString); |
| 209 | + } |
| 210 | + }); |
| 211 | + }); |
| 212 | + } |
| 213 | + |
| 214 | + private void indexTestDocForFunction(String functionName, String indexName, String argPrefix, String nullArgPrefix, String testDocId) |
| 215 | + throws IOException { |
| 216 | + Map<String, Object> testDoc = new LinkedHashMap<>(); |
| 217 | + testDoc.put("docId", testDocId); |
| 218 | + int idx = 0; |
| 219 | + for (Argument arg : fn.arguments) { |
| 220 | + idx += 1; |
| 221 | + testDoc.put(argPrefix + idx, arg.exampleValue); |
| 222 | + // first set the same value, so the mapping is populated for the null columns |
| 223 | + testDoc.put(nullArgPrefix + idx, arg.exampleValue); |
| 224 | + } |
| 225 | + index(indexName, functionName, body -> body.mapContents(testDoc)); |
| 226 | + |
| 227 | + // zero out the fields to be used as nulls |
| 228 | + for (idx = 1; idx <= fn.arguments.size(); idx++) { |
| 229 | + testDoc.put(nullArgPrefix + idx, null); |
| 230 | + } |
| 231 | + index(indexName, functionName, body -> body.mapContents(testDoc)); |
| 232 | + } |
| 233 | + |
| 234 | + private void checkScalarFunctionCoverage() throws Exception { |
| 235 | + ResultSet resultSet = esJdbc().createStatement().executeQuery("SHOW FUNCTIONS"); |
| 236 | + Set<String> functions = new LinkedHashSet<>(); |
| 237 | + while (resultSet.next()) { |
| 238 | + String name = resultSet.getString(1); |
| 239 | + String fnType = resultSet.getString(2); |
| 240 | + if ("SCALAR".equals(fnType)) { |
| 241 | + functions.add(name); |
| 242 | + } |
| 243 | + } |
| 244 | + for (Fn fn : FUNCTION_CALLS_TO_TEST) { |
| 245 | + functions.remove(fn.name); |
| 246 | + functions.removeAll(fn.aliases); |
| 247 | + } |
| 248 | + functions.removeAll(NON_TESTED_FUNCTIONS); |
| 249 | + |
| 250 | + assertThat("Some functions are not covered by this test", functions, empty()); |
| 251 | + } |
| 252 | + |
| 253 | + private static String asLiteralInQuery(Object argValue) { |
| 254 | + String argInQuery; |
| 255 | + if (argValue == null) { |
| 256 | + argInQuery = "NULL"; |
| 257 | + } else { |
| 258 | + argInQuery = String.valueOf(argValue); |
| 259 | + if (argValue instanceof String) { |
| 260 | + argInQuery = "'" + argInQuery + "'"; |
| 261 | + } |
| 262 | + } |
| 263 | + return argInQuery; |
| 264 | + } |
| 265 | + |
| 266 | + private static <T> void iterateAllPermutations(List<List<T>> possibleValuesPerItem, CheckedConsumer<List<T>, Exception> consumer) |
| 267 | + throws Exception { |
| 268 | + |
| 269 | + if (possibleValuesPerItem.isEmpty()) { |
| 270 | + consumer.accept(new ArrayList<>()); |
| 271 | + return; |
| 272 | + } |
| 273 | + iterateAllPermutations(possibleValuesPerItem.subList(1, possibleValuesPerItem.size()), onePermutationOfTail -> { |
| 274 | + for (T option : possibleValuesPerItem.get(0)) { |
| 275 | + ArrayList<T> onePermutation = new ArrayList<>(); |
| 276 | + onePermutation.add(option); |
| 277 | + onePermutation.addAll(onePermutationOfTail); |
| 278 | + consumer.accept(onePermutation); |
| 279 | + } |
| 280 | + }); |
| 281 | + } |
| 282 | + |
| 283 | +} |
0 commit comments