diff --git a/core/src/main/scala/app/softnetwork/elastic/client/SetOperationValues.scala b/core/src/main/scala/app/softnetwork/elastic/client/SetOperationValues.scala index 480207b1..ae50c609 100644 --- a/core/src/main/scala/app/softnetwork/elastic/client/SetOperationValues.scala +++ b/core/src/main/scala/app/softnetwork/elastic/client/SetOperationValues.scala @@ -284,10 +284,11 @@ private[elastic] object SetOperationValues { * * @param sqlType * the type the leg's values have there, at every depth: the branch's declared type, a date - * position whose format core cannot read for sure `VARCHAR` ([[DateRoute.AsStored]]) + * position whose format core cannot read for sure `VARCHAR` ([[DateRoute.AsStored]]); at a + * `NULL` literal, the column's type ([[MultiSearch.columnTypes]]' result) * @param read * the reader of one raw value there, answering `sqlType`'s class ([[legReaders]]' classes; - * `VARCHAR` a `String`, the text as stored) + * `VARCHAR` a `String`, the text as stored); at a `NULL` literal, `null` for every value * @param asStored * the date positions answered as stored -- their path (`tsz`, `oz.z`) and why */ @@ -324,12 +325,16 @@ private[elastic] object SetOperationValues { * known, `VARCHAR`, the text as stored, every row -- at the column, in a struct's field and * in a list's element, where the branches agree or not. The routed type is read by the SAME * reader as every other position ([[legReader]]): a `VARCHAR` position is the text leg's. + * - A `NULL` literal declares no type of its own: its slot is the column's type, the type the + * relational engine gives it ([[MultiSearch.columnTypes]]' result, which carries no date + * format, so no version is asked for it), every value read as NULL -- `None` where that type + * is `NULL` (every branch a `NULL`), holds a type not known at some depth + * ([[unknownInside]]) or one of unknown width (`NUMERIC`, `TEMPORAL`) ([[nullSlot]]). * - `None` where [[legReader]] reads nothing (a column whose type is not known, `ANY` -- a - * `WITH` or a derived table aliasing the column --, a `NULL` literal); where the leg's OR - * the column's type holds, at any depth, a type not known (`ANY`, a `STRUCT` whose fields - * are not known) ([[unknownInside]]); and where the leg's type holds, at any depth, one read - * as it comes until the engine types it (`NUMERIC`, `TEMPORAL`, `VARBINARY`, `REAL`) - * ([[valueTyped]]). + * `WITH` or a derived table aliasing the column); where the leg's OR the column's type + * holds, at any depth, a type not known (`ANY`, a `STRUCT` whose fields are not known) + * ([[unknownInside]]); and where the leg's type holds, at any depth, one read as it comes + * until the engine types it (`NUMERIC`, `TEMPORAL`, `VARBINARY`, `REAL`) ([[valueTyped]]). * * Built ONCE per statement; no decision is made per row. */ @@ -368,7 +373,8 @@ private[elastic] object SetOperationValues { /** Leg `index`'s slot at ONE column ([[legSchemas]]): its branch's type routed ([[routed]]), read * by [[legReader]] over the column whose branch `index` is the routed type -- `None` where * [[legReader]] reads nothing, where the branch's type is read as it comes ([[valueTyped]]), or - * where the column's type is not known at some depth ([[unknownInside]]). + * where the column's type is not known at some depth ([[unknownInside]]). A `NULL` literal's + * slot is the column's type, read as NULL ([[nullSlot]]). */ private[client] def legSlot( column: SetOperationColumn, @@ -378,34 +384,60 @@ private[elastic] object SetOperationValues { dates: DateReading, nanos: Set[String] = Set.empty ): Option[LegSlot] = - column.branches - .lift(index) - .flatten - .filterNot(branch => valueTyped(branch) || unknownInside(column.result)) - .flatMap { branch => - // whether the slot exists is [[legReader]]'s to say over the column AS DECLARED, before any - // date is routed (routing asks the version): routing makes a date `VARCHAR`, never `NULL`, - // and leaves the column's type alone, so [[legReader]] answers the same over the routed one - val reader = legReader(column, index, name, field, dates, Unreadable.Fail, nanos) - Option(reader).flatMap { declared => - val (slotType, asStored) = routed(branch, if (field.isEmpty) name else field, dates) - // routing changed nothing (every readable date): the routed column IS the declared one, - // so its reader is the one just built -- built once, not twice per slot - if (slotType == branch) Some(LegSlot(slotType, declared, asStored)) - else - Option( - legReader( - column.copy(branches = column.branches.updated(index, Some(slotType))), - index, - name, - field, - dates, - Unreadable.Fail, - nanos - ) - ).map(LegSlot(slotType, _, asStored)) - } + column.branches.lift(index).flatten match { + // SCHEMA-18 (R-199) -- a NULL literal declares no type of its own + case Some(branch) if branch.sqlType == SQLTypes.Null => nullSlot(column) + case declared => + declared + .filterNot(branch => valueTyped(branch) || unknownInside(column.result)) + .flatMap { branch => + // whether the slot exists is [[legReader]]'s to say over the column AS DECLARED, before + // any date is routed (routing asks the version): routing makes a date `VARCHAR`, never + // `NULL`, and leaves the column's type alone, so [[legReader]] answers the same over the + // routed one + val reader = legReader(column, index, name, field, dates, Unreadable.Fail, nanos) + Option(reader).flatMap { declared => + val (slotType, asStored) = routed(branch, if (field.isEmpty) name else field, dates) + // routing changed nothing (every readable date): the routed column IS the declared + // one, so its reader is the one just built -- built once, not twice per slot + if (slotType == branch) Some(LegSlot(slotType, declared, asStored)) + else + Option( + legReader( + column.copy(branches = column.branches.updated(index, Some(slotType))), + index, + name, + field, + dates, + Unreadable.Fail, + nanos + ) + ).map(LegSlot(slotType, _, asStored)) + } + } + } + + /** SCHEMA-18 (R-199) -- a `NULL` literal's slot: its column's set-operation type + * ([[MultiSearch.columnTypes]]' result -- the type the relational engine gives the column, which + * a `NULL` takes there), read as NULL every row; `None` where that type is `NULL` (every branch + * a `NULL`), not known at some depth ([[unknownInside]]), or of unknown width (`NUMERIC`, + * `TEMPORAL`). The result carries no date format at any depth: nothing is routed, no version is + * asked. + */ + private def nullSlot(column: SetOperationColumn): Option[LegSlot] = + if ( + column.resultType == SQLTypes.Null || unknownInside(column.result) || + holds(column.result) { + case SQLTypes.Numeric | SQLTypes.Temporal => true + case _ => false } + ) None + else Some(LegSlot(column.result, readsNull, Nil)) + + /** The reader of a `NULL` literal's values: NULL, whatever Elasticsearch answers (`null`, its + * one-element `[null]`). ONE function, so two slots of the same column are equal. + */ + private val readsNull: Any => Any = _ => null /** A branch's type with every date position [[DateRoute.of]] answers as stored made `VARCHAR`, at * every depth -- a struct's field (`path.field`), a list's element (the list's path) -- and diff --git a/core/src/test/scala/app/softnetwork/elastic/arrow/LegSchemasConsumerSmokeSpec.scala b/core/src/test/scala/app/softnetwork/elastic/arrow/LegSchemasConsumerSmokeSpec.scala index df8176a5..5a170b9b 100644 --- a/core/src/test/scala/app/softnetwork/elastic/arrow/LegSchemasConsumerSmokeSpec.scala +++ b/core/src/test/scala/app/softnetwork/elastic/arrow/LegSchemasConsumerSmokeSpec.scala @@ -81,4 +81,14 @@ class LegSchemasConsumerSmokeSpec extends AnyFlatSpec with Matchers { tsz.asStored.map((p: LegSlot.AsStored) => p.path) shouldBe Seq("tsz") tsz.read("2024-01-31 10:30 CET") shouldBe "2024-01-31 10:30 CET" } + + they should "type a NULL literal as its column, read as NULL (SCHEMA-18)" in { + val sql = "SELECT NULL AS k FROM t UNION SELECT n AS k FROM t" + slotTypes(sql) shouldBe Seq(Seq(Some("INT")), Seq(Some("INT"))) + val nullSlot: LegSlot = legs(sql).head.flatMap(_.slots.head).getOrElse(fail("no NULL slot")) + Seq[Any](null, List(null), 3, "3").foreach { cell => + assert(nullSlot.read(cell) == null, s"$cell read") + } + nullSlot.asStored shouldBe Nil + } } diff --git a/core/src/test/scala/app/softnetwork/elastic/client/SetOperationLegSchemasSpec.scala b/core/src/test/scala/app/softnetwork/elastic/client/SetOperationLegSchemasSpec.scala index 0493bef3..1d111061 100644 --- a/core/src/test/scala/app/softnetwork/elastic/client/SetOperationLegSchemasSpec.scala +++ b/core/src/test/scala/app/softnetwork/elastic/client/SetOperationLegSchemasSpec.scala @@ -444,7 +444,7 @@ class SetOperationLegSchemasSpec extends AnyFlatSpec with Matchers { "A position typed as its values come" should "have no slot where legReaders reads nothing" in { // a column whose type is not known: a WITH aliasing inside its CTE, every derived table, in - // every leg; a column of type ANY; a NULL literal + // every leg; a column of type ANY val anyColumns = Seq( "WITH a AS (SELECT tsz AS k FROM t) SELECT k FROM a UNION SELECT ts AS k FROM t", "SELECT k FROM (SELECT tsz AS k FROM t) dd UNION SELECT ts AS k FROM t", @@ -459,8 +459,16 @@ class SetOperationLegSchemasSpec extends AnyFlatSpec with Matchers { slots(sql) shouldBe Seq(Some(Seq(None)), Some(Seq(None))) Seq(0, 1).foreach(leg => legReader(sql, leg) shouldBe null) } + // SCHEMA-18 (R-199) -- legReaders reads nothing at a NULL literal, but its slot is its + // column's type, every value read as NULL slots(union("n", "NULL")).map(_.map(_.map(_.map(_.sqlType)))) shouldBe - Seq(Some(Seq(Some(SetOperationType(SQLTypes.Int)))), Some(Seq(None))) + Seq( + Some(Seq(Some(SetOperationType(SQLTypes.Int)))), + Some(Seq(Some(SetOperationType(SQLTypes.Int)))) + ) + Seq("null", "[null]", "3").foreach { json => + assert(slot(union("n", "NULL"), leg = 1).read(received(json)) == null, s"$json read") + } legReader(union("n", "NULL"), 1) shouldBe null // a SELECT * leg: no schema, whatever the width of the others slots("SELECT n FROM t UNION ALL SELECT * FROM t").map(_.isDefined) shouldBe Seq(true, false) diff --git a/core/src/test/scala/app/softnetwork/elastic/client/SetOperationNullSlotSpec.scala b/core/src/test/scala/app/softnetwork/elastic/client/SetOperationNullSlotSpec.scala new file mode 100644 index 00000000..1194d2d5 --- /dev/null +++ b/core/src/test/scala/app/softnetwork/elastic/client/SetOperationNullSlotSpec.scala @@ -0,0 +1,454 @@ +/* + * 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.{LegSchema, LegSlot} +import app.softnetwork.elastic.sql.{StringValue, Value} +import app.softnetwork.elastic.sql.parser.Parser +import app.softnetwork.elastic.sql.query.{MultiSearch, SingleSearch} +import app.softnetwork.elastic.sql.query.MultiSearch.{ + SetOperationColumn, + SetOperationType, + StructField +} +import app.softnetwork.elastic.sql.operator.SetOperator +import app.softnetwork.elastic.sql.schema.{Column, Table} +import app.softnetwork.elastic.sql.serialization.JacksonConfig +import app.softnetwork.elastic.sql.`type`.SQLTypes +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +import scala.collection.immutable.ListMap + +/** A `NULL` literal in a set-operation branch declares its column's type for that leg + * ([[SetOperationValues.legSchemas]]): the column's type as the relational engine (DuckDB 1.5.5) + * types it -- [[MultiSearch.columnTypes]] ' result, THE function core's `describe` reads -- read + * as NULL every row. No slot where that type is NULL (every branch a NULL), not known at some + * depth, or of unknown width (`NUMERIC`, `TEMPORAL`). Every other leg keeps its slot. + */ +class SetOperationNullSlotSpec extends AnyFlatSpec with Matchers { + + private def format(f: String): ListMap[String, Value[_]] = + ListMap[String, Value[_]]("format" -> StringValue(f)) + + private val zoneName = "yyyy-MM-dd HH:mm z" + + private val t = Table( + "t", + columns = List( + Column("n", SQLTypes.Int), + Column("l", SQLTypes.BigInt), + Column("x", SQLTypes.Double), + Column("f", SQLTypes.Real), + Column("b", SQLTypes.Boolean), + Column("s", SQLTypes.Keyword), + Column("d", SQLTypes.Date), + Column("ts", SQLTypes.Timestamp), + Column("c_es", SQLTypes.Timestamp, options = format("epoch_second")), + Column("tsz", SQLTypes.Timestamp, options = format(zoneName)), + Column("bin", SQLTypes.VarBinary), + Column( + "o", + SQLTypes.Struct, + multiFields = List( + Column("a", SQLTypes.Int), + Column("e", SQLTypes.Timestamp, options = format("epoch_second")) + ) + ), + Column("o2", SQLTypes.Struct, multiFields = List(Column("b", SQLTypes.Keyword))), + Column( + "oz", + SQLTypes.Struct, + multiFields = List(Column("z", SQLTypes.Timestamp, options = format(zoneName))) + ), + Column("g", SQLTypes.GeoPoint), + Column("ai", SQLTypes.Array(SQLTypes.Int)), + Column("ao", SQLTypes.Array(SQLTypes.Struct), multiFields = List(Column("a", SQLTypes.Int))), + Column("fl", SQLTypes.Struct), + Column("om", SQLTypes.Struct, multiFields = List(Column("meta", SQLTypes.Any))), + Column("meta", SQLTypes.Any) + ) + ) + + /** A one-column index, for a `SELECT *` branch. */ + private val t1 = Table("t1", columns = List(Column("n", SQLTypes.Int))) + + private val es8 = Some("8.18.3") + + private def resolved(sql: String): (Seq[SingleSearch], Seq[SetOperator]) = + Parser(sql) match { + case Right(m: MultiSearch) => + ( + m.requests.map(r => r.update(Some(if (r.sources.contains("t1")) t1 else t))), + m.resolvedOperators + ) + case other => fail(s"[$sql] expected a set operation, got $other") + } + + private def columns(sql: String): Seq[SetOperationColumn] = { + val (requests, operators) = resolved(sql) + MultiSearch.columnTypes(requests, operators).fold(e => fail(s"[$sql] refused: $e"), identity) + } + + private def schemas(sql: String, version: => Option[String] = es8): Seq[Option[LegSchema]] = { + val (requests, operators) = resolved(sql) + SetOperationValues.legSchemas(requests, operators, version) match { + case Right(legs) => legs + case Left(refusal) => fail(s"[$sql] refused: $refusal") + } + } + + private def slots(sql: String): Seq[Option[Seq[Option[LegSlot]]]] = + schemas(sql).map(_.map(_.slots)) + + private def slotAt(sql: String, leg: Int, position: Int = 0): Option[LegSlot] = + schemas(sql)(leg).flatMap(_.slots(position)) + + /** A document's value as core receives it: its JSON, read by the response parser. */ + private def received(json: String): Any = + ElasticConversion.jsonNodeToAny(JacksonConfig.objectMapper.readTree(json), ListMap.empty) + + /** A type as DuckDB names it: `INT`, `STRUCT(a INT, e TIMESTAMP)`, `INT[]`, `GEO_POINT`. */ + private def render(t: SetOperationType): String = + t.sqlType match { + case SQLTypes.Struct => + t.fields.map(f => s"${f.name} ${render(f.valueType)}").mkString("STRUCT(", ", ", ")") + case SQLTypes.Array(elementType) => + t.element.map(render).getOrElse(elementType.typeId) + "[]" + case scalar => scalar.typeId + } + + // --------------------------------------------------------------------------------------------- + // The population (spec ยง4): every cell, NULL first or second, each operator + // --------------------------------------------------------------------------------------------- + + /** One statement: its SQL, the leg holding the NULL literal, its position, the expected type. */ + private final case class Cell( + group: String, + sql: String, + leg: Int, + position: Int, + expected: String + ) + + private val operators = Seq("UNION ALL", "UNION", "INTERSECT", "EXCEPT") + + private def branch(item: String): String = s"SELECT $item AS k FROM t" + + /** Each order of `items` (as listed, and with the NULL one place over) under each operator. */ + private def uniform(group: String, items: Seq[String], expected: String): Seq[Cell] = { + val i = items.indexOf("NULL") + val j = if (i == 0) 1 else i - 1 + val swapped = items.updated(i, items(j)).updated(j, "NULL") + for { + order <- Seq(items, swapped) + operator <- operators + } yield Cell( + group, + order.map(branch).mkString(s" $operator "), + order.indexOf("NULL"), + 0, + expected + ) + } + + /** `items` under the operators given, as listed and with the NULL one place over. */ + private def fixed( + group: String, + items: Seq[String], + ops: Seq[String], + expected: String + ): Seq[Cell] = { + val i = items.indexOf("NULL") + val j = if (i == 0) 1 else i - 1 + val swapped = items.updated(i, items(j)).updated(j, "NULL") + Seq(items, swapped).map { order => + val sql = order.map(branch).head + order.tail + .map(branch) + .zip(ops) + .map { case (b, op) => s" $op $b" } + .mkString + Cell(group, sql, order.indexOf("NULL"), 0, expected) + } + } + + private val g1: Seq[Cell] = Seq( + "n" -> "INT", + "l" -> "BIGINT", + "x" -> "DOUBLE", + "f" -> "REAL", + "b" -> "BOOLEAN", + "s" -> "VARCHAR", + "d" -> "DATE", + "ts" -> "TIMESTAMP", + "c_es" -> "TIMESTAMP", + "bin" -> "VARBINARY", + "o.a" -> "INT", + "o.e" -> "TIMESTAMP" + ).flatMap { case (sibling, expected) => uniform("G1", Seq("NULL", sibling), expected) } + + private val g2: Seq[Cell] = Seq( + "tsz" -> "TIMESTAMP", + "oz" -> "STRUCT(z TIMESTAMP)", + "oz.z" -> "TIMESTAMP" + ).flatMap { case (sibling, expected) => uniform("G2", Seq("NULL", sibling), expected) } + + private val g3: Seq[Cell] = Seq( + Seq("NULL", "o") -> "STRUCT(a INT, e TIMESTAMP)", + Seq("NULL", "g") -> "GEO_POINT", + Seq("NULL", "ai") -> "INT[]", + Seq("NULL", "ao") -> "STRUCT(a INT)[]", + Seq("NULL", "o", "o2") -> "STRUCT(a INT, e TIMESTAMP, b VARCHAR)", + Seq("NULL", "g", "o") -> "STRUCT(lat DOUBLE, lon DOUBLE, a INT, e TIMESTAMP)" + ).flatMap { case (items, expected) => uniform("G3", items, expected) } + + private val g4: Seq[Cell] = + uniform("G4", Seq("NULL", "n", "x"), "DOUBLE") ++ + uniform("G4", Seq("bin", "NULL", "s"), "VARBINARY") ++ + uniform("G4", Seq("bin", "NULL", "n"), "VARCHAR") ++ + fixed("G4", Seq("NULL", "d", "ts"), Seq("INTERSECT", "UNION"), "TIMESTAMP") ++ + fixed( + "G4", + Seq("NULL", "o", "o2"), + Seq("INTERSECT", "UNION ALL"), + "STRUCT(a INT, e TIMESTAMP, b VARCHAR)" + ) ++ + fixed("G4", Seq("NULL", "n", "s"), Seq("UNION", "EXCEPT"), "VARCHAR") + + private val aggregationNull = "SELECT NULL AS k, COUNT(*) AS c FROM t" + private val aggregationN = "SELECT n AS k, COUNT(*) AS c FROM t GROUP BY n" + + private val g5: Seq[Cell] = operators.flatMap { operator => + Seq( + Cell("G5", s"$aggregationNull $operator $aggregationN", 0, 0, "INT"), + Cell("G5", s"$aggregationN $operator $aggregationNull", 1, 0, "INT"), + Cell("G5", s"SELECT NULL FROM t $operator SELECT n FROM t", 0, 0, "INT"), + Cell("G5", s"SELECT n FROM t $operator SELECT NULL FROM t", 1, 0, "INT") + ) + } + + private val population: Seq[Cell] = g1 ++ g2 ++ g3 ++ g4 ++ g5 + + /** The NULL leg's slot of a population cell, or a failure naming the cell. */ + private def nullSlotOf(cell: Cell): LegSlot = + slotAt(cell.sql, cell.leg, cell.position).getOrElse(fail(s"[${cell.sql}] no NULL slot")) + + "A NULL literal's slot" should "be its column's DuckDB type, every population cell, NULL first or second, each operator" in { + val wrong = population.flatMap { cell => + val result = columns(cell.sql)(cell.position).result + slotAt(cell.sql, cell.leg, cell.position) match { + case Some(slot) + if render(slot.sqlType) == cell.expected && slot.sqlType == result && + slot.asStored.isEmpty => + None + case other => + Some( + s"[${cell.sql}] ${cell.group} expected ${cell.expected} (= columnTypes ${render(result)}), " + + s"got ${other.map(s => s"${render(s.sqlType)} ${s.asStored}")}" + ) + } + } + wrong shouldBe empty + // the population: G1 12 x 8, G2 3 x 8, G3 6 x 8, G4 3 x 8 + 3 x 2, G5 4 x 4 + population.size shouldBe 214 + } + + it should "read every value as NULL, with nothing as stored" in { + val values = Seq( + "null", + "[null]", + "3", + "10000000000", + "1.5", + "true", + "\"a\"", + "\"2024-01-31\"", + "\"2024-01-31T10:30:00Z\"", + "1706697000", + "\"2024-01-31 10:30 CET\"", + "\"aGk=\"", + """{"a":1,"e":1706697000}""", + """{"e":1706697000}""", + """{"b":"x"}""", + """{"z":"2024-01-31 10:30 CET"}""", + """{"lat":1.0,"lon":2.0}""", + "[1,2]", + """[{"a":1},{"a":2}]""", + """["a","b"]""" + ).map(received) + val wrong = population.flatMap { cell => + val slot = nullSlotOf(cell) + val read = (null +: values).map(v => scala.util.Try(slot.read(v))) + if (read.forall(r => r.isSuccess && r.get == null) && slot.asStored.isEmpty) None + else Some(s"[${cell.sql}] read ${read.filterNot(r => r.isSuccess && r.get == null)}") + } + wrong shouldBe empty + } + + it should "type a routed date's NULL as the column declares it, the routed sibling as stored (D4)" in { + Seq( + ("tsz", "TIMESTAMP", "VARCHAR"), + ("oz", "STRUCT(z TIMESTAMP)", "STRUCT(z VARCHAR)"), + ("oz.z", "TIMESTAMP", "VARCHAR") + ).foreach { case (sibling, nullType, siblingType) => + val sql = s"SELECT NULL AS k FROM t UNION SELECT $sibling AS k FROM t" + withClue(s"[$sql] ") { + slotAt(sql, 0).map(s => render(s.sqlType)) shouldBe Some(nullType) + val routed = slotAt(sql, 1).getOrElse(fail("no sibling slot")) + render(routed.sqlType) shouldBe siblingType + routed.asStored should not be empty + } + } + } + + it should "have no slot where the column is NULL, not known inside, or of unknown width (D3)" in { + // every branch a NULL: the column's type is NULL + operators.foreach { operator => + val sql = s"SELECT NULL AS k FROM t $operator SELECT NULL AS k FROM t" + columns(sql).map(_.resultType) shouldBe Seq(SQLTypes.Null) + slots(sql) shouldBe Seq(Some(Seq(None)), Some(Seq(None))) + } + // a field-less STRUCT, a STRUCT holding ANY, ANY: no leg has a slot, as for every leg today + for { + sibling <- Seq("fl", "om", "meta") + operator <- operators + sql <- Seq( + s"SELECT NULL AS k FROM t $operator SELECT $sibling AS k FROM t", + s"SELECT $sibling AS k FROM t $operator SELECT NULL AS k FROM t" + ) + } withClue(s"[$sql] ")(slots(sql) shouldBe Seq(Some(Seq(None)), Some(Seq(None)))) + // a column of unknown width, constructed (no SQL form yields one since A-175), at the column + // and in a struct's field; REAL and VARBINARY are of known width and DO get one + val dates = SetOperationValues.DateReading(es8) + val nul = Some(SetOperationType(SQLTypes.Null)) + def column(result: SetOperationType): SetOperationColumn = + SetOperationColumn(result, Seq(nul, Some(result))) + Seq( + SetOperationType(SQLTypes.Numeric), + SetOperationType(SQLTypes.Temporal), + SetOperationType(SQLTypes.Struct, fields = Seq(StructField("t", SQLTypes.Temporal))), + SetOperationType( + SQLTypes.Array(SQLTypes.Numeric), + element = Some(SetOperationType(SQLTypes.Numeric)) + ) + ).foreach { result => + withClue(s"[$result] ")( + SetOperationValues.legSlot(column(result), 0, "k", "", dates) shouldBe None + ) + } + } + + it should "give a REAL or a VARBINARY column a slot: their width is known (D3)" in { + val dates = SetOperationValues.DateReading(es8) + Seq(SetOperationType(SQLTypes.Real), SetOperationType(SQLTypes.VarBinary)).foreach { result => + val column = + SetOperationColumn(result, Seq(Some(SetOperationType(SQLTypes.Null)), Some(result))) + SetOperationValues.legSlot(column, 0, "k", "", dates).map(_.sqlType) shouldBe Some(result) + // the sibling of that type is read as it comes, as before (valueTyped): no slot + SetOperationValues.legSlot(column, 1, "k", "f", dates) shouldBe None + } + } + + it should "ask the version as main does, never for the NULL leg itself (P3)" in { + def hasDate(t: SetOperationType): Boolean = + t.sqlType match { + case SQLTypes.Struct => t.fields.exists(f => hasDate(f.valueType)) + case SQLTypes.Array(_) => t.element.exists(hasDate) + case SQLTypes.Date | SQLTypes.Timestamp | SQLTypes.Time | SQLTypes.DateTime => true + case _ => false + } + val wrong = population.flatMap { cell => + var asked = 0 + def version: Option[String] = { asked += 1; es8 } + schemas(cell.sql, version) + // main's count: the non-NULL legs' slots alone, over one statement's date reading + var mainAsked = 0 + def mainVersion: Option[String] = { mainAsked += 1; es8 } + val (requests, ops) = resolved(cell.sql) + val cs = MultiSearch.columnTypes(requests, ops).fold(e => fail(e), identity) + val mainDates = SetOperationValues.DateReading(mainVersion) + for { + leg <- requests.indices if leg != cell.leg + position <- cs.indices + } { + val item = requests(leg).select.fieldsWithComputedAliases(position) + val field = Option(item.identifier.name).filter(_.nonEmpty).getOrElse(item.outputName) + SetOperationValues.legSlot(cs(position), leg, item.outputName, field, mainDates) + } + // the NULL slot alone asks nothing + var nullAsked = 0 + def nullVersion: Option[String] = { nullAsked += 1; es8 } + SetOperationValues.legSlot( + cs(cell.position), + cell.leg, + "k", + "", + SetOperationValues.DateReading(nullVersion) + ) + val dateFree = !hasDate(cs(cell.position).result) + if (asked == mainAsked && asked <= 1 && nullAsked == 0 && (!dateFree || asked == 0)) None + else + Some( + s"[${cell.sql}] asked $asked, main $mainAsked, NULL slot $nullAsked, date-free $dateFree" + ) + } + wrong shouldBe empty + } + + it should "keep two equal slots equal (one shared reader)" in { + population.foreach { cell => + withClue(s"[${cell.sql}] ")(nullSlotOf(cell) shouldBe nullSlotOf(cell)) + } + } + + it should "mark a row-query NULL item a script field, not an aggregation's" in { + Seq( + "SELECT NULL AS k FROM t UNION SELECT n AS k FROM t", + "SELECT NULL FROM t UNION SELECT n FROM t" + ).foreach { sql => + val (requests, _) = resolved(sql) + val item = requests.head.select.fieldsWithComputedAliases.head + withClue(s"[$sql] ")(requests.head.scriptFields should contain(item)) + } + val (aggregation, _) = resolved(s"$aggregationNull UNION $aggregationN") + aggregation.head.scriptFields shouldBe empty + } + + it should "leave CAST(NULL AS ...) on its own path, typed as cast (G5 control)" in { + val sql = "SELECT CAST(NULL AS BIGINT) AS k FROM t UNION SELECT n AS k FROM t" + slotAt(sql, 0).map(s => render(s.sqlType)) shouldBe Some("BIGINT") + slotAt(sql, 1).map(s => render(s.sqlType)) shouldBe Some("INT") + } + + // --------------------------------------------------------------------------------------------- + // G7: forms the engine does not read the slot of (recorded, not consumed) + // --------------------------------------------------------------------------------------------- + + it should "type the recorded forms as core types their column (G7)" in { + // a derived branch aliasing the column: the column is ANY, no slot anywhere + val derived = "SELECT k FROM (SELECT NULL AS k FROM t) dd UNION SELECT n AS k FROM t" + columns(derived).map(_.resultType) shouldBe Seq(SQLTypes.Any) + slots(derived) shouldBe Seq(Some(Seq(None)), Some(Seq(None))) + // beside a SELECT * branch: the declared column is the NULL alone, no slot (D3 a) + val star = "SELECT NULL AS k FROM t UNION ALL SELECT * FROM t1" + columns(star).map(_.resultType) shouldBe Seq(SQLTypes.Null) + slots(star) shouldBe Seq(Some(Seq(None)), None) + // a WITH host: the NULL leg's slot is its column's (the engine runs that branch nested) + val withHost = "WITH a AS (SELECT n FROM t) SELECT NULL AS k FROM a UNION SELECT n AS k FROM t" + slotAt(withHost, 0).map(s => render(s.sqlType)) shouldBe Some("INT") + } +} diff --git a/es8/java/src/test/scala/app/softnetwork/elastic/arrow/JavaClientNullSlotSpec.scala b/es8/java/src/test/scala/app/softnetwork/elastic/arrow/JavaClientNullSlotSpec.scala new file mode 100644 index 00000000..a7604d89 --- /dev/null +++ b/es8/java/src/test/scala/app/softnetwork/elastic/arrow/JavaClientNullSlotSpec.scala @@ -0,0 +1,273 @@ +/* + * 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.arrow + +import akka.actor.ActorSystem +import akka.stream.scaladsl.Sink +import app.softnetwork.elastic.client.{ElasticClientApi, ResultSchema, SetOperationValues} +import app.softnetwork.elastic.client.SetOperationValues.{LegSchema, LegSlot} +import app.softnetwork.elastic.client.result.{ + 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`.SQLTypes +import app.softnetwork.elastic.sql.parser.Parser +import app.softnetwork.elastic.sql.query.MultiSearch +import app.softnetwork.elastic.sql.query.MultiSearch.SetOperationType +import app.softnetwork.persistence.generateUUID +import org.scalatest.flatspec.AnyFlatSpecLike +import org.scalatest.matchers.should.Matchers +import org.slf4j.{Logger, LoggerFactory} + +import scala.collection.immutable.ListMap +import scala.concurrent.Await +import scala.concurrent.duration._ +import scala.util.Try + +/** SCHEMA-18 (R-199) -- a `NULL` literal in a set-operation branch, on Elasticsearch 8, in a + * DOWNSTREAM package as the relational engine reaches it: + * + * - core's own `UNION ALL` answers the column's type there (DuckDB's), its `describe` the schema + * it runs, the NULL branch empty or not -- unchanged by the leg's slot, which core's run path + * does not read; + * - the engine's leg schema (`SetOperationValues.legSchemas`) gives the NULL leg its column's + * type, and reads every canonical cell core gives that leg on its own -- plain, aggregation + * and un-aliased -- as NULL, under the row key core gives it. + */ +class JavaClientNullSlotSpec 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 table = "s18_t" + + /** Created through core's DDL: `ARRAY` is recorded in the mapping's `_meta`. */ + private val ddl: String = + s"CREATE TABLE $table (id KEYWORD, n INT, l BIGINT, x DOUBLE, f REAL, b BOOLEAN, s KEYWORD, " + + "d DATE, ts TIMESTAMP, c_es TIMESTAMP OPTIONS (format = 'epoch_second'), " + + "tsz TIMESTAMP OPTIONS (format = 'yyyy-MM-dd HH:mm z'), bin VARBINARY, " + + "o STRUCT FIELDS(a INT, e TIMESTAMP OPTIONS (format = 'epoch_second')), g GEO_POINT, " + + "ai ARRAY, PRIMARY KEY (id))" + + /** Two documents; the second's `o` has no `a` (A-231). */ + private val docs: Seq[(String, String)] = Seq( + "r1" -> ("""{"id":"r1","n":3,"l":10000000000,"x":1.5,"f":0.5,"b":true,"s":"a",""" + + """"d":"2024-01-31","ts":"2024-01-31T10:30:00Z","c_es":1706697000,""" + + """"tsz":"2024-01-31 10:30 CET","bin":"aGk=","o":{"a":1,"e":1706697000},""" + + """"g":{"lat":1.0,"lon":2.0},"ai":[1,2]}"""), + "r2" -> ("""{"id":"r2","n":5,"l":7,"x":2.5,"f":1.25,"b":false,"s":"b",""" + + """"d":"2024-02-01","ts":"2024-02-01T00:00:00Z","c_es":1706700000,""" + + """"tsz":"2024-01-31 10:30 UTC","bin":"AAE=","o":{"e":1706700000},""" + + """"g":[4.0,3.0],"ai":[3,4]}""") + ) + + override def beforeAll(): Unit = { + super.beforeAll() + Try(Await.result(client.run(s"DROP TABLE IF EXISTS $table"), 60.seconds)) + run(ddl) + docs.foreach { case (id, source) => client.index(table, id, source) } + client.refresh(table) + () + } + + override def afterAll(): Unit = { + Try(client.deleteIndex(table)) + super.afterAll() + } + + private def run(sql: String): QueryResult = + Await.result(client.run(sql), 60.seconds) match { + case ElasticSuccess(result) => result + case ElasticFailure(error) => fail(s"[$sql] ${error.message}") + } + + /** The consumer shape immune to the next arity change, with the schema. */ + private def rowsAndSchema( + result: QueryResult + ): (Seq[ListMap[String, Any]], Option[ResultSchema]) = + result match { + case q: QueryRows => (q.rows, q.schema) + case q: QueryStructured => (q.response.results, q.schema) + case q: QueryStream => + (Await.result(q.stream.map(_._1).runWith(Sink.seq), 60.seconds), q.schema) + case other => fail(s"$other") + } + + private def described(sql: String): Option[ResultSchema] = + client.describe(sql) match { + case ElasticSuccess(schema) => schema + case ElasticFailure(error) => fail(s"[$sql] describe: ${error.message}") + } + + /** The leg schemas the engine reads: each branch with the table's mapping attached. */ + private def legs(sql: String): Seq[Option[LegSchema]] = { + val multiple = Parser(sql) match { + case Right(m: MultiSearch) => + m.copy(requests = m.requests.map(_.update(Some(client.loadSchema(table).get)))) + case other => fail(s"[$sql] $other") + } + SetOperationValues + .legSchemas(multiple.requests, multiple.resolvedOperators, Some("8.18.3")) + .fold(refusal => fail(s"[$sql] $refusal"), identity) + } + + /** A type as DuckDB names it. */ + private def render(t: SetOperationType): String = + t.sqlType match { + case SQLTypes.Struct => + t.fields.map(f => s"${f.name} ${render(f.valueType)}").mkString("STRUCT(", ", ", ")") + case SQLTypes.Array(elementType) => + t.element.map(render).getOrElse(elementType.typeId) + "[]" + case scalar => scalar.typeId + } + + /** A value and its class, comparable across runs. */ + private def canonical(v: Any): (String, String) = + v match { + case null => ("NULL", "null") + case b: Array[Byte] => (b.map(x => f"${x & 0xff}%02x").mkString, "bytes") + case m: scala.collection.Map[_, _] => + ( + m.toSeq.map { case (k, x) => s"$k=${canonical(x)._1}" }.sorted.mkString("{", ",", "}"), + "map" + ) + case s: scala.collection.Seq[_] => (s.map(canonical(_)._1).mkString("[", ",", "]"), "list") + case other => (other.toString, other.getClass.getName) + } + + /** Each sibling: the NULL slot's type (= DuckDB's) and the statement's type on core's run (D4: a + * routed date is answered as stored, `VARCHAR`). + */ + private val siblings: Seq[(String, String, String)] = Seq( + ("n", "INT", "INT"), + ("l", "BIGINT", "BIGINT"), + ("x", "DOUBLE", "DOUBLE"), + ("f", "REAL", "REAL"), + ("b", "BOOLEAN", "BOOLEAN"), + ("s", "VARCHAR", "VARCHAR"), + ("d", "DATE", "DATE"), + ("ts", "TIMESTAMP", "TIMESTAMP"), + ("c_es", "TIMESTAMP", "TIMESTAMP"), + ("tsz", "TIMESTAMP", "VARCHAR"), + ("bin", "VARBINARY", "VARBINARY"), + ("o", "STRUCT(a INT, e TIMESTAMP)", "STRUCT"), + ("o.a", "INT", "INT"), + ("o.e", "TIMESTAMP", "TIMESTAMP"), + ("g", "GEO_POINT", "GEO_POINT"), + ("ai", "INT[]", "ARRAY") + ) + + private val none = "WHERE id = 'none'" + + "Core's UNION ALL" should "answer DuckDB's type at a NULL literal, empty or not" in { + val wrong = for { + (sibling, slotType, statementType) <- siblings + empty <- Seq(false, true) + nullFirst <- Seq(true, false) + problem <- { + val nullBranch = s"SELECT NULL AS k FROM $table${if (empty) s" $none" else ""}" + val other = s"SELECT $sibling AS k FROM $table" + val sql = + if (nullFirst) s"$nullBranch UNION ALL $other" else s"$other UNION ALL $nullBranch" + // the control: the sibling beside an empty copy of itself, on the same path + val control = s"SELECT $sibling AS k FROM $table $none UNION ALL $other" + val (rows, schema) = rowsAndSchema(run(sql)) + val (controlRows, _) = rowsAndSchema(run(control)) + val expected = controlRows.map(r => canonical(r.getOrElse("k", null))) ++ + (if (empty) Nil else docs.map(_ => canonical(null))) + val got = rows.map(r => canonical(r.getOrElse("k", null))) + val nullLeg = if (nullFirst) 0 else 1 + val slot = legs(sql)(nullLeg).flatMap(_.slots.head) + val describedSchema = described(sql) + // `!=` binds looser than `->`: each condition is parenthesised + Seq[(Boolean, String)]( + (schema.map(_.columns.map(_.sqlType.typeId)) != Some(Seq(statementType))) -> + s"type ${schema.map(_.columns.map(_.sqlType.typeId))} instead of $statementType", + (describedSchema != schema) -> s"describe $describedSchema != run $schema", + (got.sorted != expected.sorted) -> s"values $got instead of $expected", + (slot.map(s => render(s.sqlType)) != Some(slotType)) -> + s"NULL slot ${slot.map(s => render(s.sqlType))} instead of $slotType" + ).collect { case (true, what) => s"[$sql] $what" } + } + } yield problem + wrong shouldBe empty + } + + "The engine's leg schema" should "read a NULL leg's every canonical cell as NULL, typed as its column" in { + // each NULL leg run alone through core: its canonical rows, read by its slot under the row key + // core gives the item (`outputName`, the planner's key -- the un-aliased item's too) + val shapes: Seq[(String, String, Boolean)] = Seq( + ( + s"SELECT NULL AS k FROM $table UNION SELECT n AS k FROM $table", + "plain", + true + ), + ( + s"SELECT NULL AS k, COUNT(*) AS c FROM $table UNION SELECT n AS k, COUNT(*) AS c " + + s"FROM $table GROUP BY n", + "aggregation", + false + ), + ( + s"SELECT NULL FROM $table UNION SELECT n FROM $table", + "un-aliased", + true + ) + ) + shapes.foreach { case (sql, shape, scripted) => + withClue(s"[$shape: $sql] ") { + val leg = Parser(sql) match { + case Right(m: MultiSearch) => m.requests.head + case other => fail(s"$other") + } + val key = leg.select.fieldsWithComputedAliases.head.outputName + val slot: LegSlot = legs(sql).head.flatMap(_.slots.head).getOrElse(fail("no NULL slot")) + render(slot.sqlType) shouldBe "INT" + slot.asStored shouldBe Nil + val (rows, _) = rowsAndSchema(run(leg.sql)) + rows should not be empty + rows.foreach { row => + // the un-aliased item: core keys its cell by the output name the engine reads it by + if (shape == "un-aliased") row.keySet should contain(key) + val cell = row.getOrElse(key, null) + assert(slot.read(cell) == null, s"$cell read") + // a row query's NULL item is a script field (Elasticsearch's one-element array, which the + // slot's reader reads); an aggregation's is not, so its canonical cell must be NULL -- a + // list there would be written as it comes by the engine + if (scripted) + assert( + cell == null || (cell match { + case s: scala.collection.Seq[_] => s.size == 1 && s.head == null + case _ => false + }), + s"$cell" + ) + else assert(cell == null, s"$cell") + } + } + } + } +}