chaisql / chai

Modern embedded SQL database
MIT License
1.56k stars 95 forks source link

Add `len` function for array type #474

Closed icexin closed 2 years ago

icexin commented 2 years ago

Proposal

Currently, it’s not possible to compute the length of array type in Genji

asdine commented 2 years ago

It was planned for another release but I guess we can add it to the next one.

Specs

Function name: len Arity: 1 Params: an expression that evaluates to either:

Example:

SELECT len("hello");
{
  "len(\"hello"\)": 5
}

SELECT len([1, 2, 3, [4, 5]]) AS length;
{
  "length": 4
}

-- len with incompatible types evaluate to NULL
SELECT len(10) AS length;
{
  "length": NULL
}

-- example with a table
CREATE TABLE foo(
  a TEXT,
  b ARRAY,
  c (
      ...
  )
);

INSERT INTO foo VALUES (
  "hello",
  [1, 2, 3, [4, 5]],
  {
    a: 1,
    b: 2,
    c: {
      d: 3
    }
  }
);

-- length of a text field
SELECT len(a) FROM foo;
{
  "len(a)":10
}

SELECT len(b) FROM foo;
{
  "len(a)": 4
}

SELECT len(c) FROM foo;
{
  "len(a)": 3
}

SELECT len(b[3]) FROM foo;
{
  "len(b[3])": 2
}

SELECT len(c.c)  FROM foo;
{
  "len(c.c)": 1
}
gedw99 commented 2 years ago

This looks great