Files
lancedb/nodejs/lancedb/index.ts
T
Xuanwo 08a286edb3 feat: add resumable staged table writes (#5358)
A coordinator can publish batches staged by multiple ingest workers in a
single table version. This adds staged append and overwrite in LanceDB
Embedded and Enterprise across Rust, synchronous and asynchronous
Python, and TypeScript. Ordinary `table.add()` continues to commit
immediately.

A coordinator selects the mode with `begin_write(mode)` (`beginWrite` in
TypeScript) and shares the opaque write ID. Workers open the same
writable table and branch and resume with `open_write(id)` (`openWrite`
in TypeScript). They can retry the same input with the same idempotency
key. Staging returns no version. Explicit `commit()` publishes one
version and returns `AddResult`. Explicit `abort()` discards the staged
write and can be repeated. Dropping a handle performs no I/O.

Enterprise uses the existing multipart endpoints on servers with
multipart write support. A non-empty staged overwrite input carrying
top-level Arrow schema metadata fails before the SDK sends any part
insert. The SDK enforces this in Rust `StagedWrite::add(...).execute()`,
Python `StagedWrite.add` and `AsyncStagedWrite.add`, and TypeScript
`StagedWrite.add` on every supported Enterprise server version. Empty
input is a no-op. Staged append and overwrite with an empty top-level
map are supported, including field and nested field metadata on
overwrite. [OSS-2859](https://linear.app/lancedb/issue/OSS-2859) ·
[Distributed reads in OSS-441](https://linear.app/lancedb/issue/OSS-441)

The separate Sophon fix preserves top-level schema metadata in the
server’s multipart overwrite path. The SDK follow-up verifies a route
that sends every part, retry, and completion to fixed instances before
lifting the guard.
[ENT-4970](https://linear.app/lancedb/issue/ENT-4970/multipart-overwrite-drops-top-level-schema-metadata-in-sophon)
· [Sophon #11472](https://github.com/lancedb/sophon/pull/11472) ·
[OSS-3312](https://linear.app/lancedb/issue/OSS-3312/enable-schema-metadata-in-enterprise-staged-overwrite-after-verifying)

Embedded staged overwrites keep top-level, field, and nested-field
metadata from the replacement schema. Commit rejects overwrite parts
whose restored schemas differ. The Insert data guide shows staged writes
in Python, TypeScript, and Rust. The Distributed Write guide describes
both SDK-coordinated staging and server-coordinated CTAS.

## Validation

Final head `cf6737cece7b17f33a13556ba13f1460a0d4cfc8` adds the guard in
`a02beb97084cb9d5d70b0bfdbbf31ce7bb4b1067` and a documentation-only
commit.

- **Rust.** All 14 `--lib staged_write` tests and all 15 `--lib
multipart_write` tests passed with the locked `ci` profile and
Enterprise support.
`explicit_enterprise_overwrite_rejects_schema_metadata_before_upload`
covers rejection before insert, known and streaming empty inputs, and a
subsequent field-metadata part in the same session.

- **Python and Sophon 1.16.0.** The Python extension was rebuilt with
the final Rust inputs. The staged-write and permutation suites passed
133 tests with 2 skipped. On the isolated released-service fixture, sync
and async staged overwrite rejected top-level metadata with zero insert
requests. A materialized zero-row table and a streaming zero-row batch
both succeeded without an insert. A fresh read verified the original
version, row, and schema. Two independent workers then staged parts with
field and nested field metadata, and an independent coordinator
published one version with exactly the replacement rows. The reopened
SDK table and Lance manifest preserved that metadata. Ordinary overwrite
and staged append also succeeded.

- **TypeScript and docs.** TypeScript compilation, lint, TypeDoc, strict
MkDocs, and Vale passed. The final TypeScript changes are documentation.
The earlier Node native build and staged-write test below cover the
binding. The Rust tests and rebuilt Python extension exercised the final
shared guard.

At `ab9f49fba5055a5f731fe013a820515aa5cfa12c`, all 11 Rust staged-write
integration tests and 13 staged-write unit tests passed. The new tests
exercise independent reopen, reject differences at each metadata level,
and verify one publication with the complete schema after replacing the
mismatched part. Rust formatting and Vale passed for the follow-up.

On the initial validation head
`68e950d24a1418890f80eb04102de49388012318`:

- Rust passed the library check with Enterprise support and 15 existing
multipart tests.
- Python passed both staged-write tests covering synchronous
multiprocessing and asynchronous overwrite and abort. The separate
fail-loud fragment constraint regression passed all 39 cases.
[#5120](https://github.com/lancedb/lancedb/pull/5120)
- Node.js passed the native build, TypeScript compilation, lint, and the
staged-write Jest test. TypeDoc generation and strict MkDocs also
passed.

The initial Python and Node.js native extensions were built at
`47ea43533f103744e84a7cdbe83d8e4a8ddf093e` with the repository’s `ci`
profile, the default SDK features, and locked Lance 16.0.0-beta.7 and
`object_store` 0.14.2. The initial validation head differs from that
build commit only in two generated TypeDoc pages. The Python and Node.js
tests ran again at that head using the same native artifacts.

The candidate Python SDK passed multipart create, cross-process staging,
commit, and abort against released LanceDB Enterprise (Sophon) 1.16.0 on
an isolated loopback gateway and S3-compatible store. After an ordinary
append published version 2, a separate coordinator committed the staged
batches once to version 3, with exactly the three expected rows. The
probe also verified overwrite conflict handling, schema refresh after a
successful overwrite, and branch and pinned-handle behavior.

Both abort modes removed the upload marker and staged transaction
records, rejected subsequent staging and commit, and left the table at
version 3 with the same rows. Append abort removed its staged payload.
Overwrite abort left one unreferenced data file in object storage for
storage cleanup.

A separate Sophon 1.16.0 probe confirmed that multipart overwrite loses
top-level schema metadata, including `embedding_functions` and
`lancedb::column_definitions`. Field and nested-field metadata survived,
and a single-request overwrite preserved the full metadata on the same
input.

## Local security comparison

Compared head `ab9f49fba5055a5f731fe013a820515aa5cfa12c` with its merge
base `c85647526c90647d9b5d6a701afeacca3f47b34d`.

- **Dependencies.** OSV-Scanner 2.7.1 used one offline crates.io
advisory snapshot for both Cargo locks. Each scan read 1,098 package
entries and reported the same 48 advisory matches across 24 package
versions. The change makes the already-locked `prost` 0.14.4 a direct
dependency for Embedded, where Lance already pulls it in. OSV and the
GitHub Advisory Database returned no advisory for that version. The
Cargo, Python, and Node lockfiles are byte-identical. The latter two
therefore did not require a dependency audit.

- **Source.** Semgrep Community Edition 1.187.0 ran 658 security and
secret rules on 16 baseline files and 24 candidate files across Rust,
Python, and TypeScript. Both results contained the same 31 matches on
unchanged code, with zero skipped targets or parse errors. These were
existing Rust `unsafe` blocks in tests and N-API branch metadata, a
Python serialization check, and a TypeScript iterator call through
`Symbol.asyncIterator`. [Rule
snapshot](https://github.com/semgrep/semgrep-rules/tree/a5ad1714f00c9f7fde980cab0ea1d6dc6d414fd2)

The OSV results cover lockfile package versions in the local database.
Semgrep covers the changed source files with file-local analysis.
Rule-level Aikido results were unavailable for comparison.
2026-12-02 20:52:30 +00:00

784 lines
20 KiB
TypeScript

// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import "./errors_install";
import {
type Connection,
LocalConnection,
cleanseStorageOptions,
} from "./connection";
import {
type ConnectNamespaceOptions,
type ConnectionOptions,
Connection as LanceDbConnection,
JsHeaderProvider as NativeJsHeaderProvider,
type Session,
tokenize as nativeTokenize,
} from "./native.js";
import type { HeaderProvider } from "./header";
import type { BaseTokenizer } from "./indices";
import type { FtsToken } from "./table";
// Re-export native header provider for use with connectWithHeaderProvider
export {
MaterializedView,
MaterializedViewDefinition,
MaterializedViewSelect,
} from "./materialized_view";
export { ViewDescription } from "./view";
export { JsHeaderProvider as NativeJsHeaderProvider } from "./native.js";
// OpenTelemetry metrics bridge. Only the high-level entry point is public; the
// underlying recorder/catalog/snapshot functions remain internal plumbing that
// `otel.ts` consumes from the native module.
export { instrumentLanceDbMetrics } from "./otel";
export {
AddColumnsSql,
ConnectionOptions,
ConnectNamespaceOptions,
IndexStatistics,
IndexConfig,
ClientConfig,
TimeoutConfig,
RetryConfig,
TlsConfig,
OptimizeStats,
CompactionStats,
RemovalStats,
TableStatistics,
FragmentStatistics,
FragmentSummaryStats,
Tags,
TagContents,
MergeResult,
AddResult,
AddColumnsResult,
RefreshColumnOptions,
FunctionRefreshPlanningConfig,
FunctionRefreshPodResources,
FunctionRetryPolicy,
RefreshColumnResult,
FunctionErrors,
FunctionErrorsOptions,
FunctionErrorGroup,
FunctionErrorRecord,
FunctionErrorFragment,
FunctionProvenance,
FunctionProvenanceOptions,
FunctionQuarantineOptions,
FunctionValueProvenance,
RefreshMaterializedViewResult,
AlterColumnsResult,
UpdateFieldMetadataResult,
DeleteResult,
DropColumnsResult,
UpdateResult,
SplitCalculatedOptions,
SplitRandomOptions,
SplitHashOptions,
SplitSequentialOptions,
ShuffleOptions,
OAuthConfig as NativeOAuthConfig,
} from "./native.js";
export { BranchContents, ListedBranchContents } from "./table";
export {
makeArrowTable,
makeJsonField,
MakeArrowTableOptions,
Data,
VectorColumnOptions,
} from "./arrow";
export { blob, isBlobField, BlobFile } from "./blob";
export type { BlobDescriptor, BlobDescriptorSource } from "./blob";
export type {
BlobData,
BlobInput,
BlobOptions,
BlobRange,
BlobRangeRequest,
BlobReadOptions,
BlobUri,
} from "./blob";
export {
Connection,
CreateTableOptions,
TableNamesOptions,
OpenTableOptions,
CreateNamespaceOptions,
DropNamespaceOptions,
CreateNamespaceResponse,
DropNamespaceResponse,
DescribeNamespaceResponse,
RenameTableOptions,
} from "./connection";
export type {
FunctionErrorRowsOptions,
FunctionFailedRow,
FunctionRecompute,
RefreshColumnJobResult,
RetryFailedOptions,
UpgradeColumnOptions,
} from "./function_recovery";
export { JobFailureInfo, JobInfo, Session } from "./native.js";
export {
Job,
JobEventsOptions,
} from "./job";
export type {
JobProgress,
JobProgressCallback,
JobState,
JobWaitOptions,
} from "./job";
export type {
FunctionProfile,
FunctionProfileKind,
FunctionProfileOptions,
FunctionProfileStatus,
FunctionProfileWaitOptions,
} from "./profiling";
export {
QueryResult,
QueryMetadata,
TotalHits,
MetadataPendingError,
MetadataCancelledError,
} from "./query_result";
export {
AutoQuery,
ExecutableQuery,
Query,
QueryBase,
VectorQuery,
TakeQuery,
AnalyzePlanDistributedMetrics,
BlobMode,
QueryExecutionOptions,
ColumnOrdering,
FullTextSearchOptions,
RecordBatchIterator,
FullTextQuery,
MatchQuery,
PhraseQuery,
BoostQuery,
MultiMatchQuery,
BooleanQuery,
FullTextQueryType,
Operator,
Occur,
} from "./query";
export {
Index,
IndexOptions,
IvfPqOptions,
IvfRqOptions,
IvfFlatOptions,
HnswPqOptions,
HnswSqOptions,
BloomFilterOptions,
FtsOptions,
RTreeOptions,
BaseTokenizer,
} from "./indices";
export {
Table,
StagedWrite,
TableDelta,
TableDeltaReader,
TableDeltaTransaction,
DeltaVersion,
FunctionColumnAutoRefreshStatus,
FunctionColumnLastRefreshJob,
FunctionColumnStatus,
FunctionColumnVersionStatus,
Branches,
CreateBranchOptions,
BranchColumnSummary,
BranchColumnChange,
BranchIndexSummary,
BranchRowCountSummary,
CherryPickError,
BranchDiff,
CherryPickPreview,
CherryPickResult,
AddDataOptions,
UpdateOptions,
OptimizeOptions,
CompactionOptions,
PrewarmDataOptions,
Version,
WriteProgress,
FtsToken,
TokenizeTableOptions,
RTEWriteSpec,
RTEStats,
TableShardStats,
SsTableStats,
MemtableStats,
ColumnAlteration,
FieldMetadataUpdate,
} from "./table";
export {
HeaderProvider,
StaticHeaderProvider,
OAuthHeaderProvider,
TokenResponse,
} from "./header";
export {
ClientAuthMethod,
OAuthConfig,
OAuthFlowType,
OAuthSession,
SessionLogout,
SessionStatus,
TokenCacheOptions,
} from "./oauth";
export { MergeInsertBuilder, WriteExecutionOptions } from "./merge";
export * as embedding from "./embedding";
export { permutationBuilder, PermutationBuilder } from "./permutation";
export { Scannable, ScannableOptions } from "./scannable";
export * as rerankers from "./rerankers";
export {
SchemaLike,
TableLike,
DataTypeLike,
FieldLike,
RecordBatchLike,
DataLike,
IntoVector,
MultiVector,
} from "./arrow";
export {
ColumnAlreadyExistsError,
ColumnNotFoundError,
CreateDirError,
DatabaseAlreadyExistsError,
DatabaseNotFoundError,
EmbeddingFunctionNotFoundError,
ExternalError,
FieldNotFoundError,
HttpError,
IndexNotFoundError,
InvalidExpressionError,
InvalidInputError,
InvalidTableNameError,
JobCancelledError,
JobFailedError,
JobNotFoundError,
LanceArrowError,
LanceError,
LanceFormatError,
LanceRuntimeError,
NotAComputedColumnError,
NotAMaterializedViewError,
NotSupportedError,
UnsupportedMetadataError,
ObjectStoreError,
OtherError,
RetryError,
SchemaError,
SqlError,
TableAlreadyExistsError,
TableCorruptedError,
TableNotFoundError,
TimeoutError,
isAlreadyExistsError,
isLanceError,
} from "./errors";
export type { LanceErrorOptions } from "./errors";
export { IntoSql, packBits } from "./util";
export { Expr, col, lit, litBool, litInt, func } from "./expr";
export type { ExprLike } from "./expr";
/**
* Options for tokenizing a full-text search query without a table index.
*/
export interface TokenizeOptions {
/**
* The tokenizer to use. The default is "simple".
*/
baseTokenizer?: BaseTokenizer;
/** Language for stemming and stop words. */
language?: string;
/** Maximum token length; tokens longer than this are ignored. */
maxTokenLength?: number;
/** Whether to lowercase tokens. */
lowercase?: boolean;
/** Whether to stem tokens. */
stem?: boolean;
/** Whether to remove stop words. */
removeStopWords?: boolean;
/**
* Custom stop words that replace the built-in list for `language`.
*
* This option only affects tokenization when `removeStopWords` is true.
*
* `undefined` keeps the built-in language list. An empty array explicitly
* replaces it with no stop words.
*/
customStopWords?: string[];
/** Whether to fold ASCII characters. */
asciiFolding?: boolean;
/** N-gram minimum length. */
ngramMinLength?: number;
/** N-gram maximum length. */
ngramMaxLength?: number;
/** Whether to only emit token prefixes for the n-gram tokenizer. */
prefixOnly?: boolean;
/**
* The analyzer family to use. See {@link FtsOptions.analyzer}.
*/
analyzer?: "text" | "code";
/** Split code identifiers into subwords. See {@link FtsOptions.splitIdentifiers}. */
splitIdentifiers?: boolean;
/** Split identifier subwords at letter and number boundaries. */
splitOnNumerics?: boolean;
/** Also emit the complete identifier next to its subwords. */
preserveOriginal?: boolean;
/** Emit code operators such as `::`, `->` and `!=`. */
indexOperators?: boolean;
}
/**
* Tokenize a full-text search query using an explicit tokenizer.
*
* This does not require a table or FTS index. The tokenizer options match
* {@link Index.fts}.
*/
export async function tokenize(
query: string,
options?: Partial<TokenizeOptions>,
): Promise<FtsToken[]> {
return await nativeTokenize(
query,
options?.baseTokenizer,
options?.language,
options?.maxTokenLength,
options?.lowercase,
options?.stem,
options?.removeStopWords,
options?.customStopWords,
options?.asciiFolding,
options?.ngramMinLength,
options?.ngramMaxLength,
options?.prefixOnly,
options?.analyzer,
options?.splitIdentifiers,
options?.splitOnNumerics,
options?.preserveOriginal,
options?.indexOperators,
);
}
/**
* Connect to a LanceDB instance at the given URI.
*
* Accepted formats:
*
* - `/path/to/database` - database on the local file system
* - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage
* - `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database
* @param {string} uri - The uri of the database. If the database uri starts
* with `db://` then it connects to LanceDB Enterprise or LanceDB Cloud (legacy).
* @see {@link ConnectionOptions} for more details on the URI format.
* @param options - The options to use when connecting to the database
* @example
* ```ts
* const conn = await connect("/path/to/database");
* ```
* @example
* ```ts
* const conn = await connect(
* "s3://bucket/path/to/database",
* {storageOptions: {timeout: "60s"}
* });
* ```
* @example
* Using with a header provider for per-request authentication:
* ```ts
* const provider = new StaticHeaderProvider({
* "X-API-Key": "my-key"
* });
* const conn = await connectWithHeaderProvider(
* "db://host:port",
* options,
* provider
* );
* ```
*/
export async function connect(
uri: string,
options?: Partial<ConnectionOptions>,
session?: Session,
headerProvider?:
| HeaderProvider
| (() => Record<string, string>)
| (() => Promise<Record<string, string>>),
): Promise<Connection>;
/**
* Connect to a LanceDB instance at the given URI.
*
* Accepted formats:
*
* - `/path/to/database` - database on the local file system
* - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage
* - `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database
* @param options - The options to use when connecting to the database
* @see {@link ConnectionOptions} for more details on the URI format.
* @example
* ```ts
* const conn = await connect({
* uri: "/path/to/database",
* storageOptions: {timeout: "60s"}
* });
* ```
*
* @example
* ```ts
* const session = Session.default();
* const conn = await connect({
* uri: "/path/to/database",
* session: session
* });
* ```
*/
export async function connect(
options: Partial<ConnectionOptions> & { uri: string },
): Promise<Connection>;
export async function connect(
uriOrOptions: string | (Partial<ConnectionOptions> & { uri: string }),
optionsOrSession?: Partial<ConnectionOptions> | Session,
sessionOrHeaderProvider?:
| Session
| HeaderProvider
| (() => Record<string, string>)
| (() => Promise<Record<string, string>>),
headerProvider?:
| HeaderProvider
| (() => Record<string, string>)
| (() => Promise<Record<string, string>>),
): Promise<Connection> {
let uri: string | undefined;
let finalOptions: Partial<ConnectionOptions> = {};
let finalHeaderProvider:
| HeaderProvider
| (() => Record<string, string>)
| (() => Promise<Record<string, string>>)
| undefined;
if (typeof uriOrOptions !== "string") {
// First overload: connect(options)
const { uri: uri_, ...opts } = uriOrOptions;
uri = uri_;
finalOptions = opts;
} else {
// Second overload: connect(uri, options?, session?, headerProvider?)
uri = uriOrOptions;
// Handle optionsOrSession parameter
if (optionsOrSession && "inner" in optionsOrSession) {
// Second param is session, so no options provided
finalOptions = {};
} else {
// Second param is options
finalOptions = (optionsOrSession as Partial<ConnectionOptions>) || {};
}
// Handle sessionOrHeaderProvider parameter
if (
sessionOrHeaderProvider &&
(typeof sessionOrHeaderProvider === "function" ||
"getHeaders" in sessionOrHeaderProvider)
) {
// Third param is header provider
finalHeaderProvider = sessionOrHeaderProvider as
| HeaderProvider
| (() => Record<string, string>)
| (() => Promise<Record<string, string>>);
} else {
// Third param is session, header provider is fourth param
finalHeaderProvider = headerProvider;
}
}
if (!uri) {
throw new Error("uri is required");
}
finalOptions = {
...finalOptions,
storageOptions: cleanseStorageOptions(finalOptions.storageOptions),
};
// Create native header provider if one was provided
let nativeProvider: NativeJsHeaderProvider | undefined;
if (finalHeaderProvider) {
if (typeof finalHeaderProvider === "function") {
nativeProvider = new NativeJsHeaderProvider(async () =>
finalHeaderProvider(),
);
} else if (
finalHeaderProvider &&
typeof finalHeaderProvider.getHeaders === "function"
) {
nativeProvider = new NativeJsHeaderProvider(async () =>
finalHeaderProvider.getHeaders(),
);
}
}
const nativeConn = await LanceDbConnection.new(
uri,
finalOptions,
nativeProvider,
);
return new LocalConnection(nativeConn);
}
/**
* Configuration for the built-in directory namespace (`"dir"`).
*
* The directory namespace stores tables under a single root path (local
* filesystem or object storage URI). See
* {@link https://docs.lancedb.com/namespaces} for the documented surface;
* less-common knobs live under {@link DirNamespaceConfig.extraProperties}.
*/
export interface DirNamespaceConfig {
/** Root path or URI containing the LanceDB tables. */
root: string;
/**
* Whether to maintain a namespace manifest at the root. Required for
* child namespaces. Defaults to true on the impl side.
*/
manifestEnabled?: boolean;
/**
* Additional raw properties passed verbatim to the namespace
* implementation (e.g. `storage.*`, `credential_vendor.*`). Typed
* fields above take precedence on key collision.
*/
extraProperties?: Record<string, string>;
}
/**
* Configuration for the built-in REST namespace (`"rest"`).
*
* The REST namespace talks to a remote catalog server over HTTP. See
* {@link https://docs.lancedb.com/namespaces} for the documented surface;
* less-common knobs (TLS, metrics) live under
* {@link RestNamespaceConfig.extraProperties}.
*/
export interface RestNamespaceConfig {
/** Catalog endpoint URL. */
uri: string;
/**
* HTTP headers forwarded with each request. Keys are passed through
* as-is (e.g. `"x-api-key"`, `"Authorization"`).
*/
headers?: Record<string, string>;
/**
* Additional raw properties passed verbatim to the namespace
* implementation (e.g. `tls.*`, `ops_metrics_enabled`, `delimiter`).
* Typed fields above take precedence on key collision.
*/
extraProperties?: Record<string, string>;
}
function dirConfigToProperties(
config: DirNamespaceConfig,
): Record<string, string> {
// Spread the whole input so that unknown keys (e.g. a raw `manifest_enabled`
// passed via the dynamic-impl path) flow through instead of being dropped.
// Typed transformations layer on top.
const { manifestEnabled, extraProperties, ...rest } = config;
const properties: Record<string, string> = {
...(extraProperties ?? {}),
...(rest as Record<string, string>),
};
if (manifestEnabled !== undefined) {
properties.manifest_enabled = String(manifestEnabled);
}
return properties;
}
function restConfigToProperties(
config: RestNamespaceConfig,
): Record<string, string> {
const { headers, extraProperties, ...rest } = config;
const properties: Record<string, string> = {
...(extraProperties ?? {}),
...(rest as Record<string, string>),
};
if (headers) {
for (const [name, value] of Object.entries(headers)) {
properties[`headers.${name}`] = value;
}
}
return properties;
}
/**
* Connect to a LanceDB database through a namespace.
*
* Unlike {@link connect}, which routes by URI scheme (local path vs.
* `db://`), `connectNamespace` always returns a namespace-backed
* connection. The `implName` selects the namespace implementation:
*
* - `"dir"` — directory namespace, configured with {@link DirNamespaceConfig}.
* - `"rest"` — remote REST catalog, configured with {@link RestNamespaceConfig}.
* - Any other string — full module path for a custom implementation,
* configured with a free-form string-keyed `properties` map.
*
* @example Typed dir namespace
* ```ts
* const db = await connectNamespace("dir", { root: "/path/to/db" });
* await db.createTable("users", [{ id: 1 }]);
* ```
*
* @example Typed REST namespace with auth headers
* ```ts
* const db = await connectNamespace("rest", {
* uri: "https://catalog.example.com",
* headers: { "x-api-key": process.env.CATALOG_KEY ?? "" },
* });
* ```
*
* @example Custom implementation with raw properties
* ```ts
* const db = await connectNamespace("my.custom.Namespace", {
* endpoint: "...",
* });
* ```
*/
export function connectNamespace(
implName: "dir",
config: DirNamespaceConfig,
options?: Partial<ConnectNamespaceOptions>,
): Promise<Connection>;
/**
* Connect through the built-in REST namespace.
*
* Configured with {@link RestNamespaceConfig}. See the function-level
* documentation above for the full surface, examples, and how this
* relates to {@link connect}.
*
* @example
* ```ts
* const db = await connectNamespace("rest", {
* uri: "https://catalog.example.com",
* headers: { "x-api-key": process.env.CATALOG_KEY ?? "" },
* });
* ```
*/
export function connectNamespace(
implName: "rest",
config: RestNamespaceConfig,
options?: Partial<ConnectNamespaceOptions>,
): Promise<Connection>;
/**
* Connect through a custom namespace implementation by full module path,
* configured with a free-form string-keyed `properties` map. Use the
* typed overloads above for the built-in `"dir"` and `"rest"` impls.
*
* See the function-level documentation above for examples and how this
* relates to {@link connect}.
*
* @example
* ```ts
* const db = await connectNamespace("my.custom.Namespace", {
* endpoint: "...",
* });
* ```
*/
export function connectNamespace(
implName: string,
properties: Record<string, string>,
options?: Partial<ConnectNamespaceOptions>,
): Promise<Connection>;
export async function connectNamespace(
implName: string,
configOrProperties:
| DirNamespaceConfig
| RestNamespaceConfig
| Record<string, string>,
options?: Partial<ConnectNamespaceOptions>,
): Promise<Connection> {
let properties: Record<string, string>;
if (implName === "dir") {
properties = dirConfigToProperties(
configOrProperties as DirNamespaceConfig,
);
} else if (implName === "rest") {
properties = restConfigToProperties(
configOrProperties as RestNamespaceConfig,
);
} else {
properties = configOrProperties as Record<string, string>;
}
const finalOptions: ConnectNamespaceOptions = {
...options,
storageOptions: cleanseStorageOptions(options?.storageOptions),
};
const nativeConn = await LanceDbConnection.newWithNamespace(
implName,
properties,
finalOptions,
);
return new LocalConnection(nativeConn);
}
export {
Catalog,
CatalogOptions,
DatabaseNames,
connectCatalog,
} from "./catalog";
export { Listing, ListingOptions } from "./listing";
export type { CompactionResult } from "./compaction";
export type { CleanupOptions, CleanupPlan, CleanupResult } from "./cleanup";
export type {
PrewarmDataPlan,
PrewarmDataResult,
PrewarmPruningSummary,
} from "./prewarm";
export type { QueryParameters, QueryParameterValue } from "./sql";