Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions documentation/client/gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,13 @@ Each value is read by its column's declared type, where it is first read:
| GEO_POINT | `ListMap("lat" -> Double, "lon" -> Double)`, whatever spelling was indexed |
| ARRAY | `List` of its elements |

A value's text (the JDBC driver's `getString`, an Arrow `VARCHAR` cell) spells a list `[1, 2]` and a
map `{x: 1, y: 2}`, its entries in their own order, at every depth: `{x: 1, y: {z: 2}}`,
`[1, [2, 3]]`, `[{a: 1}, {a: 2}]`; a text unquoted, bytes as their base64, a NULL inside a list or
a map as `null` (a NULL cell stays a NULL).
*Since `0.25.0`*: a list or a map inside another read as its Scala class before (`{y: ListMap(z -> 2)}`),
and bytes inside one as an object hash; a value with no list, map or bytes inside is spelled as before.

#### Elasticsearch mapping types

*Since `0.25.0`* (they read `ANY` before, and `constant_keyword` answered NULL), the mapping types
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,78 @@ object ValueCoercion {

// ─── Coercions ───────────────────────────────────────────────────────────────

/** A value's text: JDBC's `getString`, arrow's VARCHAR writer.
*
* A list is `[e1, e2]`, a map `{k1: v1, k2: v2}` -- its entries in its own iteration order,
* never sorted --, a text unquoted, bytes their base64, a `null` element `null`; any other value
* its `toString`, a key its `String.valueOf`. SCHEMA-17 fix R-171: the rule holds at EVERY depth
* -- an element or an entry's value is spelled by this same rule -- so a nested object reads
* `{x: 1, y: {z: 2}}`, a list of lists `[1, [2, 3]]`, nested bytes their base64, where they read
* a Scala class (`{y: ListMap(z -> 2)}`, `List(2, 3)`) or an object hash (`[B@1b6d3586`). A
* value with no list, map or bytes inside is spelled as before, byte for byte.
*
* Cost: a flat value takes the arms it always took, in the same order (`null`, a text as itself,
* bytes, `toString`), and allocates nothing more. A list or a map is written into ONE builder
* per call, whatever its depth: no intermediate string per level or per entry (a non-text leaf's
* or key's own `toString`, nested bytes' base64, aside).
*
* The containers are Scala's (`Seq`, `Map`): the classes core hands a consumer (`List`,
* `ListMap`, `Vector`, the immutable maps). A Java collection is no core value and stays its
* `toString`.
*/
def coerceToString(value: Any): String = value match {
case null => null
case s: String => s
// SCHEMA-2 (D2) -- core reads a VARBINARY as its decoded bytes; its TEXT stays the base64
// Elasticsearch holds, as in 0.24.0 (JDBC `getString`, arrow's VARCHAR writer)
case b: Array[Byte] => java.util.Base64.getEncoder.encodeToString(b)
case seq: Seq[_] => seq.mkString("[", ", ", "]")
case map: Map[_, _] => map.map { case (k, v) => s"$k: $v" }.mkString("{", ", ", "}")
case other => other.toString
case seq: Seq[_] =>
val out = new java.lang.StringBuilder
appendSeq(out, seq)
out.toString
case map: Map[_, _] =>
val out = new java.lang.StringBuilder
appendMap(out, map)
out.toString
case other => other.toString
}

/** [[coerceToString]]'s text of a value nested in a list or a map, appended to `out` (R-171). */
private def appendText(out: java.lang.StringBuilder, value: Any): Unit = value match {
case null => out.append("null")
case s: String => out.append(s)
case b: Array[Byte] => out.append(java.util.Base64.getEncoder.encodeToString(b))
case seq: Seq[_] => appendSeq(out, seq)
case map: Map[_, _] => appendMap(out, map)
case other => out.append(other.toString)
}

/** `[e1, e2]`, each element by [[appendText]]. */
private def appendSeq(out: java.lang.StringBuilder, seq: Seq[_]): Unit = {
out.append('[')
val it = seq.iterator
if (it.hasNext) {
appendText(out, it.next())
while (it.hasNext) {
out.append(", ")
appendText(out, it.next())
}
}
out.append(']')
}

/** `{k1: v1, k2: v2}` in the map's own iteration order, each value by [[appendText]]. */
private def appendMap(out: java.lang.StringBuilder, map: Map[_, _]): Unit = {
out.append('{')
val it = map.iterator
var first = true
while (it.hasNext) {
val entry = it.next()
if (first) first = false else out.append(", ")
out.append(String.valueOf(entry._1)).append(": ")
appendText(out, entry._2)
}
out.append('}')
}

def coerceToInt(value: Any): java.lang.Integer = value match {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,25 @@ package app.softnetwork.elastic.sql.`type`
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import java.time.{Instant, LocalDate, ZoneOffset}
import java.nio.charset.StandardCharsets
import java.time.{
Instant,
LocalDate,
LocalDateTime,
LocalTime,
OffsetDateTime,
ZoneOffset,
ZonedDateTime
}
import scala.collection.immutable.{HashMap, ListMap}

/** softclient4es-arrow#168 — `coerceToDate` had no `Number` arm while `coerceToTimestamp` did, so
* an Elasticsearch `date` field stored as epoch millis threw `Cannot convert java.lang.Long to
* DATE` and took down every cross-index JOIN leg that projected it (and `ResultSet.getDate` with
* it).
*
* SCHEMA-17 fix R-171 — `coerceToString` (JDBC `getString`, arrow's VARCHAR writer) renders a
* nested list, map or bytes through itself, in today's style; a flat value renders as before.
*/
class ValueCoercionSpec extends AnyFlatSpec with Matchers {

Expand Down Expand Up @@ -76,4 +89,139 @@ class ValueCoercionSpec extends AnyFlatSpec with Matchers {
.atZone(ZoneOffset.UTC)
.toLocalDate shouldBe ExpectedDate
}

// ─── SCHEMA-17 fix R-171: coerceToString at every depth ──────────────────────────────────────

private val Hello: Array[Byte] = "hello".getBytes(StandardCharsets.UTF_8)

/** `coerceToString` as it was before R-171, verbatim: the oracle of every FLAT value (AC2). */
private def before(value: Any): String = value match {
case null => null
case s: String => s
case b: Array[Byte] => java.util.Base64.getEncoder.encodeToString(b)
case seq: Seq[_] => seq.mkString("[", ", ", "]")
case map: Map[_, _] => map.map { case (k, v) => s"$k: $v" }.mkString("{", ", ", "}")
case other => other.toString
}

"coerceToString" should "render a nested object, list or bytes through itself, in today's style (R-171 AC1)" in {
ValueCoercion.coerceToString(ListMap("x" -> 1, "y" -> ListMap("z" -> 2))) shouldBe
"{x: 1, y: {z: 2}}"
ValueCoercion.coerceToString(List(1, List(2, 3))) shouldBe "[1, [2, 3]]"
ValueCoercion.coerceToString(List(ListMap("a" -> 1), ListMap("a" -> 2))) shouldBe
"[{a: 1}, {a: 2}]"
ValueCoercion.coerceToString(ListMap("k" -> List(1, 2))) shouldBe "{k: [1, 2]}"
// nested bytes: their base64, as at top level (was `[B@<hash>`)
ValueCoercion.coerceToString(ListMap("b" -> Hello)) shouldBe "{b: aGVsbG8=}"
ValueCoercion.coerceToString(List(Hello, null)) shouldBe "[aGVsbG8=, null]"
// a nested null is `null`, a text unquoted
ValueCoercion.coerceToString(ListMap("n" -> null, "s" -> "a b")) shouldBe "{n: null, s: a b}"
ValueCoercion.coerceToString(List("x", ListMap("s" -> "y", "t" -> null))) shouldBe
"[x, {s: y, t: null}]"
}

it should "write a map's entries in its own iteration order at every depth, never sorted (R-171 AC1)" in {
ValueCoercion.coerceToString(ListMap("z" -> 1, "a" -> ListMap("y" -> 2, "b" -> 3))) shouldBe
"{z: 1, a: {y: 2, b: 3}}"
// a HashMap's order is its own, whatever it is: its entries as it iterates them
val hash = HashMap((1 to 8).map(i => s"k$i" -> List(i, ListMap("v" -> i))): _*)
ValueCoercion.coerceToString(hash) shouldBe
hash.iterator.map { case (k, l) => s"$k: [${l.head}, {v: ${l.head}}]" }.mkString("{", ", ", "}")
}

it should "render {map, list, bytes, null} nested in every container class at depth 1, 2 and 3 (R-171 AC1, AC3)" in {
// the leaves, each with the text AC1 gives it
val leaves: Seq[(String, Any, String)] = Seq(
("map", ListMap("a" -> 1, "b" -> "x"), "{a: 1, b: x}"),
("list", List(1, 2), "[1, 2]"),
("bytes", Hello, "aGVsbG8="),
("null", null, "null")
)
// the container classes core hands to a consumer (T0-1), each with the text it wraps its
// element in: a map with one entry or with two (`Map2` keeps its insertion order), a list
val wrappers: Seq[(String, Any => Any, String => String)] = Seq(
("ListMap", (v: Any) => ListMap("k" -> v), (t: String) => s"{k: $t}"),
("Map", (v: Any) => Map("k" -> v, "j" -> 0), (t: String) => s"{k: $t, j: 0}"),
("List", (v: Any) => List(v), (t: String) => s"[$t]"),
("Vector", (v: Any) => Vector(0, v), (t: String) => s"[0, $t]")
)
def paths(depth: Int): Seq[List[(String, Any => Any, String => String)]] =
if (depth == 0) Seq(Nil)
else for { w <- wrappers; rest <- paths(depth - 1) } yield w :: rest
val cases: Seq[(String, Any, String)] =
for {
depth <- 1 to 3
path <- paths(depth)
leaf <- leaves
} yield {
val (leafName, leafValue, leafText) = leaf
val value = path.foldRight(leafValue)((w, inner) => w._2(inner))
val text = path.foldRight(leafText)((w, inner) => w._3(inner))
(s"${path.map(_._1).mkString(" > ")} > $leafName", value, text)
}
cases.size shouldBe (4 + 16 + 64) * 4
val wrong = cases.flatMap { case (name, value, text) =>
val rendered = ValueCoercion.coerceToString(value)
if (rendered == text) None else Some(s"$name: <$rendered> instead of <$text>")
}
wrong shouldBe empty
}

it should "render every flat value byte-identically to before (R-171 AC2)" in {
val day = LocalDate.of(2024, 1, 31)
val flat: Seq[Any] = Seq(
"hello",
"",
Int.box(42),
Long.box(42L),
Double.box(1.5),
Float.box(2.5f),
Short.box(7.toShort),
Byte.box(8.toByte),
new java.math.BigDecimal("1.50"),
new java.math.BigInteger("18446744073709551615"),
BigDecimal("2.50"),
Boolean.box(true),
Boolean.box(false),
day,
LocalTime.of(10, 30),
LocalTime.of(10, 30, 15, 123000000),
LocalDateTime.of(2024, 1, 31, 10, 30),
ZonedDateTime.of(2024, 1, 31, 10, 30, 0, 0, ZoneOffset.UTC),
ZonedDateTime.of(2024, 1, 31, 10, 30, 0, 123456789, ZoneOffset.UTC),
OffsetDateTime.of(2024, 1, 31, 10, 30, 0, 0, ZoneOffset.ofHours(1)),
Instant.parse("2024-01-31T10:30:00Z"),
java.sql.Date.valueOf("2024-01-31"),
java.sql.Timestamp.valueOf("2024-01-31 10:30:00"),
Hello,
List(1, "a", null, 2.5, true, day),
Vector(3L, "b"),
List(),
ListMap("a" -> 1, "b" -> "x", "c" -> null, "d" -> day),
Map("only" -> 1.5),
HashMap((1 to 8).map(i => s"k$i" -> i): _*),
Map.empty[String, Any],
ListMap("lat" -> 1.5, "lon" -> 2.5),
// a top hit's `bucket_root` is an Option inside a map: its `toString`, as before
ListMap("v" -> 1, "bucket_root" -> Some("root"))
)
flat.foreach { value =>
withClue(s"$value (${value.getClass.getName}): ") {
ValueCoercion.coerceToString(value) shouldBe before(value)
}
}
// the literal pins: top-level bytes (ResultSchemaSpec), a flat list, a flat map, null
ValueCoercion.coerceToString(Hello) shouldBe "aGVsbG8="
ValueCoercion.coerceToString(List(1, "a", null, 2.5)) shouldBe "[1, a, null, 2.5]"
ValueCoercion.coerceToString(ListMap("a" -> 1, "b" -> "x", "c" -> null)) shouldBe
"{a: 1, b: x, c: null}"
ValueCoercion.coerceToString(List()) shouldBe "[]"
ValueCoercion.coerceToString(Map.empty[String, Any]) shouldBe "{}"
ValueCoercion.coerceToString(null) shouldBe null
}

it should "hand a text back as the same instance, its fast arm (R-171 AC5)" in {
val text = new String("abc")
ValueCoercion.coerceToString(text) should be theSameInstanceAs text
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import app.softnetwork.elastic.client.result.{
}
import app.softnetwork.elastic.client.spi.ElasticClientFactory
import app.softnetwork.elastic.scalatest.ElasticDockerTestKit
import app.softnetwork.elastic.sql.`type`.SQLTypes
import app.softnetwork.elastic.sql.`type`.{SQLTypes, ValueCoercion}
import app.softnetwork.elastic.sql.query.SelectStatement
import app.softnetwork.persistence.generateUUID
import org.apache.http.entity.ContentType
Expand All @@ -55,6 +55,10 @@ import scala.util.Try
* reload (AC6, Elasticsearch 7+);
* - "describe": `describe(sql)` = `run(sql)`'s schema (AC1).
*
* SCHEMA-17 fix R-171 -- "an object read as stored": the text of an object column core reads as
* stored (a disabled `object`, a field-less STRUCT) whose documents hold a nested object, a list
* of objects and a list of lists, on fixture `r171_t` (AC4).
*
* SCHEMA-2b -- aggregation values and window statements by type, on fixtures `s2b_t` / `s2b_w`:
*
* - "aggregation rows": Table A (AC3);
Expand All @@ -80,6 +84,7 @@ trait SchemaReadingSpec extends AnyFlatSpecLike with ElasticDockerTestKit with M
protected val table = "s2_t"
protected val q4 = "q4_t"
protected val q4d = "q4d_t"
protected val asStored = "r171_t"

protected lazy val major: Int = Try(elasticVersion.takeWhile(_ != '.').toInt).getOrElse(8)

Expand Down Expand Up @@ -186,15 +191,15 @@ trait SchemaReadingSpec extends AnyFlatSpecLike with ElasticDockerTestKit with M

override def beforeAll(): Unit = {
super.beforeAll()
Seq(table, q4, q4d, aggTable, windowTable).foreach(drop)
Seq(table, q4, q4d, asStored, aggTable, windowTable).foreach(drop)
load(table, mapping, docs)
load(aggTable, aggMapping, aggDocs)
load(windowTable, windowMapping, windowDocs)
()
}

override def afterAll(): Unit = {
Seq(table, q4, q4d, aggTable, windowTable).foreach(drop)
Seq(table, q4, q4d, asStored, aggTable, windowTable).foreach(drop)
super.afterAll()
}

Expand Down Expand Up @@ -432,6 +437,58 @@ trait SchemaReadingSpec extends AnyFlatSpecLike with ElasticDockerTestKit with M
answer(runOk(s"SELECT * FROM $q4d"))._2.map(_.names.toSet) shouldBe Some(Set("id", "nf"))
}

// -------------------------------------------------------------------------------------------
// SCHEMA-17 fix R-171 -- an object read as stored, as its text (AC4)
// -------------------------------------------------------------------------------------------

"An object read as stored" should "spell its nested values recursively as text (R-171 AC4)" in {
// a disabled object: no field of its own (a field-less STRUCT, read as stored), any JSON kept
load(
asStored,
"""{"properties": {"id": {"type": "keyword"},
| "o": {"type": "object", "enabled": false}}}""".stripMargin,
Seq(
"n1" -> """{"id":"n1","o":{"x":1,"y":{"z":2}}}""",
"n2" -> """{"id":"n2","o":[{"a":1},{"a":2}]}""",
"n3" -> """{"id":"n3","o":[1,[2,3]]}""",
"n4" -> """{"id":"n4","o":{"k":[1,2],"n":null,"s":"text"}}""",
"n5" -> """{"id":"n5","o":{"l":[[{"d":[true,false]}]]}}"""
)
)
// JDBC's `getString` and arrow's VARCHAR writer: `ValueCoercion.coerceToString`
val expected = Map(
"n1" -> "{x: 1, y: {z: 2}}",
"n2" -> "[{a: 1}, {a: 2}]",
"n3" -> "[1, [2, 3]]",
"n5" -> "{l: [[{d: [true, false]}]]}"
)
// n4's entries come in the map's own iteration order: the Elasticsearch 6 / 7 clients read
// `_source` without the document's key order, 8 / 9 keep it; the text follows the map it gets
val n4Entries = Map("k" -> "[1, 2]", "n" -> "null", "s" -> "text")
Seq("", " LIMIT 100").foreach { limit =>
val sql = s"SELECT id, o FROM $asStored$limit"
withClue(s"[$sql] ") {
val rows = rowsOf(sql)
val texts = rows.map { row =>
String.valueOf(row.getOrElse("id", null)) ->
ValueCoercion.coerceToString(row.getOrElse("o", null))
}.toMap
(texts - "n4") shouldBe expected
rows
.find(row => String.valueOf(row.getOrElse("id", null)) == "n4")
.flatMap(_.get("o")) match {
case Some(map: Map[_, _]) =>
val keys = map.keys.map(_.toString).toList
keys.toSet shouldBe n4Entries.keySet
texts.get("n4") shouldBe Some(
keys.map(k => s"$k: ${n4Entries(k)}").mkString("{", ", ", "}")
)
case other => fail(s"n4's object is not read as a map: $other")
}
}
}
}

// -------------------------------------------------------------------------------------------
// describe (AC1)
// -------------------------------------------------------------------------------------------
Expand Down
Loading