diff --git a/docs/src/js/classes/AutoQuery.md b/docs/src/js/classes/AutoQuery.md index 60f568e07..48fd52121 100644 --- a/docs/src/js/classes/AutoQuery.md +++ b/docs/src/js/classes/AutoQuery.md @@ -341,16 +341,24 @@ You can also use this method to create new "dynamic" columns based on your exist 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. 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. 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: +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` (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. #### Parameters -* **columns**: `string` \| `string`[] \| `Map`<`string`, `string`> \| `Record`<`string`, `string`> +* **columns**: `string` \| `string`[] \| `Map`<`string`, `string` \| [`Expr`](Expr.md)> \| `Record`<`string`, `string` \| [`Expr`](Expr.md)> #### Returns @@ -359,14 +367,8 @@ input to this method would be: #### Example ```ts -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` (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. +table.query().select(new Map([["combined", "a + b"], ["c", "c"]])); +table.query().select({ id: "id", doubled: col("unitPrice").mul(2) }); ``` #### Inherited from diff --git a/docs/src/js/classes/Query.md b/docs/src/js/classes/Query.md index 7434e7b8e..a2613cccf 100644 --- a/docs/src/js/classes/Query.md +++ b/docs/src/js/classes/Query.md @@ -415,16 +415,24 @@ You can also use this method to create new "dynamic" columns based on your exist 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. 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. 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: +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` (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. #### Parameters -* **columns**: `string` \| `string`[] \| `Map`<`string`, `string`> \| `Record`<`string`, `string`> +* **columns**: `string` \| `string`[] \| `Map`<`string`, `string` \| [`Expr`](Expr.md)> \| `Record`<`string`, `string` \| [`Expr`](Expr.md)> #### Returns @@ -433,14 +441,8 @@ input to this method would be: #### Example ```ts -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` (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. +table.query().select(new Map([["combined", "a + b"], ["c", "c"]])); +table.query().select({ id: "id", doubled: col("unitPrice").mul(2) }); ``` #### Inherited from diff --git a/docs/src/js/classes/QueryBase.md b/docs/src/js/classes/QueryBase.md index 0ef4fa286..20ee8e558 100644 --- a/docs/src/js/classes/QueryBase.md +++ b/docs/src/js/classes/QueryBase.md @@ -184,16 +184,24 @@ You can also use this method to create new "dynamic" columns based on your exist 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. 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. 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: +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` (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. #### Parameters -* **columns**: `string` \| `string`[] \| `Map`<`string`, `string`> \| `Record`<`string`, `string`> +* **columns**: `string` \| `string`[] \| `Map`<`string`, `string` \| [`Expr`](Expr.md)> \| `Record`<`string`, `string` \| [`Expr`](Expr.md)> #### Returns @@ -202,14 +210,8 @@ input to this method would be: #### Example ```ts -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` (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. +table.query().select(new Map([["combined", "a + b"], ["c", "c"]])); +table.query().select({ id: "id", doubled: col("unitPrice").mul(2) }); ``` *** diff --git a/docs/src/js/classes/TakeQuery.md b/docs/src/js/classes/TakeQuery.md index 65bc35f08..459f34998 100644 --- a/docs/src/js/classes/TakeQuery.md +++ b/docs/src/js/classes/TakeQuery.md @@ -191,16 +191,24 @@ You can also use this method to create new "dynamic" columns based on your exist 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. 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. 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: +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` (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. #### Parameters -* **columns**: `string` \| `string`[] \| `Map`<`string`, `string`> \| `Record`<`string`, `string`> +* **columns**: `string` \| `string`[] \| `Map`<`string`, `string` \| [`Expr`](Expr.md)> \| `Record`<`string`, `string` \| [`Expr`](Expr.md)> #### Returns @@ -209,14 +217,8 @@ input to this method would be: #### Example ```ts -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` (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. +table.query().select(new Map([["combined", "a + b"], ["c", "c"]])); +table.query().select({ id: "id", doubled: col("unitPrice").mul(2) }); ``` #### Inherited from diff --git a/docs/src/js/classes/VectorQuery.md b/docs/src/js/classes/VectorQuery.md index 2eef209bf..3ab4f1068 100644 --- a/docs/src/js/classes/VectorQuery.md +++ b/docs/src/js/classes/VectorQuery.md @@ -734,16 +734,24 @@ You can also use this method to create new "dynamic" columns based on your exist 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. 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. 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: +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` (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. #### Parameters -* **columns**: `string` \| `string`[] \| `Map`<`string`, `string`> \| `Record`<`string`, `string`> +* **columns**: `string` \| `string`[] \| `Map`<`string`, `string` \| [`Expr`](Expr.md)> \| `Record`<`string`, `string` \| [`Expr`](Expr.md)> #### Returns @@ -752,14 +760,8 @@ input to this method would be: #### Example ```ts -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` (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. +table.query().select(new Map([["combined", "a + b"], ["c", "c"]])); +table.query().select({ id: "id", doubled: col("unitPrice").mul(2) }); ``` #### Inherited from diff --git a/docs/src/js/interfaces/QueryExecutionOptions.md b/docs/src/js/interfaces/QueryExecutionOptions.md index cd36343b8..65c01a3fd 100644 --- a/docs/src/js/interfaces/QueryExecutionOptions.md +++ b/docs/src/js/interfaces/QueryExecutionOptions.md @@ -26,8 +26,9 @@ How to return blob v2 columns. Applies to `toArrow()` and `toArray()`. 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 diff --git a/nodejs/__test__/expr.test.ts b/nodejs/__test__/expr.test.ts index 492929c04..d2b7c858c 100644 --- a/nodejs/__test__/expr.test.ts +++ b/nodejs/__test__/expr.test.ts @@ -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>; + 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([ + ["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([ + ["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([ + ["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([ diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index 6b72f19fd..7ac58c3bb 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -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. 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. 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` (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` (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 | Record | string, + columns: + | string[] + | Map + | Record + | 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 }; diff --git a/nodejs/src/expr.rs b/nodejs/src/expr.rs index c12f81a96..0ea18e55d 100644 --- a/nodejs/src/expr.rs +++ b/nodejs/src/expr.rs @@ -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 { + match &self.inner { + DfExpr::Column(column) if column.relation.is_none() => Some(column.name.clone()), + _ => None, + } + } + #[napi] pub fn to_sql(&self) -> napi::Result { lancedb::expr::expr_to_sql_string(&self.inner)