|
| 1 | +package org.partiql.eval.internal.operator.rel |
| 2 | + |
| 3 | +import org.partiql.errors.TypeCheckException |
| 4 | +import org.partiql.eval.internal.Record |
| 5 | +import org.partiql.eval.internal.operator.Operator |
| 6 | +import org.partiql.value.MissingValue |
| 7 | +import org.partiql.value.PartiQLValue |
| 8 | +import org.partiql.value.PartiQLValueExperimental |
| 9 | +import org.partiql.value.StructValue |
| 10 | +import org.partiql.value.stringValue |
| 11 | +import org.partiql.value.structValue |
| 12 | + |
| 13 | +/** |
| 14 | + * The unpivot operator produces a bag of records from a struct. |
| 15 | + * |
| 16 | + * Input: { k_0: v_0, ..., k_i: v_i } |
| 17 | + * Output: [ k_0, v_0 ] ... [ k_i, v_i ] |
| 18 | + */ |
| 19 | +@OptIn(PartiQLValueExperimental::class) |
| 20 | +internal sealed class RelUnpivot : Operator.Relation { |
| 21 | + |
| 22 | + /** |
| 23 | + * Iterator of the struct fields. |
| 24 | + */ |
| 25 | + private lateinit var _iterator: Iterator<Pair<String, PartiQLValue>> |
| 26 | + |
| 27 | + /** |
| 28 | + * Each mode overrides. |
| 29 | + */ |
| 30 | + abstract fun struct(): StructValue<*> |
| 31 | + |
| 32 | + /** |
| 33 | + * Initialize the _iterator from the concrete implementation's struct() |
| 34 | + */ |
| 35 | + override fun open() { |
| 36 | + _iterator = struct().entries.iterator() |
| 37 | + } |
| 38 | + |
| 39 | + override fun next(): Record? { |
| 40 | + if (!_iterator.hasNext()) { |
| 41 | + return null |
| 42 | + } |
| 43 | + val f = _iterator.next() |
| 44 | + val k = stringValue(f.first) |
| 45 | + val v = f.second |
| 46 | + return Record.of(k, v) |
| 47 | + } |
| 48 | + |
| 49 | + override fun close() {} |
| 50 | + |
| 51 | + /** |
| 52 | + * In strict mode, the UNPIVOT operator raises an error on mistyped input. |
| 53 | + * |
| 54 | + * @property expr |
| 55 | + */ |
| 56 | + class Strict(private val expr: Operator.Expr) : RelUnpivot() { |
| 57 | + |
| 58 | + override fun struct(): StructValue<*> { |
| 59 | + val v = expr.eval(Record.empty) |
| 60 | + if (v !is StructValue<*>) { |
| 61 | + throw TypeCheckException() |
| 62 | + } |
| 63 | + return v |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * In permissive mode, the UNPIVOT operator coerces the input (v) to a struct. |
| 69 | + * |
| 70 | + * 1. If v is a struct, return it. |
| 71 | + * 2. If v is MISSING, return { }. |
| 72 | + * 3. Else, return { '_1': v }. |
| 73 | + * |
| 74 | + * @property expr |
| 75 | + */ |
| 76 | + class Permissive(private val expr: Operator.Expr) : RelUnpivot() { |
| 77 | + |
| 78 | + override fun struct(): StructValue<*> = when (val v = expr.eval(Record.empty)) { |
| 79 | + is StructValue<*> -> v |
| 80 | + is MissingValue -> structValue<PartiQLValue>() |
| 81 | + else -> structValue("_1" to v) |
| 82 | + } |
| 83 | + } |
| 84 | +} |
0 commit comments