feat(node): accept Expr values in select() (#4878)

Closes #3042.

Node `select()` now takes `Expr` values, the same expression builder
that `where()` already accepts. A `Map` or a plain object can mix `Expr`
values and SQL strings:

```ts
import { col } from "@lancedb/lancedb";

const rows = await table
  .query()
  .select({
    id: "id",
    name: col("firstName"),
    total: col("unitPrice").mul(col("quantity")),
  })
  .toArray();
```

This works on every query with `select()`: `query()`, `vectorSearch()`,
`search()` and the take queries. The parameter type is now `Map<string,
string | Expr>` and `Record<string, string | Expr>`. Nothing else in the
TypeScript API changes.

### How it works

`select()` turns each `Expr` into SQL with `toSql()` and passes the
pairs to the native `select` that SQL strings already use. `where()`
handles an `Expr` the same way, so Node treats expressions alike in both
places. `toSql()` quotes camelCase names and SQL keywords with
backticks, so `col("firstName")` reads `firstName`.

I also looked at passing the expressions to Rust as `Select::Expr`, as
Python's `select_expr` does. I didn't go that way:

- Before a local or remote query runs, Rust turns `Select::Expr` back
into SQL with the same `expr_to_sql_string`. The query is the same
either way.
- A map that mixes SQL strings and expressions can't become a
`Select::Expr` without parsing the strings. Python's `AsyncQuery.select`
sends a mixed dict through `select_expr` and wraps each string with
`lit()` (`_coerce`), so `select({"id": "id", "doubled": col("score") *
lit(2)})` returns the string `'id'` in the `id` column. Sending SQL
keeps every string a SQL expression.
- I found one path that accepts `Select::Expr` and rejects
`Select::Dynamic`: namespace `QueryTable` pushdown. Node can't turn
pushdown on today, so nothing changes yet. If Node gets that option,
`select()` can send `Select::Expr` when every value is an `Expr`.

`blobMode: "bytes"` (#4353) finds blob columns by name in the `[output,
source]` list of the selection. For a camelCase column, `toSql()` gives
`` `imageData` ``, which doesn't match `imageData`. So when an `Expr` is
a bare column reference, the match uses its plain name. For this, the
native `Expr` gets a small `columnName()` helper, like `column_name()`
in the Python bindings, which Python uses for the same match. A blob
renamed with `col()` gets its bytes, as with a SQL string. Other
expressions are not filled with bytes, as before.

A value that is neither a string nor an `Expr` now throws a `TypeError`
that names the key, instead of the native conversion error.

### Tests

New tests in `expr.test.ts`:

- a `Map` that mixes SQL strings with `col("firstName")` and
`col("unitPrice").mul(2)` on a plain query, with the column order
- a `Record` with `upper()`, `func("lower", ...)` and a SQL string,
filtered with an `Expr` in `where()`
- `Expr` values on a vector query, an automatic `search()` (full-text
search) and a take query
- `blobMode: "bytes"` with a camelCase blob column selected with
`col()`: renamed, next to a computed `Expr` column, and in a take query
- a number as a value throws a `TypeError`

The whole Node suite passes. The Node docs under `docs/src/js` are
regenerated. The `@example` in the middle of the `select()` docstring
used to swallow the two paragraphs after it into the code block, so I
moved the example to the end, which is why each query class page
changes.

Left out: `Expr` items in the plain column list (`select([col("a")])`),
because an expression needs an output name. The `select` of a
materialized view still takes SQL strings only.
This commit is contained in:
Bilal Atique
2026-11-27 17:10:43 +08:00
committed by GitHub
parent fdfbb98a9c
commit 09beba532e
9 changed files with 298 additions and 85 deletions
+167 -1
View File
@@ -5,7 +5,7 @@ import * as http from "http";
import type { AddressInfo } from "net";
import * as tmp from "tmp";
import { type Table, connect } from "../lancedb";
import { type Table, blob, connect } from "../lancedb";
import {
Table as ArrowTable,
Field,
@@ -15,6 +15,7 @@ import {
tableToIPC,
} from "../lancedb/arrow";
import { Expr, col, func, lit, litBool, litInt } from "../lancedb/expr";
import { Index } from "../lancedb/indices";
describe("expr", () => {
describe("col", () => {
@@ -271,6 +272,171 @@ describe("expr", () => {
});
});
describe("select", () => {
let db: Awaited<ReturnType<typeof connect>>;
let table: Table;
let tmpDir: tmp.DirResult;
beforeAll(async () => {
tmpDir = tmp.dirSync({ unsafeCleanup: true });
db = await connect(tmpDir.name);
table = await db.createTable("items", [
{ id: 1, firstName: "Alice", unitPrice: 10, vector: [1, 0] },
{ id: 2, firstName: "Bob", unitPrice: 20, vector: [0, 1] },
{ id: 3, firstName: "Charlie", unitPrice: 30, vector: [-1, 0] },
]);
await table.createIndex("firstName", { config: Index.fts() });
});
afterAll(() => {
table.close();
db.close();
tmpDir.removeCallback();
});
it("accepts Expr values in a Map, mixed with SQL strings", async () => {
const rows = await table
.query()
.select(
new Map<string, string | Expr>([
["id", "id"],
["name", col("firstName")],
["doubled", col("unitPrice").mul(2)],
]),
)
.toArray();
expect(Object.keys(rows[0])).toEqual(["id", "name", "doubled"]);
expect(rows.map((row) => [row.id, row.name, row.doubled])).toEqual([
[1, "Alice", 20],
[2, "Bob", 40],
[3, "Charlie", 60],
]);
});
it("accepts Expr values in a Record, mixed with SQL strings", async () => {
const [row] = await table
.query()
.where(col("firstName").eq("Bob"))
.select({
shout: col("firstName").upper(),
quiet: func("lower", col("firstName")),
id: "id",
})
.toArray();
expect(Object.keys(row)).toEqual(["shout", "quiet", "id"]);
expect([row.shout, row.quiet, row.id]).toEqual(["BOB", "bob", 2]);
});
it("accepts Expr values in a vector query", async () => {
const rows = await table
.vectorSearch([1, 0])
.select({ name: col("firstName"), doubled: col("unitPrice").mul(2) })
.limit(1)
.toArray();
expect(rows).toHaveLength(1);
expect([rows[0].name, rows[0].doubled]).toEqual(["Alice", 20]);
});
it("accepts Expr values in an automatic search", async () => {
const rows = await table
.search("Bob")
.select({ name: col("firstName"), doubled: col("unitPrice").mul(2) })
.toArray();
expect(rows).toHaveLength(1);
expect([rows[0].name, rows[0].doubled]).toEqual(["Bob", 40]);
});
it("accepts Expr values in a take query", async () => {
const rows = await table
.takeOffsets([2, 0])
.select(
new Map<string, string | Expr>([
["name", col("firstName")],
["doubled", col("unitPrice").mul(2)],
]),
)
.toArray();
expect(
rows.map((row) => [row.name, row.doubled]).sort((a, b) => a[1] - b[1]),
).toEqual([
["Alice", 20],
["Charlie", 60],
]);
});
it("rejects a value that is neither SQL nor an Expr", () => {
const select = () => table.query().select({ id: 1 as unknown as string });
expect(select).toThrow(TypeError);
expect(select).toThrow(
'select() values must be SQL strings or Expr objects, got number for "id"',
);
});
describe("with blobMode bytes", () => {
const alpha = Buffer.from("alpha");
const beta = Buffer.from("beta");
let blobs: Table;
beforeAll(async () => {
const schema = new Schema([
new Field("id", new Int64(), true),
blob("imageData"),
]);
blobs = await db.createTable(
"blobs",
[
{ id: 1n, imageData: alpha },
{ id: 2n, imageData: beta },
],
{ schema },
);
});
afterAll(() => {
blobs.close();
});
it("fills a camelCase blob column renamed with col()", async () => {
const [row] = await blobs
.query()
.where("id = 2")
.select(
new Map<string, string | Expr>([
["key", "id"],
["picture", col("imageData")],
]),
)
.toArray({ blobMode: "bytes" });
expect(Object.keys(row)).toEqual(["key", "picture"]);
expect(Number(row.key)).toBe(2);
expect(Buffer.from(row.picture)).toEqual(beta);
});
it("fills a blob column next to a computed Expr", async () => {
const rows = await blobs
.query()
.select({ imageData: col("imageData"), next: col("id").add(1) })
.toArray({ blobMode: "bytes" });
expect(Object.keys(rows[0])).toEqual(["imageData", "next"]);
expect(
rows.map((row) => [Buffer.from(row.imageData), Number(row.next)]),
).toEqual([
[alpha, 2],
[beta, 3],
]);
});
it("fills a blob column selected with col() in a take query", async () => {
const rows = await blobs
.takeOffsets([0])
.select({ picture: col("imageData") })
.toArray({ blobMode: "bytes" });
expect(Object.keys(rows[0])).toEqual(["picture"]);
expect(Buffer.from(rows[0].picture)).toEqual(alpha);
});
});
});
it("sends a quoted expression value to remote as one literal", async () => {
const value = "\\') OR true --";
const schema = new Schema([
+44 -17
View File
@@ -283,8 +283,9 @@ export interface QueryExecutionOptions {
* called. All the bytes are held in memory.
*
* Selecting a parent struct or directly aliasing a blob or struct also returns
* bytes. Blobs inside lists keep their descriptors. Arbitrary projection
* expressions are not materialized as bytes.
* bytes, including through an `Expr` that only references a column, such as
* `col("image")`. Blobs inside lists keep their descriptors. Arbitrary
* projection expressions are not materialized as bytes.
*
* The rows and bytes come from the same snapshot. Remote queries require
* authoritative query version and snapshot identity headers, verified again
@@ -416,34 +417,62 @@ export class QueryBase<
* For example, you may not care about "a" or "b" but instead simply want "a + b". This is often
* seen in the SELECT clause of an SQL query (e.g. `SELECT a+b FROM my_table`).
*
* To create dynamic columns you can pass in a Map<string, string>. A column will be returned
* for each entry in the map. The key provides the name of the column. The value is
* an SQL string used to specify how the column is calculated.
* To create dynamic columns you can pass in a Map<string, string | Expr>. A column will be
* returned for each entry in the map. The key provides the name of the column. The value is
* an SQL string or an `Expr` that specifies how the column is calculated. An `Expr` built
* with `col` keeps the exact, case-sensitive column name.
*
* For example, an SQL query might state `SELECT a + b AS combined, c`. The equivalent
* input to this method would be:
* @example
* new Map([["combined", "a + b"], ["c", "c"]])
* input to this method would be `new Map([["combined", "a + b"], ["c", "c"]])`.
*
* Columns will always be returned in the order given, even if that order is different than
* the order used when adding the data.
*
* Note that you can pass in a `Record<string, string>` (e.g. an object literal). This method
* uses `Object.entries` which should preserve the insertion order of the object. However,
* object insertion order is easy to get wrong and `Map` is more foolproof.
* Note that you can pass in a `Record<string, string | Expr>` (e.g. an object literal). This
* method uses `Object.entries` which should preserve the insertion order of the object.
* However, object insertion order is easy to get wrong and `Map` is more foolproof.
*
* @example
* ```ts
* table.query().select(new Map([["combined", "a + b"], ["c", "c"]]));
* table.query().select({ id: "id", doubled: col("unitPrice").mul(2) });
* ```
*/
select(
columns: string[] | Map<string, string> | Record<string, string> | string,
columns:
| string[]
| Map<string, string | Expr>
| Record<string, string | Expr>
| string,
): this {
const selectColumns = (columnArray: string[]) => {
this.doCall((inner: NativeQueryType) => {
inner.selectColumns(columnArray);
});
};
const selectMapping = (columnTuples: [string, string][]) => {
const selectMapping = (entries: [string, string | Expr][]) => {
const columnTuples: [string, string][] = [];
const sources: [string, string][] = [];
for (const [name, value] of entries) {
if (value instanceof Expr) {
const sql = value.toSql();
columnTuples.push([name, sql]);
// toSql() quotes camelCase names and SQL keywords, so blobMode
// matches a bare column reference by its plain name instead.
sources.push([name, value.inner.columnName() ?? sql]);
} else if (typeof value === "string") {
columnTuples.push([name, value]);
sources.push([name, value]);
} else {
throw new TypeError(
`select() values must be SQL strings or Expr objects, got ${typeof value} for "${name}"`,
);
}
}
this.doCall((inner: NativeQueryType) => {
inner.select(columnTuples);
});
return sources;
};
let projection: [string, string][];
@@ -454,11 +483,9 @@ export class QueryBase<
selectColumns(columns);
projection = columns.map((column) => [column, column]);
} else if (columns instanceof Map) {
projection = Array.from(columns.entries());
selectMapping(projection);
projection = selectMapping(Array.from(columns.entries()));
} else {
projection = Object.entries(columns);
selectMapping(projection);
projection = selectMapping(Object.entries(columns));
}
if (this.blobContext !== undefined) {
this.blobContext = { ...this.blobContext, projection };
+9
View File
@@ -163,6 +163,15 @@ impl Expr {
})
}
/// The column name when this is a bare column reference, otherwise null.
#[napi]
pub fn column_name(&self) -> Option<String> {
match &self.inner {
DfExpr::Column(column) if column.relation.is_none() => Some(column.name.clone()),
_ => None,
}
}
#[napi]
pub fn to_sql(&self) -> napi::Result<String> {
lancedb::expr::expr_to_sql_string(&self.inner)