diff --git a/core/src/main/scala/app/softnetwork/elastic/client/ElasticConversion.scala b/core/src/main/scala/app/softnetwork/elastic/client/ElasticConversion.scala index 8f6941f0..42983019 100644 --- a/core/src/main/scala/app/softnetwork/elastic/client/ElasticConversion.scala +++ b/core/src/main/scala/app/softnetwork/elastic/client/ElasticConversion.scala @@ -746,10 +746,13 @@ trait ElasticConversion { /** SCHEMA-2 (D4, D6-D8) -- the hits of a statement read through its plan ([[HitReading]]): each * `_source` key the projection touches, each computed column's `fields` entry and each UNNEST * element field by its column's reader, before any re-read as a temporal; every other key as it - * always was. A date column the hit's `_ignored` names follows Elasticsearch's verdict, per - * value: a cell of one value is NULL, an array keeps the elements its format reads and answers - * the others NULL ([[HitReading.onIgnored]]). A several-element cell a scalar column refuses - * ([[MultiValued.Fail]]) fails the statement, naming the document. + * always was. A top-level column the hit's `_ignored` names follows Elasticsearch's verdict, per + * value, for every kind that takes `ignore_malformed` -- a date, a number, an `ip`, a + * `geo_point`, a `boolean` (SCHEMA-17 fix R-172) --: a cell of one value is NULL, an array keeps + * the elements the kind's own parse accepts and answers the others NULL + * ([[HitReading.onIgnored]], the one lookup); a keyword or a wildcard over `ignore_above` keeps + * its text. A several-element cell a scalar column refuses ([[MultiValued.Fail]]) fails the + * statement, naming the document. */ private def parseHitsByPlan( hits: List[JsonNode], diff --git a/core/src/main/scala/app/softnetwork/elastic/client/HitReading.scala b/core/src/main/scala/app/softnetwork/elastic/client/HitReading.scala index 58edf6ee..7f422ed6 100644 --- a/core/src/main/scala/app/softnetwork/elastic/client/HitReading.scala +++ b/core/src/main/scala/app/softnetwork/elastic/client/HitReading.scala @@ -55,10 +55,11 @@ private[client] object MultiValued { * - `scripted`: a computed column's hit `fields` entry, by output name (one-element array * unwrapped); * - `inner`: an UNNEST inner hit's element fields, by inner-hit name then field; - * - `ignoredDates`: the `_source` keys read as dates by their format, each with the reader of - * its cell where the hit's `_ignored` names it (D8): Elasticsearch's verdict is per VALUE, so - * a cell of one value is NULL and an array keeps the elements the format reads, the others - * NULL; + * - `ignoredReaders`: the top-level `_source` keys of a kind Elasticsearch may ignore a value of + * (`ignore_malformed`) -- a date read by its format, and every kind of + * [[HitReading.IgnoredKinds]] (SCHEMA-17 fix R-172) --, each with the reader of its cell where + * the hit's `_ignored` names it (D8): Elasticsearch's verdict is per VALUE, so a cell of one + * value is NULL and an array keeps the elements the kind's own parse accepts, the others NULL; * - `strict` / `keep`: the projection drops every undeclared key, but `keep` (D9); * - `star`: a bare `SELECT *` -- unmapped top-level keys dropped, a flat dotted key folded into * its mapped parent (A-3); @@ -75,7 +76,7 @@ private[client] final class HitReading( private[client] val source: java.util.HashMap[String, JsonNode => Any], private[client] val scripted: java.util.HashMap[String, JsonNode => Any], private[client] val inner: Map[String, java.util.HashMap[String, JsonNode => Any]], - private[client] val ignoredDates: java.util.HashMap[String, JsonNode => Any], + private[client] val ignoredReaders: java.util.HashMap[String, JsonNode => Any], val strict: Boolean, val keep: Set[String], private[client] val star: Boolean, @@ -87,8 +88,11 @@ private[client] final class HitReading( new java.util.HashMap[String, String]() ) { - /** Whether a hit's `_ignored` must be read (D8): the plan reads some `_source` key as a date. */ - private[client] val readsIgnored: Boolean = !ignoredDates.isEmpty + /** Whether a hit's `_ignored` must be read (D8): the plan reads some top-level `_source` key of a + * kind Elasticsearch may ignore a value of. One lookup per hit, which allocates nothing when the + * hit has no `_ignored` (`ElasticConversion.ignoredOf`). + */ + private[client] val readsIgnored: Boolean = !ignoredReaders.isEmpty /** Whether some selected path is collected whatever its parent's value is (SCHEMA-17 A-181, * [[HitReading.ListPath.always]]): decided once per statement, so a row of a statement with none @@ -101,10 +105,12 @@ private[client] final class HitReading( found } - /** The reader of `key`'s cell when the hit's `_ignored` names it (D8); `null` for a key that is - * not read as a date, which keeps its own reader (a keyword keeps its stored text). + /** The reader of `key`'s cell when the hit's `_ignored` names it (D8): THE lookup (#292) of every + * hit-reading path (search hits, scroll / PIT / search_after pages, `*`), built with the plan. + * `null` for a key of no such kind, which keeps its own reader: a keyword or a wildcard over + * `ignore_above` keeps its stored text, an object its own reader (a top-level key only). */ - private[client] def onIgnored(key: String): JsonNode => Any = ignoredDates.get(key) + private[client] def onIgnored(key: String): JsonNode => Any = ignoredReaders.get(key) /** Whether a (non-plan) top-level key is folded into its mapped parent under `*` (A-3). */ private[client] def foldsUnder(key: String): String = { @@ -181,6 +187,93 @@ private[client] object HitReading { nanosPaths(c.multiFields, s"$path.") }.toSet + /** SCHEMA-17 fix R-172 (A-201) -- the Elasticsearch kinds, beside the dates (read by their + * format), that take `ignore_malformed`: a value of them the hit's `_ignored` names was refused + * by Elasticsearch, which holds it in `_source` only. `boolean` takes it only on the majors that + * map the option (not 6.8 nor 7.x): elsewhere `_ignored` never names it. A refused + * `scaled_float` is named only from 8.6: before, its value keeps its reading as stored, as any + * value `_ignored` does not name. The strings (`keyword`, `wildcard`, ...) are not here: + * `_ignored` names them over `ignore_above`, a value Elasticsearch keeps. + */ + private[client] val IgnoredKinds: Set[String] = Set( + "byte", + "short", + "integer", + "long", + "unsigned_long", + "float", + "half_float", + "double", + "scaled_float", + "ip", + "geo_point", + "boolean" + ) + + /** SCHEMA-17 fix R-172 (A-201) -- each top-level column of `columns` of a kind of + * [[IgnoredKinds]], with that kind: its `Column.mappingType` (#292: a table typed from its + * mappings and one typed from `_field_caps` both carry the field's own type). Built once per + * plan, so a reader knows its kind when it is built, never per row. + */ + private[client] def ignoredKinds(columns: Seq[Column]): Map[String, String] = + columns.flatMap { c => + val kind = c.mappingType + if (IgnoredKinds.contains(kind)) Some(c.name -> kind) else None + }.toMap + + /** The smallest magnitude a `half_float` refuses: Lucene's `HalfFloatPoint` rounds it (ties to + * even) to infinity, which Elasticsearch refuses (the largest half float is 65504). + */ + private val HalfFloatLimit: Float = 65520f + + /** SCHEMA-17 fix R-172 (A-201) -- whether `text` may be an address an `ip` field indexes: an IPv4 + * literal (four decimal parts of at most three digits, each at most 255), or a text holding a + * `:` made only of hex digits, `:` and `.` -- an IPv6 literal, an embedded IPv4 one included --, + * optionally followed by `%` and a zone. Written by hand, never `InetAddress.getByName`, which + * resolves host names; lenient where Elasticsearch's own parse is stricter (a leading zero, an + * IPv6 group count), so an address Elasticsearch indexed is never NULL. + */ + private[client] def ipLiteral(text: String): Boolean = + if (text.indexOf(':') < 0) ipv4(text) + else { + val zone = text.indexOf('%') + val end = if (zone < 0) text.length else zone + if (end == 0 || zone == text.length - 1) false + else { + var ok = true + var i = 0 + while (ok && i < end) { + val c = text.charAt(i) + ok = c == ':' || c == '.' || Character.digit(c, 16) >= 0 + i += 1 + } + ok + } + } + + private def ipv4(text: String): Boolean = { + var parts = 0 + var digits = 0 + var value = 0 + var ok = true + var i = 0 + while (ok && i < text.length) { + val c = text.charAt(i) + if (c == '.') { + ok = digits > 0 + parts += 1 + digits = 0 + value = 0 + } else if (c >= '0' && c <= '9') { + digits += 1 + value = value * 10 + (c - '0') + ok = digits <= 3 && value <= 255 + } else ok = false + i += 1 + } + ok && digits > 0 && parts == 3 + } + /** SCHEMA-6 (A-26) -- a selected dotted column under a parent the plan reads WHOLE (`SELECT obj, * obj.a`, `SELECT *, obj.a`): where the parent's `_source` value is a list of objects, the row * key `key` holds the values the path `segments` collects there ([[Readers.collected]]), read by @@ -491,7 +584,8 @@ private[client] object HitReading { remedyOf(single.schema), single.schema.fold(Set.empty[String])(t => nanosPaths(t.columns)), fieldCapsDates(single), - storedLeaves(single.schema) + storedLeaves(single.schema), + single.schema.fold(Map.empty[String, String])(t => ignoredKinds(t.columns)) ) val fields = single.select.fieldsWithComputedAliases val star = fields.exists(isStar) @@ -499,7 +593,7 @@ private[client] object HitReading { val indexed = single.indexedColumns.toSet val source = new java.util.HashMap[String, JsonNode => Any]() val scripted = new java.util.HashMap[String, JsonNode => Any]() - val ignoredDates = new java.util.HashMap[String, JsonNode => Any]() + val ignoredReaders = new java.util.HashMap[String, JsonNode => Any]() // the dotted paths the projection selects, relative to their parent (D4) val selectedPaths: Map[String, Seq[String]] = fields .filterNot(f => isStar(f) || f.identifier.nested || f.identifier.functions.nonEmpty) @@ -519,7 +613,7 @@ private[client] object HitReading { def put(key: String, t: SetOperationType, keepKeys: Set[String]): Unit = { val (reader, onIgnored) = readers.column(key, t, keepKeys) source.put(key, reader) - onIgnored.foreach(ignoredDates.put(key, _)) + onIgnored.foreach(ignoredReaders.put(key, _)) } single.schema.foreach { table => if (star) @@ -689,7 +783,7 @@ private[client] object HitReading { source, scripted, inner, - ignoredDates, + ignoredReaders, strict, keep, star && schema.isDefined && fields.forall(isStar), @@ -702,6 +796,9 @@ private[client] object HitReading { /** The readers of one statement (D5), built once: `JsonNode => Any`, a node never `null` (the * caller hands `null` / a JSON `null` to none of them but the scalar wrapper). + * + * `kinds`: SCHEMA-17 fix R-172 (A-201) -- each top-level column of a kind of [[IgnoredKinds]], + * with that kind ([[ignoredKinds]]): its cell gets a reader for the hit's `_ignored` (D8). */ private[client] final class Readers( aliases: ListMap[String, String], @@ -711,7 +808,8 @@ private[client] object HitReading { remedy: String => Option[String] = _ => None, nanos: Set[String] = Set.empty, isoOnlyDates: Boolean = false, - stored: Set[String] = Set.empty + stored: Set[String] = Set.empty, + kinds: Map[String, String] = Map.empty ) { /** The failure of a several-element cell of `name` (SCHEMA-6 D6). */ @@ -775,11 +873,14 @@ private[client] object HitReading { case _ => true } - /** A `_source` column of type `t`, and -- for a date read by its format -- the reader of its - * cell when the hit's `_ignored` names it (D8): Elasticsearch refused some value of it, and - * its verdict is per VALUE. A cell of one value is NULL (the value refused); an array keeps - * each element the format reads -- a value Elasticsearch indexed -- and answers the others - * NULL. + /** A `_source` column of type `t`, and -- for a date read by its format, and a top-level column + * of a kind of [[IgnoredKinds]] (SCHEMA-17 fix R-172, A-201) -- the reader of its cell when + * the hit's `_ignored` names it (D8): Elasticsearch refused some value of it, and its verdict + * is per VALUE. A cell of one value is NULL (the value refused); an array keeps each element + * the kind's own Elasticsearch parse accepts -- a value Elasticsearch indexed, read by the + * column's reader -- and answers the others NULL, under the scalar column's rule of several + * values. A column declared `ARRAY` reads its elements the same way (A-202), a scalar cell + * a list of its one value, NULL. */ def column( name: String, @@ -809,7 +910,8 @@ private[client] object HitReading { ): (JsonNode => Any, Option[JsonNode => Any]) = t.sqlType match { case SQLTypes.Array(_) => - (list(name, t.element.getOrElse(SetOperationType(SQLTypes.Any))), None) + val element = t.element.getOrElse(SetOperationType(SQLTypes.Any)) + (list(name, element), ignoredList(name, element)) // SCHEMA-17 (A-168): a list of objects in a column declared STRUCT takes the default rule // (`multiValued`, [[multiValuedFor]]) -- the in-place ALTER that declares an `object` field // `ARRAY` ships in the same release (A-166), so the failure names a remedy that @@ -817,8 +919,9 @@ private[client] object HitReading { // list of one. An object is no leaf: the statement's rule, whatever `mode` (R-150, A-183) case SQLTypes.Struct if t.fields.nonEmpty => (scalar(name, struct(name, t, keepKeys), multiValued), None) - case SQLTypes.GeoPoint => (geo(name, mode), None) - case _ if !typed(t) => (asRead, None) + case SQLTypes.GeoPoint => + (geo(name, mode), if (pointsOf(name)) Some(ignoredGeo(name, mode)) else None) + case _ if !typed(t) => (asRead, None) case scalarType => val (one, ignoredOne) = scalarOne(name, scalarType, t.format) ( @@ -1110,13 +1213,231 @@ private[client] object HitReading { private def point(name: String, node: JsonNode): Any = SetOperationValues.geoPoint(HitReading.plain(node), name) - /** ONE non-null, non-array value of a scalar type, and -- for a date read by its format -- the - * same read answering NULL where the format does not read the value (D8). + /** SCHEMA-17 fix R-172 (A-201) -- whether `name` is a top-level `geo_point` field. */ + private def pointsOf(name: String): Boolean = kinds.get(name).contains("geo_point") + + /** SCHEMA-17 fix R-172 (A-201) -- ONE element of a `geo_point` cell the hit's `_ignored` names: + * the point Elasticsearch indexed, or NULL for a value that is no point, which it refused. + */ + private def ignoredPoint(name: String): JsonNode => Any = + node => + try point(name, node) + catch { case _: IllegalArgumentException => null } + + /** SCHEMA-17 fix R-172 (A-201) -- a `GEO_POINT` cell the hit's `_ignored` names (D8): one value + * -- `[lon, lat]` is one point -- is NULL, the value Elasticsearch refused; several are each a + * point or NULL ([[ignoredPoint]]), per `mode`. + */ + private def ignoredGeo(name: String, mode: MultiValued): JsonNode => Any = { + val one = ignoredPoint(name) + node => + if (node == null || !node.isArray || coordinates(node)) null + else { + val size = node.size() + if (size == 0) null + else if (size == 1) element(one)(node.get(0)) + else + mode match { + case MultiValued.AsRead => + val values = ListBuffer.empty[Any] + val it = node.elements() + while (it.hasNext) values += element(one)(it.next()) + values.toList + case MultiValued.Fail => throw several(name) + } + } + } + + /** SCHEMA-17 fix R-172 (A-202) -- the cell of a column declared `ARRAY` the hit's `_ignored` + * names (D8), for an element read by its format (a date) or of a kind of [[IgnoredKinds]]: a + * `List` of its elements, each the kind's own Elasticsearch parse accepts read by the column's + * element reader, the others NULL; a scalar cell -- one value, the one Elasticsearch refused + * -- a list of one NULL. `None` for any other element: a string keeps its text, a `STRUCT` or + * a nested list its own reader. + */ + private def ignoredList( + name: String, + elementType: SetOperationType + ): Option[JsonNode => Any] = { + val points = elementType.sqlType == SQLTypes.GeoPoint + val read: Option[JsonNode => Any] = elementType.sqlType match { + case SQLTypes.GeoPoint => if (pointsOf(name)) Some(ignoredPoint(name)) else None + case SQLTypes.Struct | SQLTypes.Array(_) => None + case _ if !typed(elementType) => None + case scalarType => scalarOne(name, scalarType, elementType.format)._2 + } + read.map { one => (node: JsonNode) => + if (node == null || node.isNull) null + // SCHEMA-6: `[lon, lat]` in an `ARRAY` is ONE point (R-34) + else if (node.isArray && !(points && coordinates(node))) { + val values = ListBuffer.empty[Any] + val it = node.elements() + while (it.hasNext) values += element(one)(it.next()) + values.toList + } else List(null) + } + } + + /** ONE non-null, non-array value of a scalar type, and -- for a date read by its format, and a + * top-level column of a kind of [[IgnoredKinds]] (SCHEMA-17 fix R-172, A-201) -- the same read + * answering NULL where the kind's own Elasticsearch parse refuses the value (D8): the format + * for a date, [[acceptance]] for the others. */ def scalarOne( name: String, sqlType: app.softnetwork.elastic.sql.`type`.SQLType, format: Option[String] + ): (JsonNode => Any, Option[JsonNode => Any]) = { + val read = scalarRead(name, sqlType, format) + if (read._2.isDefined) read + else + kinds.get(name) match { + case Some(kind) => + val one = read._1 + val accepts = acceptance(name, kind) + (one, Some((node: JsonNode) => if (accepts(node)) one(node) else null)) + case None => read + } + } + + /** SCHEMA-17 fix R-172 (A-201) -- whether Elasticsearch's own parse of the field kind `kind` + * (`ignore_malformed` on, `coerce` on) accepts a node, ONE element of a cell the hit's + * `_ignored` names: an element it accepts is a value it indexed, kept and read by the column's + * reader; one it refuses is NULL. Chosen once per reader, never per row. Where core is not + * sure of the verdict (an object or a nested list, an `ip` spelling beyond the plain literals) + * the element is KEPT: never NULL a value Elasticsearch indexed. An empty text is no value + * (Elasticsearch indexes nothing for it, and names nothing): kept, read as the column reads + * it. + * + * - `byte` / `short` / `integer` / `long`: [[WholeRange]] reads it, as Elasticsearch does; + * - `unsigned_long`: an integral number within `[0, 2^64 - 1]`; a whole floating number `>= + * 0`, whatever its size (Elasticsearch saturates one `>= 2^63` to `2^63 - 1` and indexes + * it); a text (not trimmed) holding a whole number within `[0, 2^64 - 1]` + * ([[unsignedLong]]); + * - `float` / `half_float` / `double` / `scaled_float`: a number, or a text `parseFloat` / + * `parseDouble` reads, that is finite in the kind (`half_float`: below 65520 in magnitude, + * which Lucene's half-float rounding, ties to even, keeps finite); + * - `boolean`: a JSON boolean, or the text `true`, `false` or empty; + * - `ip`: a text that is an IPv4 literal, or an IPv6 one ([[ipLiteral]]): never resolved; + * - `geo_point`: a point core reads. + */ + private def acceptance(name: String, kind: String): JsonNode => Boolean = { + val accepts: JsonNode => Boolean = kind match { + case "byte" => node => wholeAccepted(WholeRange.ForTinyInt.read(node)) + case "short" => node => wholeAccepted(WholeRange.ForSmallInt.read(node)) + case "integer" => node => wholeAccepted(WholeRange.ForInt.read(node)) + case "long" => node => wholeAccepted(WholeRange.ForBigInt.read(node)) + case "unsigned_long" => node => unsignedLong(node) + case "float" => node => finiteFloat(node, Float.PositiveInfinity) + case "half_float" => node => finiteFloat(node, HalfFloatLimit) + case "double" | "scaled_float" => + node => + if (node.isNumber) java.lang.Double.isFinite(node.doubleValue()) + else if (node.isTextual) { + val text = node.asText() + text.isEmpty || { + try java.lang.Double.isFinite(java.lang.Double.parseDouble(text)) + catch { case _: NumberFormatException => false } + } + } else !node.isBoolean + case "boolean" => + node => + if (node.isBoolean) true + else if (node.isTextual) { + val text = node.asText() + text.isEmpty || text == "true" || text == "false" + } else !node.isNumber + case "ip" => + node => + if (node.isTextual) ipLiteral(node.asText()) + else !(node.isNumber || node.isBoolean) + case "geo_point" => + node => + try { + point(name, node) + true + } catch { case _: IllegalArgumentException => false } + case _ => _ => true + } + if (kind == "geo_point") accepts + else node => node.isContainerNode || accepts(node) + } + + private def wholeAccepted(read: Any): Boolean = + read match { + case null | _: java.lang.Integer | _: java.lang.Long => true + case _ => false + } + + /** `float` (`limit` the float infinity) and `half_float` (`limit` 65520): Elasticsearch's + * `parser.floatValue(coerce)` -- `Float.parseFloat` on a text, which trims --, then finite. + */ + private def finiteFloat(node: JsonNode, limit: Float): Boolean = + if (node.isNumber) Math.abs(node.floatValue()) < limit + else if (node.isTextual) { + val text = node.asText() + text.isEmpty || { + try Math.abs(java.lang.Float.parseFloat(text)) < limit + catch { case _: NumberFormatException => false } + } + } else !node.isBoolean + + /** `unsigned_long`: Elasticsearch's `parseUnsignedLong` (7.17 / 8.18), which refuses a decimal + * part ("has a decimal part") and a negative value, never truncating one: + * + * - an integral number within `[0, 2^64 - 1]`; + * - a floating number -- a double, a float or a big decimal: Elasticsearch's parser reads + * every JSON float token as a `Double` -- equal to its floor (`Double.compare`) and not + * negative, whatever its size: Elasticsearch saturates a whole floating number `>= 2^63` + * (an infinity included) to `2^63 - 1` and indexes it; + * - a text (not trimmed, read by `parseUnsignedLong`, else `new BigDecimal`) that is exact + * ([[unsignedDecimal]]). No value is materialised beyond the digits it holds: a text of a + * large exponent is judged by its digit count. + */ + private def unsignedLong(node: JsonNode): Boolean = + if (node.isIntegralNumber) { + val b = node.bigIntegerValue() + b.signum() >= 0 && b.bitLength() <= 64 + } else if (node.isNumber) { + // Elasticsearch: `Double.compare(v, Math.floor(v)) != 0` refuses, then `longValue() < 0` + val d = node.doubleValue() + java.lang.Double.compare(d, Math.floor(d)) == 0 && !(d < 0.0d) + } else if (node.isTextual) { + val text = node.asText() + text.isEmpty || { + val unsigned = + try { + java.lang.Long.parseUnsignedLong(text) + true + } catch { case _: NumberFormatException => false } + unsigned || { + val d = + try new java.math.BigDecimal(text) + catch { case _: NumberFormatException => null } + (d ne null) && unsignedDecimal(d) + } + } + } else !node.isBoolean + + /** A big decimal an `unsigned_long` takes: zero, or a positive whole number -- no non-zero + * digit after the point (`toBigIntegerExact`) -- below 2^64. The digits before the point are + * counted in Long arithmetic, off the scale (trailing zeros change none of them), before any + * value is built. + */ + private def unsignedDecimal(d: java.math.BigDecimal): Boolean = + d.signum() == 0 || { + val integerDigits = d.precision().toLong - d.scale() + d.signum() > 0 && integerDigits > 0 && integerDigits <= 20 && { + val whole = if (d.scale() <= 0) d else d.stripTrailingZeros() + whole.scale() <= 0 && whole.toBigInteger.bitLength() <= 64 + } + } + + /** The scalar read of [[scalarOne]], before any D8 reader of a kind of [[IgnoredKinds]]. */ + private def scalarRead( + name: String, + sqlType: app.softnetwork.elastic.sql.`type`.SQLType, + format: Option[String] ): (JsonNode => Any, Option[JsonNode => Any]) = sqlType match { case SQLTypes.TinyInt | SQLTypes.SmallInt | SQLTypes.Int => @@ -1325,7 +1646,8 @@ private[client] object HitReading { * * A value Elasticsearch refuses is no value of the type -- it holds it in `_source` only * (`ignore_malformed`) -- so `read` answers [[OutOfType]] and the column keeps it as stored - * (`Unreadable.KeepAsStored`): narrowing it would wrap it. So is a `long` text where the majors + * (`Unreadable.KeepAsStored`): narrowing it would wrap it; where the hit's `_ignored` names the + * field, the value is NULL (D8, SCHEMA-17 fix R-172). So is a `long` text where the majors * disagree: 7.17 and 8.18 refuse a scale below -19 and read 0 above 19, where 6.8 reads the * truncated value -- except a non-zero value with a scale of 2^29 + 8 (536,870,920) or more, * which 6.8 refuses: its `toBigInteger` divides by `BigInteger.TEN.pow(scale)`, which reports an diff --git a/core/src/test/scala/app/softnetwork/elastic/client/HitReadingIgnoredValuesSpec.scala b/core/src/test/scala/app/softnetwork/elastic/client/HitReadingIgnoredValuesSpec.scala new file mode 100644 index 00000000..cbe6450c --- /dev/null +++ b/core/src/test/scala/app/softnetwork/elastic/client/HitReadingIgnoredValuesSpec.scala @@ -0,0 +1,430 @@ +/* + * Copyright 2025 SOFTNETWORK + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package app.softnetwork.elastic.client + +import app.softnetwork.elastic.client.SetOperationValues.DateReading +import app.softnetwork.elastic.schema.{FieldCaps, Index} +import app.softnetwork.elastic.sql.`type`.{SQLTypes, ValueCoercion} +import app.softnetwork.elastic.sql.parser.Parser +import app.softnetwork.elastic.sql.query.SingleSearch +import app.softnetwork.elastic.sql.schema.Schema +import app.softnetwork.elastic.sql.serialization.JacksonConfig +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +import java.time.{ZoneOffset, ZonedDateTime} +import scala.collection.immutable.ListMap + +/** SCHEMA-17 fix R-172 -- a value Elasticsearch ignored as malformed (the hit's `_ignored` names + * its top-level field) reads as NULL for every kind that takes `ignore_malformed`, by the rule + * dates already follow (SCHEMA-2 D8): one value is NULL; an array keeps each element the kind's + * own Elasticsearch parse accepts, read by the column's reader, and answers the others NULL. A + * keyword or a wildcard over `ignore_above`, which `_ignored` names too, keeps its text. A value + * `_ignored` does not name keeps its reading (D6). + */ +class HitReadingIgnoredValuesSpec extends AnyFlatSpec with Matchers { + + private val mapping: String = + """{"r172_t": {"aliases": {}, "mappings": { + | "_meta": {"columns": { + | "la": {"data_type": "ARRAY"}, "ia": {"data_type": "ARRAY"}, + | "ra": {"data_type": "ARRAY"}, "hfa": {"data_type": "ARRAY"}, + | "ua": {"data_type": "ARRAY"}, "ipa": {"data_type": "ARRAY"}, + | "ga": {"data_type": "ARRAY"}, "da": {"data_type": "ARRAY"}, + | "w": {"data_type": "INT"}}}, + | "properties": { + | "id": {"type": "keyword"}, "k": {"type": "keyword"}, "ok": {"type": "long"}, + | "tb": {"type": "byte", "ignore_malformed": true}, + | "sh": {"type": "short", "ignore_malformed": true}, + | "i": {"type": "integer", "ignore_malformed": true}, + | "l": {"type": "long", "ignore_malformed": true}, + | "u": {"type": "unsigned_long", "ignore_malformed": true}, + | "r": {"type": "float", "ignore_malformed": true}, + | "hf": {"type": "half_float", "ignore_malformed": true}, + | "x": {"type": "double", "ignore_malformed": true}, + | "sf": {"type": "scaled_float", "scaling_factor": 100, "ignore_malformed": true}, + | "ip": {"type": "ip", "ignore_malformed": true}, + | "g": {"type": "geo_point", "ignore_malformed": true}, + | "b": {"type": "boolean", "ignore_malformed": true}, + | "dm": {"type": "date", "ignore_malformed": true}, + | "kw": {"type": "keyword", "ignore_above": 3}, + | "wc": {"type": "wildcard", "ignore_above": 3}, + | "la": {"type": "long", "ignore_malformed": true}, + | "ia": {"type": "integer", "ignore_malformed": true}, + | "ra": {"type": "float", "ignore_malformed": true}, + | "hfa": {"type": "half_float", "ignore_malformed": true}, + | "ua": {"type": "unsigned_long", "ignore_malformed": true}, + | "ipa": {"type": "ip", "ignore_malformed": true}, + | "ga": {"type": "geo_point", "ignore_malformed": true}, + | "da": {"type": "date", "ignore_malformed": true}, + | "obj": {"properties": {"n": {"type": "long", "ignore_malformed": true}, + | "i": {"type": "integer", "ignore_malformed": true}}}, + | "w": {"type": "long"} + | }}, "settings": {"index": {"number_of_shards": "1"}}}}""".stripMargin + + private val schema: Schema = Index("r172_t", mapping).schema + + private def statement(sql: String, table: Schema = schema): SingleSearch = Parser(sql) match { + case Right(s: SingleSearch) => s.update(Some(table)) + case other => fail(s"[$sql] expected a SingleSearch, got $other") + } + + private def outputs(single: SingleSearch): Seq[String] = { + val fields = single.select.fieldsWithComputedAliases + if (fields.size == 1 && fields.head.identifier.identifierName == "*") Seq.empty + else fields.map(_.outputName) + } + + private def contextOf( + single: SingleSearch, + version: String, + multiValued: MultiValued + ): ConversionContext = { + val elements = ElementConversions.of(single, Some(version)) + SchemaColumns( + HitReading.of(single, DateReading(Some(version)), multiValued, elements.keySet), + single.doubleKeyLevels + )(elements) + } + + /** The rows `sql` answers for `hits` on both parse routes a client's page takes: the body text (a + * one-shot search) and the tree (scroll, PIT and search_after pages). + */ + private def onRoutes( + sql: String, + hits: String, + version: String = "8.18.3", + multiValued: MultiValued = HitReading.Default, + table: Schema = schema + ): Seq[(String, Seq[ListMap[String, Any]])] = { + val single = statement(sql, table) + implicit val context: ConversionContext = contextOf(single, version, multiValued) + val response = s"""{"hits": {"total": {"value": 1, "relation": "eq"}, "hits": [$hits]}}""" + Seq( + "body" -> ElasticConversion + .parseResponse(response, single.fieldAliases, ListMap.empty, outputs(single)) + .get, + "tree" -> ElasticConversion + .parseSingleSearchResponse( + JacksonConfig.objectMapper.readTree(response), + single.fieldAliases, + ListMap.empty, + outputs(single) + ) + .get + ) + } + + /** A document holding `value` in `field`, beside a keyword and a number Elasticsearch indexed, + * its hit's `_ignored` naming `ignored`. + */ + private def hit(field: String, value: String, ignored: Seq[String]): String = { + val names = + if (ignored.isEmpty) "" + else ignored.map(n => s""""$n"""").mkString(""", "_ignored": [""", ", ", "]") + s"""{"_id": "d1", "_index": "r172_t", + | "_source": {"id": "d1", "k": "keep", "ok": 5, "$field": $value}$names}""".stripMargin + } + + private def utc(y: Int, mo: Int, d: Int, h: Int = 0, mi: Int = 0): ZonedDateTime = + ZonedDateTime.of(y, mo, d, h, mi, 0, 0, ZoneOffset.UTC) + + private val point: ListMap[String, Any] = ListMap("lat" -> 1.5, "lon" -> 2.5) + + /** One value of each kind Elasticsearch refuses -- a text it cannot parse, a number out of the + * kind's range or not finite -- which it holds in `_source` only and names in `_ignored`. + */ + private val refused: Seq[(String, String)] = Seq( + "tb" -> "\"x\"", + "tb" -> "200", + "sh" -> "\"x\"", + "sh" -> "40000", + "i" -> "\"x\"", + "i" -> "3000000000", + "l" -> "\"x\"", + "l" -> "100000000000000000000", + "u" -> "\"x\"", + "u" -> "-1", + "r" -> "\"x\"", + "r" -> "1e39", + "hf" -> "\"x\"", + "hf" -> "65520", + "x" -> "\"x\"", + "x" -> "\"1e309\"", + "sf" -> "\"x\"", + "sf" -> "\"1e309\"", + "ip" -> "\"x\"", + "g" -> "\"not a point\"", + "b" -> "\"x\"", + // the date rule, unchanged + "dm" -> "\"not-a-date\"" + ) + + "A value Elasticsearch ignored as malformed" should + "read NULL in its column for every kind, on every venue and parse route (AC2)" in { + refused.foreach { case (field, value) => + Seq( + s"SELECT id, k, ok, $field FROM r172_t", + "SELECT * FROM r172_t", + s"SELECT id, k, ok, $field FROM r172_t WHERE ok > 0" + ).foreach { sql => + onRoutes(sql, hit(field, value, Seq(field))).foreach { case (route, rows) => + withClue(s"[$route] $sql over $field = $value: ") { + val row = rows.head + row.getOrElse(field, null) shouldBe (null: Any) + row.get("id") shouldBe Some("d1") + row.get("k") shouldBe Some("keep") + row.get("ok") shouldBe Some(5L) + } + } + } + } + } + + it should "keep its reading where the hit's _ignored does not name it (D6)" in { + refused.filterNot(_._1 == "dm").foreach { case (field, value) => + onRoutes(s"SELECT id, $field FROM r172_t", hit(field, value, Nil)).foreach { + case (route, rows) => + withClue(s"[$route] $field = $value: ") { + Option(rows.head.getOrElse(field, null)) shouldBe defined + } + } + } + // ...and a cell `_ignored` names leaves the document's other cells to their own readers + onRoutes("SELECT id, i, ok FROM r172_t", hit("i", "\"x\"", Seq("i"))).foreach { + case (route, rows) => withClue(s"[$route] ")(rows.head.get("ok") shouldBe Some(5L)) + } + } + + "An ARRAY cell Elasticsearch ignored some value of" should + "keep each element the kind's own parse accepts and answer the others NULL (AC2, A-201, A-202)" in { + val cases: Seq[(String, String, Seq[Any])] = Seq( + ("la", """[1, "x", 3]""", Seq(1L, null, 3L)), + ("ia", """[1, 3000000000, "y"]""", Seq(1, null, null)), + ("ra", """[1.5, 1e39, "x"]""", Seq(1.5f, null, null)), + ("hfa", """[65519, 65520, "x"]""", Seq(65519.0f, null, null)), + ( + "ua", + """[-1, 18446744073709551615, 5]""", + Seq(null, new java.math.BigInteger("18446744073709551615"), 5L) + ), + ( + "ipa", + """["10.0.0.1", "x", "::1", "2001:db8::ff00:42:8329"]""", + Seq("10.0.0.1", null, "::1", "2001:db8::ff00:42:8329") + ), + ("ga", """[{"lat": 1.5, "lon": 2.5}, "not a point"]""", Seq(point, null)), + ("da", """["2024-01-31T10:30:00Z", "bad"]""", Seq(utc(2024, 1, 31, 10, 30), null)) + ) + cases.foreach { case (field, values, expected) => + Seq(s"SELECT id, $field FROM r172_t", "SELECT * FROM r172_t").foreach { sql => + onRoutes(sql, hit(field, values, Seq(field))).foreach { case (route, rows) => + withClue(s"[$route] $sql over $field = $values: ") { + rows.head.getOrElse(field, null) shouldBe expected + } + } + } + } + } + + it should "read a scalar column's several values the same way where the statement keeps them" in { + onRoutes( + "SELECT id, i FROM r172_t", + hit("i", """[1, 3000000000, "y"]""", Seq("i")), + multiValued = MultiValued.AsRead + ).foreach { case (route, rows) => + withClue(s"[$route] ")(rows.head.getOrElse("i", null) shouldBe List(1, null, null)) + } + // one element: the value Elasticsearch ignored, NULL + onRoutes("SELECT id, i FROM r172_t", hit("i", """["x"]""", Seq("i"))).foreach { + case (route, rows) => + withClue(s"[$route] ")(rows.head.getOrElse("i", null) shouldBe (null: Any)) + } + // several values in a scalar column still fail under the default rule, naming the ALTER (D6) + val failure = intercept[Exception] { + onRoutes("SELECT id, i FROM r172_t", hit("i", """[1, "x"]""", Seq("i"))) + } + val message = Option(failure.getCause).fold(failure.getMessage)(_.getMessage) + message should include("ALTER TABLE r172_t ALTER COLUMN i SET DATA TYPE ARRAY") + } + + it should "judge each element by its kind's own Elasticsearch parse at the edges (A-201)" in { + val cases: Seq[(String, String, Seq[Any])] = Seq( + ("tb", """[127, 128, -129, "5", ""]""", Seq(127, null, null, 5, null)), + ("sh", """[32767, 32768]""", Seq(32767, null)), + ("i", """[2147483647, 2147483648, "7.9"]""", Seq(2147483647, null, 7)), + ("l", """[9223372036854775807, 9223372036854775808, "1.9"]""", Seq(Long.MaxValue, null, 1L)), + ( + "u", + """[0, -1, 18446744073709551615, 18446744073709551616]""", + Seq(0L, null, new java.math.BigInteger("18446744073709551615"), null) + ), + // a whole number only: Elasticsearch refuses a decimal part, and trims no text + ( + "u", + """[5.5, "5.5", 5.0, "5.0", -0.5, " 5 ", "0.0"]""", + Seq(null, null, 5L, 5L, null, null, 0L) + ), + // a whole floating number >= 0 is indexed whatever its size (Elasticsearch saturates one + // >= 2^63 to 2^63 - 1): kept, read as the BIGINT column reads it -- as stored beyond `long` + ("u", """[1e20, "x"]""", Seq(1e20, null)), + ( + "u", + """[1e20, 18446744073709551616.0, -1.0, -0.0]""", + Seq(1e20, 18446744073709551616.0, null, 0L) + ), + ("r", """[3.4028235e38, 3.5e38, " 2.5 "]""", Seq(Float.MaxValue, null, 2.5f)), + ("hf", """[65504, 65519.99, 65520, -65520]""", Seq(65504.0f, 65519.99f, null, null)), + ("x", """[2.5, "NaN", "1e309"]""", Seq(2.5, null, null)), + ("sf", """[1.25, "Infinity"]""", Seq(1.25, null)), + ("b", """[true, "false", "x", 1]""", Seq(true, false, null, null)), + ( + "ip", + """["10.0.0.1", "256.0.0.1", 123, "::ffff:10.0.0.1"]""", + Seq("10.0.0.1", null, null, "::ffff:10.0.0.1") + ), + ("g", """[[2.5, 1.5], "1.5,2.5", "not a point"]""", Seq(point, point, null)) + ) + cases.foreach { case (field, values, expected) => + onRoutes( + s"SELECT id, $field FROM r172_t", + hit(field, values, Seq(field)), + multiValued = MultiValued.AsRead + ).foreach { case (route, rows) => + withClue(s"[$route] $field = $values: ")(rows.head.getOrElse(field, null) shouldBe expected) + } + } + } + + "A keyword or a wildcard over ignore_above" should + "keep its text, though the hit's _ignored names it (AC3)" in { + Seq("kw", "wc").foreach { field => + Seq(s"SELECT id, $field FROM r172_t", "SELECT * FROM r172_t").foreach { sql => + onRoutes(sql, hit(field, "\"abcdefgh\"", Seq(field))).foreach { case (route, rows) => + withClue(s"[$route] $sql: ")(rows.head.getOrElse(field, null) shouldBe "abcdefgh") + } + } + } + } + + "An integer of 3000000000 and a float of 1e39 Elasticsearch ignored" should + "read NULL, never a wrapped number through the coercions (AC4)" in { + onRoutes("SELECT id, i FROM r172_t", hit("i", "3000000000", Seq("i"))).foreach { + case (route, rows) => + val i = rows.head.getOrElse("i", null) + withClue(s"[$route] i = $i: ") { + ValueCoercion.coerceToInt(i) shouldBe (null: java.lang.Integer) + i shouldBe (null: Any) + } + } + onRoutes("SELECT id, r FROM r172_t", hit("r", "1e39", Seq("r"))).foreach { case (route, rows) => + val r = rows.head.getOrElse("r", null) + withClue(s"[$route] r = $r: ") { + ValueCoercion.coerceToFloat(r) shouldBe (null: java.lang.Float) + r shouldBe (null: Any) + } + } + } + + "A number outside its column's type that Elasticsearch indexed" should + "read as stored and fail through the coercions naming it (AC7, R-177)" in { + // `w` declared INT over a `long` field; `obj.i` an object's sub-field, which D8 does not + // reach (A-202) though `_ignored` names it + val w = schema.columns.find(_.name == "w").getOrElse(fail("no column w")) + (w.dataType, w.mappingType) shouldBe (SQLTypes.Int, "long") + Seq( + ("SELECT id, w FROM r172_t", hit("w", "3000000000", Nil), "w"), + ( + "SELECT id, obj.i FROM r172_t", + hit("obj", """{"i": 3000000000}""", Seq("obj.i")), + "obj.i" + ) + ).foreach { case (sql, document, key) => + onRoutes(sql, document).foreach { case (route, rows) => + val v = rows.head.getOrElse(key, null) + withClue(s"[$route] $sql: $v (${Option(v).map(_.getClass.getName).orNull}): ") { + v shouldBe java.lang.Long.valueOf(3000000000L) + val error = the[java.sql.SQLException] thrownBy ValueCoercion.coerceToInt(v) + error.getMessage shouldBe "Value 3000000000 is out of range for INT" + } + } + } + } + + "Whether the hit's _ignored decides a cell" should + "be ONE lookup, built with the plan, for every accepted kind (AC5, #292)" in { + val dates = DateReading(Some("8.18.3")) + val accepted = Seq("tb", "sh", "i", "l", "u", "r", "hf", "x", "sf", "ip", "g", "b", "dm") ++ + Seq("la", "ia", "ra", "hfa", "ua", "ipa", "ga", "da") + val star = HitReading.of(statement("SELECT * FROM r172_t"), dates) + star.readsIgnored shouldBe true + accepted.foreach(k => withClue(s"* $k: ")(star.onIgnored(k) should not be null)) + // a string keeps its own reader (AC3), an object its own (A-202: a top-level field) + Seq("id", "k", "kw", "wc", "obj").foreach(k => + withClue(s"* $k: ")(star.onIgnored(k) shouldBe null) + ) + // a named column is decided by the same lookup + accepted.foreach { k => + val named = HitReading.of(statement(s"SELECT id, $k FROM r172_t"), dates) + withClue(s"named $k: ") { + named.readsIgnored shouldBe true + named.onIgnored(k) should not be null + } + } + // a dotted column keeps today's reading (A-202) + HitReading + .of(statement("SELECT id, obj.n FROM r172_t"), dates) + .onIgnored("obj.n") shouldBe null + } + + /** `r172_c` as a read-only user is typed: from `_field_caps`, as the client types it. */ + private val caps: Schema = { + val answer = FieldCaps.read( + "r172_c", + JacksonConfig.objectMapper.readTree( + """{"indices": ["r172_c"], "fields": { + | "id": {"keyword": {"type": "keyword", "metadata_field": false}}, + | "i": {"integer": {"type": "integer", "metadata_field": false}}, + | "ip": {"ip": {"type": "ip", "metadata_field": false}}, + | "kw": {"keyword": {"type": "keyword", "metadata_field": false}} + |}}""".stripMargin + ) + ) + FieldCaps.table(answer, Index("r172_c", answer.members.head._2).schema) + } + + "A table typed from _field_caps" should "read a value Elasticsearch ignored NULL by its field's kind" in { + Seq("7.17.29", "8.18.3").foreach { version => + onRoutes( + "SELECT id, i, ip, kw FROM r172_c", + """{"_id": "d1", "_index": "r172_c", + | "_source": {"id": "d1", "i": "x", "ip": "x", "kw": "abcdefgh"}, + | "_ignored": ["i", "ip", "kw"]}""".stripMargin, + version = version, + table = caps + ).foreach { case (route, rows) => + withClue(s"[$version $route] ") { + val row = rows.head + row.getOrElse("i", null) shouldBe (null: Any) + row.getOrElse("ip", null) shouldBe (null: Any) + row.getOrElse("kw", null) shouldBe "abcdefgh" + row.get("id") shouldBe Some("d1") + } + } + } + } +} diff --git a/documentation/client/gateway.md b/documentation/client/gateway.md index f066f5a0..67a55b50 100644 --- a/documentation/client/gateway.md +++ b/documentation/client/gateway.md @@ -355,11 +355,21 @@ In a column not declared a list, a one-element array is its element and an empty several values fail the statement (*since `0.25.0`*, see [Columns holding several values](../sql/dql_statements.md#columns-holding-several-values)); a column declared `ARRAY` reads a single value as a list of one. A date field whose format core cannot read -for sure (a zone name, a region id) is a VARCHAR, its text as stored; a date value Elasticsearch -ignored (`ignore_malformed`) is NULL, and the other values of the same array keep theirs. An -integral column reads a fractional number or a numeric text as Elasticsearch indexed it, truncated -toward zero. A value a typed column cannot read is answered as stored: a value Elasticsearch did not -index (a number outside its type's range, a `long` text with surrounding spaces) is never narrowed. +for sure (a zone name, a region id) is a VARCHAR, its text as stored. A value Elasticsearch ignored +as malformed (`ignore_malformed`: the hit's `_ignored` names the field) in a top-level field is +NULL: a date, and *since `0.25.0`* a number, an `ip`, a `geo_point` and a `boolean` (where the +Elasticsearch version accepts the option on it), verified on Elasticsearch 7.17 and later; a +`scaled_float` from 8.6, the first version that names it in `_ignored` (before 8.6 its value is +answered as stored). In an array, and in a column declared `ARRAY`, the values Elasticsearch +indexed keep theirs and only the ones it ignored are NULL. A `keyword` or a `wildcard` over its +`ignore_above`, which `_ignored` names too, keeps its text. An integral column reads a fractional +number or a numeric text as Elasticsearch indexed it, truncated toward zero. A value a typed column +cannot read is answered as stored, never narrowed: a value this rule does not reach (an object's +sub-field, though `_ignored` names it; a value Elasticsearch refused without naming it, such as a +`scaled_float` before 8.6), and a number outside a column declared narrower than its field (an +`INT` over a `long`). *Since `0.25.0`*, the JDBC driver's +getters and an Arrow cell of a narrower type fail on such a number, naming it (`Value 3000000000 is +out of range for INT`), where they answered a wrapped value (see [JDBC](jdbc.md#supported-sql)). Aggregation values follow the same table: diff --git a/documentation/client/jdbc.md b/documentation/client/jdbc.md index a29364e8..65953d88 100644 --- a/documentation/client/jdbc.md +++ b/documentation/client/jdbc.md @@ -269,6 +269,13 @@ computed column the engine declares `DOUBLE` (`x * 2` over a `DOUBLE` column) is `Integer`s, is reported as `INTEGER`. A value the engine answers as stored keeps its own class (see [Value classes](gateway.md#value-classes)), and a column of no known type (`ANY`) can carry whole and decimal numbers alike: there, the column is reported as the type of its first value. +`getByte`, `getShort`, `getInt`, `getLong` and `getFloat` throw `SQLException` on a number outside +their type (*since engine `0.25.0`*: `Value 3000000000 is out of range for INT`) instead of +answering a wrapped value: `getInt` of a `BIGINT` past the integer range, a value answered as stored +in a column declared narrower than its field (an `INT` over a `long`), an `INT` sum past the +integer range, an `unsigned_long` above 2^63 - 1 through `getLong`, a `DOUBLE` beyond the largest +`REAL` through `getFloat`. A fractional number is still truncated toward zero (`getInt` of `42.9` is +`42`), and NaN or an infinity is no integer. A set operation's columns follow the declared types. On a JOIN result (*since arrow-extensions `0.3.4`*) the columns carry DuckDB's types, an integer getter throws `SQLException` on a value outside its type's range instead of answering a wrapped value, `getBigDecimal` of a diff --git a/es7/rest/src/test/scala/app/softnetwork/elastic/client/RestHighLevelClientIgnoredValueReadingSpec.scala b/es7/rest/src/test/scala/app/softnetwork/elastic/client/RestHighLevelClientIgnoredValueReadingSpec.scala new file mode 100644 index 00000000..fc80e9ed --- /dev/null +++ b/es7/rest/src/test/scala/app/softnetwork/elastic/client/RestHighLevelClientIgnoredValueReadingSpec.scala @@ -0,0 +1,19 @@ +/* + * Copyright 2025 SOFTNETWORK + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package app.softnetwork.elastic.client + +class RestHighLevelClientIgnoredValueReadingSpec extends IgnoredValueReadingSpec diff --git a/es8/java/src/test/scala/app/softnetwork/elastic/client/JavaClientIgnoredValueReadingSpec.scala b/es8/java/src/test/scala/app/softnetwork/elastic/client/JavaClientIgnoredValueReadingSpec.scala new file mode 100644 index 00000000..048200f5 --- /dev/null +++ b/es8/java/src/test/scala/app/softnetwork/elastic/client/JavaClientIgnoredValueReadingSpec.scala @@ -0,0 +1,19 @@ +/* + * Copyright 2025 SOFTNETWORK + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package app.softnetwork.elastic.client + +class JavaClientIgnoredValueReadingSpec extends IgnoredValueReadingSpec diff --git a/es9/java/src/test/scala/app/softnetwork/elastic/client/JavaClientIgnoredValueReadingSpec.scala b/es9/java/src/test/scala/app/softnetwork/elastic/client/JavaClientIgnoredValueReadingSpec.scala new file mode 100644 index 00000000..048200f5 --- /dev/null +++ b/es9/java/src/test/scala/app/softnetwork/elastic/client/JavaClientIgnoredValueReadingSpec.scala @@ -0,0 +1,19 @@ +/* + * Copyright 2025 SOFTNETWORK + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package app.softnetwork.elastic.client + +class JavaClientIgnoredValueReadingSpec extends IgnoredValueReadingSpec diff --git a/sql/src/main/scala/app/softnetwork/elastic/sql/type/ValueCoercion.scala b/sql/src/main/scala/app/softnetwork/elastic/sql/type/ValueCoercion.scala index 696a3da7..0ea2c0e2 100644 --- a/sql/src/main/scala/app/softnetwork/elastic/sql/type/ValueCoercion.scala +++ b/sql/src/main/scala/app/softnetwork/elastic/sql/type/ValueCoercion.scala @@ -72,19 +72,22 @@ object ValueCoercion { } def coerceToInt(value: Any): java.lang.Integer = value match { - case null => null - case n: Number => n.intValue() - case s: String => java.lang.Integer.valueOf(s) - case b: Boolean => if (b) 1 else 0 + case null => null + // SCHEMA-17 fix R-177: the canonical class as it is, any other number within INT's range + case i: java.lang.Integer => i + case n: Number => java.lang.Integer.valueOf(whole(n, IntRange).toInt) + case s: String => java.lang.Integer.valueOf(s) + case b: Boolean => if (b) 1 else 0 case _ => throw new java.sql.SQLException(s"Cannot convert ${value.getClass.getName} to INT") } def coerceToLong(value: Any): java.lang.Long = value match { - case null => null - case n: Number => n.longValue() - case s: String => java.lang.Long.valueOf(s) - case b: Boolean => if (b) 1L else 0L + case null => null + case l: java.lang.Long => l + case n: Number => java.lang.Long.valueOf(whole(n, BigIntRange)) + case s: String => java.lang.Long.valueOf(s) + case b: Boolean => if (b) 1L else 0L case _ => throw new java.sql.SQLException(s"Cannot convert ${value.getClass.getName} to BIGINT") } @@ -98,9 +101,10 @@ object ValueCoercion { } def coerceToFloat(value: Any): java.lang.Float = value match { - case null => null - case n: Number => n.floatValue() - case s: String => java.lang.Float.valueOf(s) + case null => null + case f: java.lang.Float => f + case n: Number => java.lang.Float.valueOf(real(n)) + case s: String => java.lang.Float.valueOf(s) case _ => throw new java.sql.SQLException(s"Cannot convert ${value.getClass.getName} to REAL") } @@ -115,17 +119,19 @@ object ValueCoercion { } def coerceToByte(value: Any): java.lang.Byte = value match { - case null => null - case n: Number => n.byteValue() - case s: String => java.lang.Byte.valueOf(s) + case null => null + case b: java.lang.Byte => b + case n: Number => java.lang.Byte.valueOf(whole(n, TinyIntRange).toByte) + case s: String => java.lang.Byte.valueOf(s) case _ => throw new java.sql.SQLException(s"Cannot convert ${value.getClass.getName} to TINYINT") } def coerceToShort(value: Any): java.lang.Short = value match { - case null => null - case n: Number => n.shortValue() - case s: String => java.lang.Short.valueOf(s) + case null => null + case s: java.lang.Short => s + case n: Number => java.lang.Short.valueOf(whole(n, SmallIntRange).toShort) + case s: String => java.lang.Short.valueOf(s) case _ => throw new java.sql.SQLException(s"Cannot convert ${value.getClass.getName} to SMALLINT") } @@ -224,4 +230,89 @@ object ValueCoercion { case _ => throw new java.sql.SQLException(s"Cannot convert ${value.getClass.getName} to TIMESTAMP") } + + // ─── Range guard (SCHEMA-17 fix R-177) ────────────────────────────────────── + // + // [[coerceToByte]], [[coerceToShort]], [[coerceToInt]], [[coerceToLong]] and [[coerceToFloat]] + // never narrow a number silently: one outside the target type's range throws + // `SQLException("Value is out of range for ")`, as DuckDB's conversion does, where + // `intValue()` & co. wrapped it (JDBC `getInt`, arrow's `Int32` cell: 3000000000 read + // -1294967296). A value within the range converts as it always did, its canonical class first + // and as it is (no new allocation); a fractional value is truncated toward zero as before, and + // it is the truncated value that must fit (2147483647.9 is 2147483647 for INT). + + /** The range of an integral SQL type, for [[whole]]: `bits` the most a two's-complement value of + * it holds besides its sign; `below` / `above` the double values strictly between which a number + * truncated toward zero is in range (below `Long.MinValue`, the next double down). + */ + private final class IntegralRange(val name: String, val min: Long, val max: Long, val bits: Int) { + val below: Double = if (min == Long.MinValue) Math.nextDown(min.toDouble) else min - 1d + val above: Double = max + 1d + val belowDecimal: java.math.BigDecimal = + java.math.BigDecimal.valueOf(min).subtract(java.math.BigDecimal.ONE) + val aboveDecimal: java.math.BigDecimal = + java.math.BigDecimal.valueOf(max).add(java.math.BigDecimal.ONE) + } + + private val TinyIntRange = new IntegralRange("TINYINT", Byte.MinValue, Byte.MaxValue, 7) + private val SmallIntRange = new IntegralRange("SMALLINT", Short.MinValue, Short.MaxValue, 15) + private val IntRange = new IntegralRange("INT", Int.MinValue, Int.MaxValue, 31) + private val BigIntRange = new IntegralRange("BIGINT", Long.MinValue, Long.MaxValue, 63) + + /** The largest REAL, exactly, as a decimal and as an integer (it is a whole number). */ + private val RealMaxDecimal: java.math.BigDecimal = + new java.math.BigDecimal(Float.MaxValue.toDouble) + private val RealMinDecimal: java.math.BigDecimal = RealMaxDecimal.negate() + private val RealMaxInteger: java.math.BigInteger = RealMaxDecimal.toBigInteger + private val RealMinInteger: java.math.BigInteger = RealMaxInteger.negate() + + private def outOfRange(value: Number, sqlType: String): java.sql.SQLException = + new java.sql.SQLException(s"Value $value is out of range for $sqlType") + + /** `n` truncated toward zero, where that is within `range`; else the out-of-range failure. A + * whole number of the JDK is judged exactly, a `BigInteger` by its bit length, a `BigDecimal` + * against the bounds (a fraction of magnitude below 1 is 0, never divided by its scale's power + * of ten); a `Double`, a `Float` and any other number by its double value, so NaN and the + * infinities are out of range. + */ + private def whole(n: Number, range: IntegralRange): Long = n match { + case _: java.lang.Integer | _: java.lang.Long | _: java.lang.Short | _: java.lang.Byte | + _: java.util.concurrent.atomic.AtomicInteger | _: java.util.concurrent.atomic.AtomicLong | + _: java.util.concurrent.atomic.LongAdder | _: java.util.concurrent.atomic.LongAccumulator => + val l = n.longValue() + if (l < range.min || l > range.max) throw outOfRange(n, range.name) else l + case b: java.math.BigInteger => + if (b.bitLength() > range.bits) throw outOfRange(n, range.name) else b.longValue() + case b: scala.math.BigInt => whole(b.bigInteger, range) + case d: java.math.BigDecimal => + if (d.compareTo(range.belowDecimal) <= 0 || d.compareTo(range.aboveDecimal) >= 0) + throw outOfRange(n, range.name) + else if (d.precision().toLong - d.scale() <= 0) 0L + else d.longValue() + case d: scala.math.BigDecimal => whole(d.bigDecimal, range) + case _ => + val d = n.doubleValue() + if (d > range.below && d < range.above) n.longValue() else throw outOfRange(n, range.name) + } + + /** `n` as a REAL, where it is within ±`Float.MaxValue`; else the out-of-range failure. NaN and + * the infinities of a floating number stay what they are; a whole number or a decimal beyond the + * bounds, which `floatValue()` turned into an infinity, fails. + */ + private def real(n: Number): Float = n match { + case b: java.math.BigInteger => + if (b.compareTo(RealMaxInteger) > 0 || b.compareTo(RealMinInteger) < 0) + throw outOfRange(n, "REAL") + else b.floatValue() + case b: scala.math.BigInt => real(b.bigInteger) + case d: java.math.BigDecimal => + if (d.compareTo(RealMaxDecimal) > 0 || d.compareTo(RealMinDecimal) < 0) + throw outOfRange(n, "REAL") + else d.floatValue() + case d: scala.math.BigDecimal => real(d.bigDecimal) + case _ => + val d = n.doubleValue() + if (java.lang.Double.isFinite(d) && Math.abs(d) > Float.MaxValue) throw outOfRange(n, "REAL") + else n.floatValue() + } } diff --git a/sql/src/test/scala/app/softnetwork/elastic/sql/type/ValueCoercionRangeSpec.scala b/sql/src/test/scala/app/softnetwork/elastic/sql/type/ValueCoercionRangeSpec.scala new file mode 100644 index 00000000..34ec0912 --- /dev/null +++ b/sql/src/test/scala/app/softnetwork/elastic/sql/type/ValueCoercionRangeSpec.scala @@ -0,0 +1,236 @@ +/* + * Copyright 2025 SOFTNETWORK + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package app.softnetwork.elastic.sql.`type` + +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +import java.math.{BigDecimal => JBigDecimal, BigInteger} + +/** SCHEMA-17 fix R-177 -- the numeric coercions JDBC's getters and arrow's cells go through never + * narrow a number silently: a value outside the target type's range throws `SQLException("Value + * is out of range for ")`, where `intValue()` & co. wrapped it (MEASURED on c167e07b, + * Elasticsearch 8.18.3: an `integer` holding 3000000000 read -1294967296 through `coerceToInt`, a + * `long` holding 1e20 read 7766279631452241920 through `coerceToLong`). A value within the range + * converts byte for byte as before -- its canonical class as it is --, a fraction truncated toward + * zero. + */ +class ValueCoercionRangeSpec extends AnyFlatSpec with Matchers { + + /** The failure of `f`, which must be the out-of-range one for `sqlType`. */ + private def outOfRange(sqlType: String)(f: => Any): String = { + val error = the[java.sql.SQLException] thrownBy f + error.getMessage should (startWith("Value ") and endWith(s" is out of range for $sqlType")) + error.getMessage + } + + /** One integral target: its coercion, its SQL name, its bounds. */ + private final case class Target(name: String, coerce: Any => Any, min: Long, max: Long) + + private val targets: Seq[Target] = Seq( + Target("TINYINT", ValueCoercion.coerceToByte, Byte.MinValue, Byte.MaxValue), + Target("SMALLINT", ValueCoercion.coerceToShort, Short.MinValue, Short.MaxValue), + Target("INT", ValueCoercion.coerceToInt, Int.MinValue, Int.MaxValue), + Target("BIGINT", ValueCoercion.coerceToLong, Long.MinValue, Long.MaxValue) + ) + + private def big(l: Long): BigInteger = BigInteger.valueOf(l) + + /** What the coercion answered before R-177, for a value within the target's range. */ + private def legacy(t: Target, n: Number): Any = t.name match { + case "TINYINT" => java.lang.Byte.valueOf(n.byteValue()) + case "SMALLINT" => java.lang.Short.valueOf(n.shortValue()) + case "INT" => java.lang.Integer.valueOf(n.intValue()) + case _ => java.lang.Long.valueOf(n.longValue()) + } + + "An integral coercion" should "fail on every bound's outer neighbour, whatever the number's class" in { + targets.foreach { t => + withClue(s"${t.name}: ") { + val below = big(t.min).subtract(BigInteger.ONE) + val above = big(t.max).add(BigInteger.ONE) + // the whole numbers of the JDK, where the neighbour fits a Long + if (t.name != "BIGINT") { + outOfRange(t.name)(t.coerce(java.lang.Long.valueOf(t.min - 1))) shouldBe + s"Value ${t.min - 1} is out of range for ${t.name}" + outOfRange(t.name)(t.coerce(java.lang.Long.valueOf(t.max + 1))) shouldBe + s"Value ${t.max + 1} is out of range for ${t.name}" + outOfRange(t.name)(t.coerce((t.min - 1).toDouble)) + outOfRange(t.name)(t.coerce((t.max + 1).toDouble)) + outOfRange(t.name)(t.coerce((t.max + 1).toFloat)) + } else { + // 2^63 and the next double below -2^63 + outOfRange(t.name)(t.coerce(9.223372036854775808e18)) + outOfRange(t.name)(t.coerce(Math.nextDown(-9.223372036854775808e18))) + outOfRange(t.name)(t.coerce(9.223372036854775808e18f)) + } + outOfRange(t.name)(t.coerce(below)) shouldBe s"Value $below is out of range for ${t.name}" + outOfRange(t.name)(t.coerce(above)) + outOfRange(t.name)(t.coerce(new JBigDecimal(below))) + outOfRange(t.name)(t.coerce(new JBigDecimal(above))) + outOfRange(t.name)(t.coerce(scala.math.BigInt(above))) + outOfRange(t.name)(t.coerce(scala.math.BigDecimal(new JBigDecimal(below)))) + // a BigInteger beyond a Long, which `longValue()` wrapped + outOfRange(t.name)(t.coerce(new BigInteger("100000000000000000000"))) + outOfRange(t.name)(t.coerce(new JBigDecimal("1E+1000000000"))) + // NaN and the infinities have no integral value + Seq[Any]( + Double.NaN, + Double.PositiveInfinity, + Double.NegativeInfinity, + Float.NaN, + Float.PositiveInfinity, + Float.NegativeInfinity + ).foreach(v => outOfRange(t.name)(t.coerce(v))) + } + } + } + + it should "convert each bound itself, byte for byte as before, in its canonical class" in { + targets.foreach { t => + withClue(s"${t.name}: ") { + val population: Seq[Number] = Seq[Number]( + java.lang.Long.valueOf(t.min), + java.lang.Long.valueOf(t.max), + java.lang.Long.valueOf(0L), + java.lang.Long.valueOf(-1L), + java.lang.Integer.valueOf(42), + java.lang.Short.valueOf(7.toShort), + java.lang.Byte.valueOf(-7.toByte), + big(t.min), + big(t.max), + new JBigDecimal(big(t.max)), + new JBigDecimal(big(t.min)), + scala.math.BigInt(t.max), + scala.math.BigDecimal(t.min), + java.lang.Double.valueOf(42.9), + java.lang.Double.valueOf(-42.9), + java.lang.Float.valueOf(1.5f), + java.lang.Double.valueOf(-0.0) + ) ++ ( + // a whole double at each bound, where the double holds it exactly + if (t.name != "BIGINT") + Seq[Number]( + java.lang.Double.valueOf(t.min.toDouble), + java.lang.Double.valueOf(t.max.toDouble) + ) + else Seq[Number](java.lang.Double.valueOf(-9.223372036854775808e18)) + ) + population.foreach { n => + withClue(s"$n (${n.getClass.getName}): ") { + val answer = t.coerce(n) + answer shouldBe legacy(t, n) + answer.getClass shouldBe legacy(t, n).getClass + } + } + } + } + } + + it should "keep the truncation toward zero, the truncated value judged against the range" in { + ValueCoercion.coerceToInt(2147483647.9) shouldBe Int.MaxValue + ValueCoercion.coerceToInt(-2147483648.9) shouldBe Int.MinValue + ValueCoercion.coerceToInt(new JBigDecimal("2147483647.9")) shouldBe Int.MaxValue + ValueCoercion.coerceToInt(new JBigDecimal("-2147483648.9")) shouldBe Int.MinValue + outOfRange("INT")(ValueCoercion.coerceToInt(2147483648.0)) + outOfRange("INT")(ValueCoercion.coerceToInt(-2147483649.0)) + outOfRange("INT")(ValueCoercion.coerceToInt(new JBigDecimal("2147483648"))) + ValueCoercion.coerceToByte(127.99) shouldBe 127.toByte + outOfRange("TINYINT")(ValueCoercion.coerceToByte(128.0)) + ValueCoercion.coerceToShort(-32768.5) shouldBe -32768.toShort + outOfRange("SMALLINT")(ValueCoercion.coerceToShort(-32769.0)) + ValueCoercion.coerceToLong(9.2233720368547748e18) shouldBe 9223372036854774784L + // a fraction of magnitude below 1 is 0, without dividing by ten to the power of its scale + ValueCoercion.coerceToInt(new JBigDecimal("1E-1000000000")) shouldBe 0 + ValueCoercion.coerceToLong(new JBigDecimal("-0.999")) shouldBe 0L + } + + it should "answer its canonical class as it is, with no new instance" in { + // values outside the JDK's box caches: a re-boxed answer would be another instance + val i = java.lang.Integer.valueOf(1000000) + (ValueCoercion.coerceToInt(i) eq i) shouldBe true + val l = java.lang.Long.valueOf(3000000000L) + (ValueCoercion.coerceToLong(l) eq l) shouldBe true + val s = java.lang.Short.valueOf(1000.toShort) + (ValueCoercion.coerceToShort(s) eq s) shouldBe true + val f = java.lang.Float.valueOf(1e30f) + (ValueCoercion.coerceToFloat(f) eq f) shouldBe true + } + + it should "keep every non-number arm as before" in { + targets.foreach(t => withClue(s"${t.name}: ")(t.coerce(null) shouldBe (null: Any))) + ValueCoercion.coerceToFloat(null) shouldBe (null: java.lang.Float) + ValueCoercion.coerceToInt("42") shouldBe 42 + ValueCoercion.coerceToLong("3000000000") shouldBe 3000000000L + ValueCoercion.coerceToInt(true) shouldBe 1 + ValueCoercion.coerceToLong(false) shouldBe 0L + a[NumberFormatException] should be thrownBy ValueCoercion.coerceToInt("3000000000") + a[java.sql.SQLException] should be thrownBy ValueCoercion.coerceToInt(new Object) + } + + it should "fail on the cells T0-1 measured wrapping (an integer of 3000000000, a long of 1e20)" in { + outOfRange("INT")(ValueCoercion.coerceToInt(java.lang.Long.valueOf(3000000000L))) shouldBe + "Value 3000000000 is out of range for INT" + outOfRange("BIGINT")( + ValueCoercion.coerceToLong(new BigInteger("100000000000000000000")) + ) shouldBe "Value 100000000000000000000 is out of range for BIGINT" + // an unsigned_long above 2^63 - 1, which `getLong` wrapped negative + outOfRange("BIGINT")(ValueCoercion.coerceToLong(new BigInteger("18446744073709551615"))) + } + + "coerceToFloat" should "fail on a finite number beyond the largest REAL" in { + val beyond = Math.nextUp(Float.MaxValue.toDouble) + outOfRange("REAL")(ValueCoercion.coerceToFloat(beyond)) + outOfRange("REAL")(ValueCoercion.coerceToFloat(-beyond)) + outOfRange("REAL")( + ValueCoercion.coerceToFloat(1e39) + ) shouldBe "Value 1.0E39 is out of range for REAL" + outOfRange("REAL")(ValueCoercion.coerceToFloat(Double.MaxValue)) + outOfRange("REAL")(ValueCoercion.coerceToFloat(BigInteger.ONE.shiftLeft(128))) + outOfRange("REAL")(ValueCoercion.coerceToFloat(BigInteger.ONE.shiftLeft(128).negate())) + outOfRange("REAL")(ValueCoercion.coerceToFloat(new JBigDecimal("1E+39"))) + outOfRange("REAL")(ValueCoercion.coerceToFloat(new JBigDecimal("-1E+1000000000"))) + outOfRange("REAL")(ValueCoercion.coerceToFloat(scala.math.BigDecimal("1E+39"))) + } + + it should "convert the largest REAL itself, NaN and the infinities, byte for byte as before" in { + val population: Seq[Number] = Seq[Number]( + java.lang.Double.valueOf(Float.MaxValue.toDouble), + java.lang.Double.valueOf(-Float.MaxValue.toDouble), + java.lang.Double.valueOf(Double.NaN), + java.lang.Double.valueOf(Double.PositiveInfinity), + java.lang.Double.valueOf(Double.NegativeInfinity), + java.lang.Double.valueOf(1.5), + java.lang.Double.valueOf(1e-50), + java.lang.Long.valueOf(Long.MaxValue), + java.lang.Integer.valueOf(Int.MinValue), + new JBigDecimal(Float.MaxValue.toDouble), + new JBigDecimal("1E-1000000000"), + new BigInteger("340282346638528859811704183484516925440"), + BigInteger.valueOf(42L), + scala.math.BigInt(42) + ) + population.foreach { n => + withClue(s"$n (${n.getClass.getName}): ") { + val answer = ValueCoercion.coerceToFloat(n) + java.lang.Float.floatToRawIntBits(answer) shouldBe java.lang.Float.floatToRawIntBits( + n.floatValue() + ) + } + } + } +} diff --git a/testkit/src/main/scala/app/softnetwork/elastic/client/IgnoredValueReadingSpec.scala b/testkit/src/main/scala/app/softnetwork/elastic/client/IgnoredValueReadingSpec.scala new file mode 100644 index 00000000..54673a77 --- /dev/null +++ b/testkit/src/main/scala/app/softnetwork/elastic/client/IgnoredValueReadingSpec.scala @@ -0,0 +1,660 @@ +/* + * Copyright 2025 SOFTNETWORK + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package app.softnetwork.elastic.client + +import akka.actor.ActorSystem +import akka.stream.scaladsl.Sink +import app.softnetwork.elastic.client.result.{ + DdlResult, + ElasticFailure, + ElasticSuccess, + QueryResult, + QueryRows, + QueryStream, + QueryStructured +} +import app.softnetwork.elastic.client.spi.ElasticClientFactory +import app.softnetwork.elastic.scalatest.ElasticDockerTestKit +import app.softnetwork.elastic.sql.`type`.ValueCoercion +import app.softnetwork.persistence.generateUUID +import com.fasterxml.jackson.databind.ObjectMapper +import org.apache.http.entity.ContentType +import org.apache.http.nio.entity.NStringEntity +import org.apache.http.util.EntityUtils +import org.elasticsearch.client.Request +import org.scalatest.flatspec.AnyFlatSpecLike +import org.scalatest.matchers.should.Matchers +import org.slf4j.{Logger, LoggerFactory} + +import java.time.{ZoneOffset, ZonedDateTime} +import scala.collection.immutable.ListMap +import scala.concurrent.Await +import scala.concurrent.duration._ +import scala.util.{Failure, Success, Try} + +/** SCHEMA-17 fix R-172 -- a value Elasticsearch ignored as malformed (`ignore_malformed`: the hit's + * `_ignored` names its field) reads as NULL for every kind that takes the option, as a date + * already did (SCHEMA-2 D8); a keyword or a wildcard over `ignore_above`, which `_ignored` names + * too, keeps its text. On a real cluster, one document per value, beside a keyword and a number + * Elasticsearch indexed: + * + * - the premises: every kind takes `ignore_malformed` (a `boolean` only where the major maps the + * option), every document is indexed, and the raw hit's `_ignored` names each field holding a + * value Elasticsearch could not parse -- a canary, so no row below passes empty; + * - such a value is NULL in its column in `SELECT *`, a named column, a WHERE-filtered and a + * scrolled (unLIMITed) statement, the document's other cells intact; a value Elasticsearch + * indexed keeps its reading; + * - an `ARRAY` column declared in place keeps each element Elasticsearch indexed and answers + * the others NULL; + * - an `integer` holding 3000000000 and a `float` holding 1e39 are NULL, never a wrapped number + * through `ValueCoercion`; + * - `_ignored` naming an object's sub-field never NULLs the object (the key matches exactly); + * - SCHEMA-17 fix R-177: a number Elasticsearch indexed that core answers as stored outside its + * column's type -- an `INT` declared over a `long` field, a computed `INT` past the int range, + * an object's sub-field -- fails through `ValueCoercion` naming the value, never wraps. + * + * Elasticsearch 7.17 and later (R-176): 6.8 rejects an out-of-range `short` / `integer` / `long` + * document outright; this spec has no 6.8 runner. A `scaled_float` Elasticsearch refused is named + * in `_ignored` only from 8.6 (A-206): 6.8, 7.x and 8.0 to 8.5 index it and name nothing, so there + * core has no verdict and answers it as stored (D6), which the spec asserts there in place of NULL + * (`namesScaledFloat`). Documents are indexed raw: the core client's `index` rewrites an + * `unsigned_long` above 2^63-1. + */ +trait IgnoredValueReadingSpec extends AnyFlatSpecLike with ElasticDockerTestKit with Matchers { + + lazy val log: Logger = LoggerFactory.getLogger(getClass.getName) + + implicit val system: ActorSystem = ActorSystem(generateUUID()) + + lazy val client: ElasticClientApi = ElasticClientFactory.create(elasticConfig) + + private val mapper = new ObjectMapper() + + protected val table = "r172_t" + + /** SCHEMA-17 fix R-177 -- a table core creates, `w` declared `INT` over a `long` field, `p` and + * `q` two `INT` columns: one document, holding 3000000000 in `w` and 2000000000 in `p` and `q`. + */ + protected val wide = "r172_w" + + /** SCHEMA-17 fix R-172 (A-206) -- whether this major names a `scaled_float` it refused in the + * hit's `_ignored`: from 8.6 on (`ScaledFloatFieldMapper` calls `addIgnoredField` from 8.6.0). + * Before, the refused value is indexed unnamed and keeps its as-stored reading; every other kind + * is named from 7.17 on. + */ + protected lazy val namesScaledFloat: Boolean = + ElasticsearchVersion.isAtLeast(elasticVersion, 8, 6) + + /** The fields whose refused values this major does not name in `_ignored` (A-206). */ + private lazy val unnamed: Set[String] = if (namesScaledFloat) Set.empty else Set("sf") + + /** A kind `ignore_malformed` applies to: its field, its Elasticsearch type, a value Elasticsearch + * cannot parse into it, a value out of its range where it has one, a valid value and its read. + */ + protected final case class Kind( + field: String, + esType: String, + malformed: String, + outOfRange: Option[String], + valid: String, + read: Any, + options: String = "" + ) { + def mapping: String = s"""{"type":"$esType","ignore_malformed":true$options}""" + } + + /** A string kind over `ignore_above`: Elasticsearch names it in `_ignored`, and keeps it. */ + protected final case class Capped(field: String, esType: String) + + /** A field declared `ARRAY` in place, holding values Elasticsearch indexed and values it + * ignored, and the list it reads. + */ + protected final case class Listed( + field: String, + esType: String, + declared: String, + values: String, + read: Seq[Any] + ) + + private def utc(y: Int, mo: Int, d: Int, h: Int = 0, mi: Int = 0): ZonedDateTime = + ZonedDateTime.of(y, mo, d, h, mi, 0, 0, ZoneOffset.UTC) + + protected val point: ListMap[String, Any] = ListMap("lat" -> 1.5, "lon" -> 2.5) + + /** A text a geo_point cannot read: `x` alone would be a geohash. */ + private val notAPoint = "\"not a point\"" + + protected lazy val kinds: Seq[Kind] = Seq( + Kind("tb", "byte", "\"x\"", Some("200"), "7", Integer.valueOf(7)), + Kind("sh", "short", "\"x\"", Some("40000"), "7", Integer.valueOf(7)), + Kind("i", "integer", "\"x\"", Some("3000000000"), "7", Integer.valueOf(7)), + Kind("l", "long", "\"x\"", Some("100000000000000000000"), "7", java.lang.Long.valueOf(7L)), + Kind("u", "unsigned_long", "\"x\"", Some("-1"), "7", java.lang.Long.valueOf(7L)), + Kind("r", "float", "\"x\"", Some("1e39"), "1.5", java.lang.Float.valueOf(1.5f)), + Kind("hf", "half_float", "\"x\"", Some("65520"), "0.5", java.lang.Float.valueOf(0.5f)), + Kind("x", "double", "\"x\"", Some("\"1e309\""), "2.5", java.lang.Double.valueOf(2.5)), + Kind( + "sf", + "scaled_float", + "\"x\"", + Some("\"1e309\""), + "1.25", + java.lang.Double.valueOf(1.25), + options = ""","scaling_factor":100""" + ), + Kind("ip", "ip", "\"x\"", None, "\"10.0.0.1\"", "10.0.0.1"), + Kind( + "g", + "geo_point", + notAPoint, + Some("""{"lat":100.0,"lon":200.0}"""), + """{"lat":1.5,"lon":2.5}""", + point + ), + Kind("b", "boolean", "\"x\"", None, "true", java.lang.Boolean.TRUE), + Kind("dm", "date", "\"not-a-date\"", None, "\"2024-01-31T10:30:00Z\"", utc(2024, 1, 31, 10, 30)) + ) + + protected lazy val capped: Seq[Capped] = Seq(Capped("kw", "keyword"), Capped("wc", "wildcard")) + + /** The text a capped string holds, over its `ignore_above` of 3. */ + protected val cappedText = "abcdefgh" + + protected lazy val listed: Seq[Listed] = Seq( + Listed("la", "long", "ARRAY", """[1, "x", 3]""", Seq(1L, null, 3L)), + Listed("ia", "integer", "ARRAY", """[1, 3000000000, "y"]""", Seq(1, null, null)), + Listed("ra", "float", "ARRAY", """[1.5, 1e39, "x"]""", Seq(1.5f, null, null)), + Listed( + "hfa", + "half_float", + "ARRAY", + """[65519, 65520, "x"]""", + Seq(65519.0f, null, null) + ), + Listed( + "ua", + "unsigned_long", + "ARRAY", + """[-1, 18446744073709551615, 5]""", + Seq(null, new java.math.BigInteger("18446744073709551615"), 5L) + ), + Listed("ipa", "ip", "ARRAY", """["10.0.0.1", "x"]""", Seq("10.0.0.1", null)), + Listed( + "ga", + "geo_point", + "ARRAY", + s"""[{"lat":1.5,"lon":2.5}, $notAPoint]""", + Seq(point, null) + ), + Listed( + "da", + "date", + "ARRAY", + """["2024-01-31T10:30:00Z", "bad"]""", + Seq(utc(2024, 1, 31, 10, 30), null) + ) + ) + + // the fixture, as this major answered it (filled once, by `beforeAll`) + + /** Each field's mapping PUT: accepted, or Elasticsearch's refusal. */ + protected val mappings = + scala.collection.mutable.LinkedHashMap.empty[String, Either[String, Unit]] + + /** Each document's indexing: indexed, or Elasticsearch's rejection. */ + protected val indexing = + scala.collection.mutable.LinkedHashMap.empty[String, Either[String, Unit]] + + /** Each in-place `ALTER` declaring a list: done, or its failure. */ + protected val alters = scala.collection.mutable.LinkedHashMap.empty[String, Either[String, Unit]] + + /** The paths each document's raw hit `_ignored` names. */ + protected val ignoredBy = scala.collection.mutable.LinkedHashMap.empty[String, Set[String]] + + /** The one field each document holds, beside `id`, `k` and `ok`. */ + protected val fieldOf = scala.collection.mutable.LinkedHashMap.empty[String, String] + + private def drop(index: String): Unit = { + Try(Await.result(client.run(s"DROP TABLE IF EXISTS $index"), 60.seconds)) + Try(client.deleteIndex(index)) + } + + private def ddl(sql: String): Either[String, Unit] = + Try(Await.result(client.run(sql), 120.seconds)) match { + case Success(ElasticSuccess(DdlResult(true, _))) => Right(()) + case Success(ElasticFailure(error)) => Left(error.message) + case Success(other) => Left(String.valueOf(other)) + case Failure(t) => Left(s"${t.getClass.getSimpleName}: ${t.getMessage}") + } + + private def mapField(field: String, mapping: String): Boolean = { + val outcome: Either[String, Unit] = + Try(client.setMapping(table, s"""{"properties": {"$field": $mapping}}""")) match { + case Success(ElasticSuccess(true)) => Right(()) + case Success(ElasticFailure(error)) => Left(error.message) + case Success(other) => Left(String.valueOf(other)) + case Failure(t) => Left(s"${t.getClass.getSimpleName}: ${t.getMessage}") + } + mappings.put(field, outcome) + outcome.isRight + } + + /** `json` indexed raw as the document `id` of `index`, its outcome recorded in [[indexing]]. */ + private def putRaw(index: String, id: String, json: String): Unit = { + val request = new Request("PUT", s"/$index/_doc/$id") + request.setEntity(new NStringEntity(json, ContentType.APPLICATION_JSON)) + indexing.put( + id, + Try(restClient.performRequest(request)) match { + case Success(_) => Right(()) + case Failure(t) => Left(s"${t.getClass.getSimpleName}: ${t.getMessage}") + } + ) + () + } + + private def putDoc(id: String, field: String, value: String): Unit = { + fieldOf.put(id, field) + putRaw(table, id, s"""{"id":"$id","k":"keep","ok":5,"$field":$value}""") + } + + /** The `CREATE TABLE` of [[wide]]: done, or its failure. */ + protected var wideCreated: Either[String, Unit] = Left("not run") + + override def beforeAll(): Unit = { + super.beforeAll() + drop(wide) + wideCreated = ddl( + s"CREATE TABLE $wide (id KEYWORD, w INT OPTIONS (type = 'long'), p INT, q INT)" + ) + if (wideCreated.isRight) { + putRaw(wide, "w1", """{"id":"w1","w":3000000000,"p":2000000000,"q":2000000000}""") + client.refresh(wide) + } + drop(table) + client + .createIndex(table, settings = """{"number_of_shards": 1, "number_of_replicas": 0}""") + .get shouldBe true + client + .setMapping( + table, + """{"properties": {"id": {"type": "keyword"}, "k": {"type": "keyword"}, + | "ok": {"type": "long"}}}""".stripMargin + ) + .get shouldBe true + // every kind is tried on every major: a type this major does not map, or that refuses the + // option, is recorded and holds no document + kinds.foreach { k => + if (mapField(k.field, k.mapping)) { + putDoc(s"${k.field}_m", k.field, k.malformed) + k.outOfRange.foreach(putDoc(s"${k.field}_o", k.field, _)) + putDoc(s"${k.field}_v", k.field, k.valid) + } + } + capped.foreach { c => + if (mapField(c.field, s"""{"type":"${c.esType}","ignore_above":3}""")) { + putDoc(s"${c.field}_m", c.field, s""""$cappedText"""") + putDoc(s"${c.field}_v", c.field, "\"ab\"") + } + } + listed.foreach { l => + if (mapField(l.field, s"""{"type":"${l.esType}","ignore_malformed":true}""")) + putDoc(s"${l.field}_a", l.field, l.values) + } + if ( + mapField( + "obj", + """{"properties": {"n": {"type": "long", "ignore_malformed": true}, + | "i": {"type": "integer", "ignore_malformed": true}}}""".stripMargin + ) + ) { + putDoc("obj_n", "obj", """{"n":"x"}""") + putDoc("obj_i", "obj", """{"i":3000000000}""") + } + // the lists are declared once every field is mapped: the first statement caches the table's + // schema, which a field mapped after it would be missing from + listed.foreach { l => + if (mappings.get(l.field).exists(_.isRight)) + alters.put( + l.field, + ddl(s"ALTER TABLE $table ALTER COLUMN ${l.field} SET DATA TYPE ${l.declared}") + ) + } + client.refresh(table) + // the raw hits' `_ignored`, as Elasticsearch answers them + val response = restClient.performRequest(new Request("GET", s"/$table/_search?size=1000")) + val hits = mapper.readTree(EntityUtils.toString(response.getEntity)).path("hits").path("hits") + val it = hits.elements() + while (it.hasNext) { + val hit = it.next() + val names = Set.newBuilder[String] + val ignored = hit.path("_ignored").elements() + while (ignored.hasNext) names += ignored.next().asText() + ignoredBy.put(hit.path("_id").asText(), names.result()) + } + } + + override def afterAll(): Unit = { + drop(table) + drop(wide) + super.afterAll() + } + + // ------------------------------------------------------------------------------------------- + // Results + // ------------------------------------------------------------------------------------------- + + private def answer(result: QueryResult): Seq[ListMap[String, Any]] = + result match { + case q: QueryRows => q.rows + case q: QueryStructured => q.response.results + case q: QueryStream => Await.result(q.stream.map(_._1).runWith(Sink.seq), 60.seconds) + case other => fail(s"unexpected result $other") + } + + /** The statement's outcome: its rows, or its failure's message -- a failed stream included. */ + protected def outcome(sql: String): Either[String, Seq[ListMap[String, Any]]] = + Try(Await.result(client.run(sql), 60.seconds) match { + case ElasticSuccess(result) => Right(answer(result)) + case ElasticFailure(error) => Left(error.message) + }).toEither.left + .map(t => s"${t.getClass.getSimpleName}: ${t.getMessage}") + .joinRight + + protected def rowsOf(sql: String): Seq[ListMap[String, Any]] = + outcome(sql).fold(error => fail(s"[$sql] failed: $error"), identity) + + private def one(sql: String): ListMap[String, Any] = + rowsOf(sql) match { + case Seq(row) => row + case other => fail(s"[$sql] answered ${other.size} rows: $other") + } + + private def byId(rows: Seq[ListMap[String, Any]]): Map[String, ListMap[String, Any]] = + rows.map(r => String.valueOf(r.getOrElse("id", "?")) -> r).toMap + + private def indexed(doc: String): Boolean = indexing.get(doc).exists(_.isRight) + + /** The (document, field) pairs whose one value Elasticsearch ignored, by the raw hit. */ + private def ignoredCells(fields: Set[String]): Seq[(String, String)] = + fieldOf.toSeq.collect { + case (doc, field) if fields.contains(field) && ignoredBy.get(doc).exists(_.contains(field)) => + doc -> field + } + + private def intact(row: ListMap[String, Any], doc: String): Unit = { + row.get("id") shouldBe Some(doc) + row.get("k") shouldBe Some("keep") + row.get("ok") shouldBe Some(5L) + } + + // ------------------------------------------------------------------------------------------- + // Premises (T0-1) + // ------------------------------------------------------------------------------------------- + + "The fixture" should "hold every premise of R-172 on this major (T0-1)" in { + // every type takes `ignore_malformed` -- a boolean only where this major maps the option + kinds.filter(_.esType != "boolean").foreach { k => + withClue(s"${k.field} (${k.esType}): ")(mappings.get(k.field) shouldBe Some(Right(()))) + } + capped.foreach { c => + withClue(s"${c.field} (${c.esType}): ")(mappings.get(c.field) shouldBe Some(Right(()))) + } + listed.foreach { l => + withClue(s"${l.field} (${l.esType}): ") { + mappings.get(l.field) shouldBe Some(Right(())) + alters.get(l.field) shouldBe Some(Right(())) + } + } + // Elasticsearch indexes every document holding a value it cannot parse, and names the field + // in the hit's `_ignored` -- an object's sub-field by its path + val cappedFields = capped.map(_.field).toSet + val refused: Seq[(String, String)] = + fieldOf.toSeq.collect { + case (doc, field) + if ((doc.endsWith("_m") && !cappedFields.contains(field)) || doc.endsWith("_a")) && + !unnamed.contains(field) => + doc -> field + } ++ Seq("obj_n" -> "obj.n", "obj_i" -> "obj.i").filter { case (doc, _) => + fieldOf.contains(doc) + } + refused should not be empty + refused.foreach { case (doc, field) => + withClue(s"$doc: ") { + indexing.get(doc) shouldBe Some(Right(())) + ignoredBy.getOrElse(doc, Set.empty[String]) should contain(field) + } + } + // ...except a scaled_float before 8.6, indexed and named nowhere (A-206) + unnamed.foreach { field => + Seq(s"${field}_m", s"${field}_o").foreach { doc => + withClue(s"$doc (unnamed before 8.6): ") { + indexing.get(doc) shouldBe Some(Right(())) + ignoredBy.getOrElse(doc, Set.empty[String]) should not contain field + } + } + } + // a string over `ignore_above` is indexed, and named (AC3) + capped.filter(c => mappings.get(c.field).exists(_.isRight)).foreach { c => + val doc = s"${c.field}_m" + withClue(s"$doc: ") { + indexing.get(doc) shouldBe Some(Right(())) + ignoredBy.getOrElse(doc, Set.empty[String]) should contain(c.field) + } + } + // ...and every valid value, naming none + fieldOf.keys.filter(_.endsWith("_v")).foreach { doc => + withClue(s"$doc: ") { + indexing.get(doc) shouldBe Some(Right(())) + ignoredBy.getOrElse(doc, Set.empty[String]) shouldBe empty + } + } + // R-177: the table core created, and its one document + wideCreated shouldBe Right(()) + indexing.get("w1") shouldBe Some(Right(())) + } + + // ------------------------------------------------------------------------------------------- + // AC2 -- one value + // ------------------------------------------------------------------------------------------- + + "A value Elasticsearch ignored as malformed" should + "read NULL in its column on every venue, its document's other cells intact (AC2)" in { + val cells = ignoredCells(kinds.map(_.field).toSet) + // a canary: at least the text each mapped kind cannot parse -- each kind this major names + // (A-206: a scaled_float from 8.6 on, its unnamed reading asserted below) + val canary = kinds + .filter(k => mappings.get(k.field).exists(_.isRight) && !unnamed.contains(k.field)) + .map(_.field + "_m") + cells.map(_._1) should contain allElementsOf canary + // SELECT *, scrolled and LIMITed + Seq(s"SELECT * FROM $table", s"SELECT * FROM $table LIMIT 1000").foreach { sql => + val rows = byId(rowsOf(sql)) + cells.foreach { case (doc, field) => + withClue(s"[$sql] $doc.$field: ") { + val row = rows.getOrElse(doc, fail("no row")) + row.getOrElse(field, null) shouldBe (null: Any) + intact(row, doc) + } + } + } + // a named column, scrolled, LIMITed, filtered by WHERE + cells.groupBy(_._2).foreach { case (field, byField) => + val named = s"SELECT id, k, ok, $field FROM $table" + Seq(named, s"$named LIMIT 1000", s"$named WHERE ok = 5").foreach { sql => + val rows = byId(rowsOf(sql)) + byField.foreach { case (doc, _) => + withClue(s"[$sql] $doc: ") { + val row = rows.getOrElse(doc, fail("no row")) + row.getOrElse(field, null) shouldBe (null: Any) + intact(row, doc) + } + } + } + byField.foreach { case (doc, _) => + withClue(s"[$named WHERE id = '$doc'] ") { + one(s"$named WHERE id = '$doc'").getOrElse(field, null) shouldBe (null: Any) + } + } + } + // a value Elasticsearch indexed keeps its reading + kinds.filter(k => indexed(s"${k.field}_v")).foreach { k => + withClue(s"${k.field}_v: ") { + one(s"SELECT id, ${k.field} FROM $table WHERE id = '${k.field}_v'")(k.field) shouldBe k.read + } + } + } + + // ------------------------------------------------------------------------------------------- + // A-206 -- a scaled_float, named in _ignored from Elasticsearch 8.6 on + // ------------------------------------------------------------------------------------------- + + /** `sf`'s two refused values, each with the reading it keeps where the major names neither (T0-1 + * on 6.8.23: the text as stored; the non-finite text read as a `Double` infinity). + */ + private val scaledFloatAsStored: Seq[(String, Any)] = + Seq("sf_m" -> "x", "sf_o" -> java.lang.Double.valueOf(Double.PositiveInfinity)) + + "A scaled_float Elasticsearch refused" should + "read NULL where _ignored names it (8.6+), and as stored where it does not (A-206)" in { + val star = byId(rowsOf(s"SELECT * FROM $table")) + scaledFloatAsStored.foreach { case (doc, asStored) => + val expected: Any = if (namesScaledFloat) null else asStored + withClue(s"$doc (named: $namesScaledFloat on $elasticVersion): ") { + indexing.get(doc) shouldBe Some(Right(())) + val names = ignoredBy.getOrElse(doc, Set.empty[String]) + if (namesScaledFloat) names should contain("sf") else names should not contain "sf" + one(s"SELECT id, sf FROM $table WHERE id = '$doc'").getOrElse("sf", null) shouldBe expected + val row = star.getOrElse(doc, fail("no row")) + row.getOrElse("sf", null) shouldBe expected + intact(row, doc) + } + } + } + + // ------------------------------------------------------------------------------------------- + // AC3 -- a string over ignore_above + // ------------------------------------------------------------------------------------------- + + "A string over ignore_above" should "keep its text, though the hit's _ignored names it (AC3)" in { + val docs = capped.filter(c => indexed(s"${c.field}_m")) + docs.map(_.field) should contain("kw") + val star = byId(rowsOf(s"SELECT * FROM $table")) + docs.foreach { c => + val doc = s"${c.field}_m" + withClue(s"$doc: ") { + // named: the canary that the text is kept DESPITE it + ignoredBy.getOrElse(doc, Set.empty[String]) should contain(c.field) + one(s"SELECT id, ${c.field} FROM $table WHERE id = '$doc'")(c.field) shouldBe cappedText + star.getOrElse(doc, fail("no row")).getOrElse(c.field, null) shouldBe cappedText + } + } + } + + // ------------------------------------------------------------------------------------------- + // AC2 -- a declared list + // ------------------------------------------------------------------------------------------- + + "An ARRAY column declared in place" should + "keep each element Elasticsearch indexed and answer the others NULL (AC2, A-202)" in { + val docs = listed.filter(l => indexed(s"${l.field}_a")) + docs.map(_.field) should contain allElementsOf Seq("la", "ia", "ra") + val star = byId(rowsOf(s"SELECT * FROM $table")) + docs.foreach { l => + val doc = s"${l.field}_a" + withClue(s"$doc: ") { + one(s"SELECT id, ${l.field} FROM $table WHERE id = '$doc'")(l.field) shouldBe l.read + star.getOrElse(doc, fail("no row")).getOrElse(l.field, null) shouldBe l.read + } + } + } + + // ------------------------------------------------------------------------------------------- + // AC4 -- the SILENT case + // ------------------------------------------------------------------------------------------- + + "An out-of-range number Elasticsearch ignored" should + "read NULL, never a wrapped number through the coercions (AC4)" in { + // an `integer` of 3000000000 + indexing.get("i_o") shouldBe Some(Right(())) + ignoredBy.getOrElse("i_o", Set.empty[String]) should contain("i") + val i = one(s"SELECT id, i FROM $table WHERE id = 'i_o'").getOrElse("i", null) + withClue(s"i = $i (${Option(i).map(_.getClass.getName).orNull}): ") { + ValueCoercion.coerceToInt(i) shouldBe (null: java.lang.Integer) + i shouldBe (null: Any) + } + // a `float` of 1e39 + indexing.get("r_o") shouldBe Some(Right(())) + ignoredBy.getOrElse("r_o", Set.empty[String]) should contain("r") + val r = one(s"SELECT id, r FROM $table WHERE id = 'r_o'").getOrElse("r", null) + withClue(s"r = $r (${Option(r).map(_.getClass.getName).orNull}): ") { + ValueCoercion.coerceToFloat(r) shouldBe (null: java.lang.Float) + r shouldBe (null: Any) + } + } + + // ------------------------------------------------------------------------------------------- + // A-202 -- the key matches exactly + // ------------------------------------------------------------------------------------------- + + "A sub-field Elasticsearch ignored" should "never NULL its parent object (A-202)" in { + indexing.get("obj_n") shouldBe Some(Right(())) + ignoredBy.getOrElse("obj_n", Set.empty[String]) should contain("obj.n") + one(s"SELECT id, obj FROM $table WHERE id = 'obj_n'").getOrElse("obj", null) match { + case m: scala.collection.Map[_, _] => + m.asInstanceOf[scala.collection.Map[String, Any]].keySet should contain("n") + case other => fail(s"obj answered $other") + } + } + + // ------------------------------------------------------------------------------------------- + // AC7 (R-177) -- a number Elasticsearch indexed, outside its column's type + // ------------------------------------------------------------------------------------------- + + /** `cell` is the number `expected` -- as stored, outside INT -- and `coerceToInt` fails naming it + * where it wrapped it (T0-2: 3000000000 read -1294967296). + */ + private def failsAsInt(cell: Any, expected: Double): Unit = + withClue(s"$cell (${Option(cell).map(_.getClass.getName).orNull}): ") { + cell match { + case n: Number => n.doubleValue() shouldBe expected + case other => fail(s"not a number: $other") + } + val error = the[java.sql.SQLException] thrownBy ValueCoercion.coerceToInt(cell) + error.getMessage should (startWith("Value ") and endWith(" is out of range for INT")) + } + + "A number outside its column's type that Elasticsearch indexed" should + "fail through the coercions naming it, never wrap (AC7, R-177)" in { + wideCreated shouldBe Right(()) + indexing.get("w1") shouldBe Some(Right(())) + // a column declared INT over a `long` field (T0-2 a) + failsAsInt(one(s"SELECT id, w FROM $wide WHERE id = 'w1'").getOrElse("w", null), 3e9) + // a computed INT past the int range (T0-2 b) + failsAsInt(one(s"SELECT id, p + q AS s FROM $wide WHERE id = 'w1'").getOrElse("s", null), 4e9) + // an object's sub-field, read as a dotted column: `_ignored` names it, but D8 reads a + // top-level field only (A-202) + indexing.get("obj_i") shouldBe Some(Right(())) + failsAsInt( + one(s"SELECT id, obj.i FROM $table WHERE id = 'obj_i'").getOrElse("obj.i", null), + 3e9 + ) + // a value within the range converts as it did + ValueCoercion.coerceToInt(one(s"SELECT id, i FROM $table WHERE id = 'i_v'")("i")) shouldBe 7 + } +}