Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
docs(connectors): Python and Rust pages for Postgres, SQLite, Snowflake and Valkey (#2747)
LJ π₯₯π΄70a61fb84e1c
diff --git a/docs/src/content/docs/connectors/postgres.mdx b/docs/src/content/docs/connectors/postgres.mdxindex 18e3b715..82fd445a 100644--- a/docs/src/content/docs/connectors/postgres.mdx+++ b/docs/src/content/docs/connectors/postgres.mdx@@ -5,6 +5,11 @@ description: >Read Postgres tables via PgTableSource and write with declare_table_target() βautomatic schema inference, pgvector index management (ivfflat / hnsw), customtype overrides, and SQL attachments for triggers and indexes.+rust_description: >+ Read Postgres tables as a row stream via read_table and write with+ declare_table_target() β schema derivation from Rust structs, pgvector index+ management (ivfflat / hnsw), column type overrides, and SQL attachments for+ triggers and indexes.---import LangTabs from '../../../components/LangTabs.astro';@@ -30,6 +35,8 @@ The module is compiled with the `postgres` Cargo feature of the `cocoindex` crat</Fragment></LangTabs>+<Lang only="python">+:::note[Dependencies]This connector requires additional dependencies. Install with:@@ -39,9 +46,11 @@ pip install cocoindex[postgres]:::+</Lang>+## Connection setup-Create an [`asyncpg`](https://magicstack.github.io/asyncpg/current/) connection pool directly:+<Lang only="python">Create an [`asyncpg`](https://magicstack.github.io/asyncpg/current/) connection pool directly:</Lang><Lang only="rust">Open a `postgres::Database`:</Lang>{/* Rust: examples/rust/text_embedding/src/main.rs, rust/sdk/cocoindex/src/connectors/postgres.rs */}<LangTabs>@@ -70,10 +79,22 @@ The connector handles pgvector extension setup automatically when a table uses v## As source+<Lang only="python">+Use `PgTableSource` to read rows from a PostgreSQL table. It returns a `RowFetcher` that supports both synchronous and asynchronous iteration.### PgTableSource+</Lang>++<Lang only="rust">++Use `read_table` to read rows from a PostgreSQL table. It returns a stream of rows, read from one consistent snapshot of the table.++### read_table++</Lang>+{/* Rust: rust/sdk/cocoindex/src/connectors/postgres.rs */}<LangTabs><Fragment slot="python">@@ -98,13 +119,30 @@ class PgTableSource(Generic[RowT]):<Fragment slot="rust">```rust-pub async fn read_table<T: DeserializeOwned>(db: &Database, table_name: &str) -> Result<Vec<T>>+pub async fn read_table<T>(+ db: &Database,+ table_name: &str,+) -> Result<impl Stream<Item = Result<T>> + Send + 'static>+where+ T: serde::de::DeserializeOwned + Send + 'static-pub async fn read_table_with_options<T: DeserializeOwned>(+pub async fn read_table_with_options<T>(db: &Database,table_name: &str,options: ReadTableOptions,-) -> Result<Vec<T>>+) -> Result<impl Stream<Item = Result<T>> + Send + 'static>+where+ T: serde::de::DeserializeOwned + Send + 'static++pub async fn read_table_items<T, K, S>(+ db: &Database,+ table_name: &str,+ key_fn: K,+) -> Result<impl Stream<Item = Result<(StableKey, T)>> + Send + 'static>+where+ T: serde::de::DeserializeOwned + Send + 'static,+ K: Fn(&T) -> S + Send + 'static,+ S: IntoStableKeyimpl ReadTableOptions {pub fn new() -> Self@@ -113,13 +151,15 @@ impl ReadTableOptions {}```-The Rust source is a function, not a class. `read_table::<T>(db, table)` selects every column (`SELECT *`) and deserializes each row into `T`. `read_table_items(db, table, key_fn)` returns `(key, row)` pairs for `ctx.mount_each`.+`read_table_with_options` and `read_table_items_with_options` take a `ReadTableOptions` as well. `read_table_items` pairs each row with the key `key_fn` derives from it, ready for `ctx.mount_each` once collected.</Fragment></LangTabs>**Parameters:**+<Lang only="python">+- `pool` β An asyncpg connection pool.- `table_name` β Name of the table to read from.- `columns` β List of column names to select. If omitted with `row_type`, uses the record's field names. If omitted without `row_type`, uses `SELECT *`.@@ -127,16 +167,53 @@ The Rust source is a function, not a class. `read_table::<T>(db, table)` selects- `row_type` β Optional record type (dataclass, NamedTuple, or Pydantic model) for automatic row conversion. When provided, `columns` (if specified) must be a subset of the record's fields.- `row_factory` β Optional callable to transform each row dict. Mutually exclusive with `row_type`.+</Lang>++<Lang only="rust">++- `db` β The `postgres::Database` to read from.+- `table_name` β Name of the table to read from.+- `T` β The row type. Each row is deserialized into `T`.+- `ReadTableOptions::columns` β Column names to select. When not set, the query is `SELECT *`.+- `ReadTableOptions::pg_schema_name` β PostgreSQL schema name. When not set, the table name isn't schema-qualified, so the connection's `search_path` picks the schema (normally `public`).+- `key_fn` (`read_table_items` only) β Derives the stable key of a row.++</Lang>+### Row mapping+<Lang only="python">+By default, rows are returned as `dict[str, Any]`, with PostgreSQL types converted to Python types using [asyncpg's type conversion](https://magicstack.github.io/asyncpg/current/usage.html#type-conversion). You can configure automatic conversion to custom types using `row_type` or `row_factory`.-In Rust, the row type is the type parameter of `read_table::<T>`. `T` must implement `serde::Deserialize`; column names map to struct fields, and unknown columns are ignored. The Rust SDK has no `row_factory`: map the rows after reading them.+</Lang>++<Lang only="rust">++The row type is the type parameter of `read_table::<T>`. `T` must implement `serde::Deserialize`; column names map to struct fields, and unknown columns are ignored. Use `serde_json::Value` as `T` to get each row as a JSON object.++<RustNote>+There is no `row_factory`. Read the rows into a struct, then map them with the stream's or an iterator's `map`.+</RustNote>++</Lang>++<Lang only="python">#### Using `row_type`Pass a record type (dataclass, NamedTuple, or Pydantic model) to automatically convert rows. When `columns` is omitted, the record's field names are used:+</Lang>++<Lang only="rust">++#### Choosing the row type++Name the row type on the result, or as `read_table::<T>`. Select fewer columns with `ReadTableOptions::columns`:++</Lang>+{/* Rust: examples/rust/postgres_source/src/main.rs, rust/sdk/cocoindex/tests/postgres_source.rs */}<LangTabs><Fragment slot="python">@@ -171,25 +248,34 @@ struct SourceProduct {amount: i64,}-let products: Vec<SourceProduct> = postgres::read_table(source_db, "source_products").await?;+let products: Vec<SourceProduct> = postgres::read_table(source_db, "source_products")+ .await?+ .try_collect()+ .await?;-// Only some columns, from a schema other than the search path+// Only some columnslet mut rows: Vec<SourceNameOnly> = postgres::read_table_with_options(&db,&src_table,postgres::ReadTableOptions::new().columns(["name"]),)+.await?+.try_collect().await?;```+`try_collect` comes from `futures::TryStreamExt`.+Derive `MemoInput` as well when the row is an argument of a memoized function.</Fragment></LangTabs>+<Lang only="python">+#### Using `row_factory`-For custom transformations, pass a callable. The Rust SDK has no `row_factory`: read the rows into a struct and map them with an iterator.+For custom transformations, pass a callable:```pythonsource = postgres.PgTableSource(@@ -200,9 +286,11 @@ source = postgres.PgTableSource()```+</Lang>+### Iterating rows-`fetch_rows()` returns a `RowFetcher` that supports both sync and async iteration:+<Lang only="python">`fetch_rows()` returns a `RowFetcher` that supports both sync and async iteration:</Lang><Lang only="rust">`read_table` returns a stream of `Result<T>`. Consume it with the `futures` stream adapters, or collect it:</Lang>{/* Rust: examples/rust/postgres_source/src/main.rs */}<LangTabs>@@ -222,11 +310,16 @@ async for row in source.fetch_rows():<Fragment slot="rust">```rust-let products: Vec<SourceProduct> = postgres::read_table(source_db, "source_products").await?;+use futures::TryStreamExt as _;++let products: Vec<SourceProduct> = postgres::read_table(source_db, "source_products")+ .await?+ .try_collect()+ .await?;println!("read {} source product(s)", products.len());```-`read_table` reads the whole table in one `REPEATABLE READ, READ ONLY` transaction and returns a `Vec`. The Rust SDK does not stream rows through a cursor.+`read_table` reads the whole table in one `REPEATABLE READ, READ ONLY` transaction, so the rows come from one consistent snapshot. The rows stream from the server as the stream is consumed: at most 256 rows are buffered ahead of the consumer. Dropping the stream ends the read.</Fragment></LangTabs>@@ -269,6 +362,7 @@ async def app_main(pool: asyncpg.Pool) -> None:```rustuse cocoindex::connectors::postgres;use cocoindex::prelude::*;+use futures::TryStreamExt as _;// Source database.cocoindex::context_key!(static SOURCE_DB: postgres::Database);@@ -283,25 +377,35 @@ struct SourceProduct {amount: i64,}-/// Compute the derived fields + embedding for one source row. Memoized by the-/// row content, so unchanged rows skip the embedding work on re-runs.-#[cocoindex::function(memo)]-async fn process_product(ctx: &Ctx, product: SourceProduct) -> Result<OutputProduct> {+/// Derive and embed one product, declaring its output row. Memoized on the+/// source row: an unchanged row keeps its output without re-running.+#[cocoindex::function(memo, memo_key(table = skip))]+async fn process_product(+ ctx: &Ctx,+ product: SourceProduct,+ table: postgres::TableTarget,+) -> Result<()> {// ...}async fn app_main(ctx: Ctx) -> Result<()> {+ let target =+ postgres::mount_table_target(&ctx, &DB, TABLE, output_schema()?, Some(PG_SCHEMA)).await?;+let source_db = ctx.get_key(&SOURCE_DB)?;- let products: Vec<SourceProduct> = postgres::read_table(source_db, "source_products").await?;+ let products: Vec<SourceProduct> = postgres::read_table(source_db, "source_products")+ .await?+ .try_collect()+ .await?;- let outputs = use_mount_each!(+ // One processing component per source row.+ mount_each!(products.into_iter().map(|p| (format!("{}|{}", p.product_category, p.product_name), p)),- |product| process_product(ctx, product)+ |product| process_product(ctx, product, target)).await?;- // ...Ok(())}```@@ -319,7 +423,7 @@ The `postgres` connector provides target state APIs for writing rows to tables.#### Setting up a connection-Create a `ContextKey[asyncpg.Pool]` to identify your connection pool, then provide the pool directly in your lifespan:+<Lang only="python">Create a `ContextKey[asyncpg.Pool]` to identify your connection pool, then provide the pool directly in your lifespan:</Lang><Lang only="rust">Declare a context key for the `postgres::Database`, then provide the database in your lifespan:</Lang>:::noteThe key name is load-bearing across runs β it's the stable identity CocoIndex uses to track managed rows. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity) before renaming.@@ -416,13 +520,15 @@ pub async fn mount_table_target_with_options() -> Result<TableTarget>```-`managed_by` is set through `ManagedTargetOptions::user_managed()` on the `_with_options` variants (`table_target_with_options`, `mount_table_target_with_options`). The default is system-managed.+Each function has a `_with_options` variant (`declare_table_target_with_options`, `mount_table_target_with_options`, `table_target_with_options`) that takes a `ManagedTargetOptions`. `ManagedTargetOptions::user_managed()` sets a user-managed table; the default is system-managed.</Fragment></LangTabs>**Parameters:**+<Lang only="python">+- `db` β A `ContextKey[asyncpg.Pool]` identifying the connection pool to use.- `table_name` β Name of the table.- `table_schema` β Schema definition including columns and primary key (see [Table Schema](#table-schema-from-python-class)).@@ -431,12 +537,25 @@ pub async fn mount_table_target_with_options(**Returns:** A pending `TableTarget`. Use the convenience wrapper `await postgres.mount_table_target(PG_DB, table_name, table_schema)` to resolve.-In Rust, `declare_table_target` returns a handle whose rows resolve when the current component commits; `mount_table_target(...).await?` returns a handle that accepts rows at once.+</Lang>++<Lang only="rust">++- `ctx` β The current component's context.+- `db` β The `ContextKey<postgres::Database>` identifying the database to use.+- `table_name` β Name of the table.+- `table_schema` β Schema definition including columns and primary key (see [Table Schema](#table-schema-from-a-rust-struct)).+- `pg_schema_name` β Optional PostgreSQL schema name. When `None`, the table name isn't schema-qualified, so the connection's `search_path` picks the schema (normally `public`).+- `options` (`_with_options` variants) β `ManagedTargetOptions`: whether CocoIndex manages the table lifecycle (the default) or assumes it exists (`ManagedTargetOptions::user_managed()`).++**Returns:** A `TableTarget`. From `declare_table_target`, its rows resolve when the current component commits. From `mount_table_target(...).await?`, it accepts rows at once.++</Lang>:::caution[One table, one key]CocoIndex identifies a table by its key: the `db` key, `pg_schema_name` and `table_name`. Two different keys are two different tables to CocoIndex, even when PostgreSQL resolves them to the same table (see [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity)). Two cases are easy to miss:-- `pg_schema_name=None` and `pg_schema_name="public"` are two different keys, even when `search_path` makes them reach the same table.+- <Lang only="python">`pg_schema_name=None` and `pg_schema_name="public"` are two different keys, even when `search_path` makes them reach the same table.</Lang><Lang only="rust">`pg_schema_name: None` and `Some("public")` are the same key, even when `search_path` makes `None` reach a table in another schema. Two targets in that case collide on one key.</Lang>- PostgreSQL truncates a table name longer than 63 bytes, so two long names that share their first 63 bytes are one table.Declare each table through one key only. Switching a table from one form to the other changes its key: CocoIndex then cleans up the table it tracked under the old key, which is the same table.@@ -474,7 +593,9 @@ table.declare_row(&ctx, &row)?;**Parameters:**-- `row` β A row object (dict, dataclass, NamedTuple, or Pydantic model). Must include all primary key columns. In Rust, any `Serialize` value whose fields match the schema's columns.+- `row` β <Lang only="python">A row object (dict, dataclass, NamedTuple, or Pydantic model). Must include all primary key columns.</Lang><Lang only="rust">Any `Serialize` value that serializes to an object whose entries are the table's columns. Extra entries are ignored, and a missing entry is written as NULL. It must include all primary key columns.</Lang>++CocoIndex writes rows in batches: each upsert or delete statement carries up to 2,000 rows, and the statements of a batch run concurrently over the pool.#### Vector indexes (attachment)@@ -524,7 +645,7 @@ pub struct VectorIndexOptions {</Fragment></LangTabs>-The actual PostgreSQL index is named `{table_name}__vector__{name}`. PostgreSQL truncates a name longer than 63 bytes. If two vector indexes declared on the same `TableTarget` get the same name after truncation, `declare_vector_index` raises a `ValueError`.+The actual PostgreSQL index is named `{table_name}__vector__{name}`. PostgreSQL truncates a name longer than 63 bytes. <Lang only="python">If two vector indexes declared on the same `TableTarget` get the same name after truncation, `declare_vector_index` raises a `ValueError`.</Lang><Lang only="rust">`declare_vector_index` does not check for two names that become the same after truncation: keep the full index names distinct in their first 63 bytes.</Lang>**Parameters:**@@ -641,10 +762,22 @@ table.declare_sql_command_attachment(</Fragment></LangTabs>+<Lang only="python">+### Table schema: from Python classDefine the table structure using a Python class (dataclass, NamedTuple, or Pydantic model):+</Lang>++<Lang only="rust">++### Table schema: from a Rust struct++Define the table structure with a struct that derives `SchemaFields` and `Serialize`:++</Lang>+{/* Rust: rust/sdk/cocoindex/src/connectors/postgres.rs */}<LangTabs><Fragment slot="python">@@ -679,17 +812,28 @@ impl TableSchema {}```-The Rust row type is a struct that derives `SchemaFields` (and `Serialize`). `TableSchema::from_row::<Row>(primary_key)` derives the columns. Python's `column_overrides` become builder calls on the derived schema: `with_vector_schema` or `with_vector_dim` for a vector column, `with_column_type` for a type override.+`TableSchema::from_row::<Row>(primary_key)` derives the columns. Builder calls on the derived schema override single columns: `with_vector_schema` or `with_vector_dim` for a vector column, `with_column_type` for a type override.</Fragment></LangTabs>**Parameters:**+<Lang only="python">+- `record_type` β A record type whose fields define table columns.- `primary_key` β List of column names forming the primary key.- `column_overrides` β Optional per-column overrides for type mapping or vector configuration.+</Lang>++<Lang only="rust">++- `T` β A struct whose fields define table columns.+- `primary_key` β Column names forming the primary key.++</Lang>+**Example:**{/* Rust: examples/rust/postgres_source/src/main.rs */}@@ -738,41 +882,82 @@ fn output_schema() -> Result<postgres::TableSchema> {</Fragment></LangTabs>+<Lang only="python">+Python types are automatically mapped to PostgreSQL types:-| Python Type | Rust Type | PostgreSQL Type |-|-------------|-----------|-----------------|-| `bool` | `bool` | `boolean` |-| `int` | `i64` (`i16`: `smallint`, `i32`: `integer`) | `bigint` |-| `float` | `f64` (`f32`: `real`) | `double precision` |-| `decimal.Decimal` | `Decimal` | `numeric` |-| `str` | `String` | `text` |-| `bytes` | `Vec<u8>` | `bytea` |-| `uuid.UUID` | `Uuid` | `uuid` |-| `datetime.date` | `NaiveDate` | `date` |-| `datetime.time` | `NaiveTime` | `time with time zone` |-| `datetime.datetime` | `DateTime`, `NaiveDateTime` | `timestamp with time zone` |-| `datetime.timedelta` | `Duration` | `interval` |-| `list`, `dict`, nested structs | other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `jsonb` |-| `NDArray` (with vector schema) | `Vec<f32>` with `#[coco(vector)]` (`half` for `halfvec`) | `vector(n)` or `halfvec(n)` |--Unsigned Rust integers map to the next signed width (`u32` to `bigint`, `u64` to `bigint`); a value above `i64::MAX` is rejected when the row is written.+| Python Type | PostgreSQL Type |+|-------------|-----------------|+| `bool` | `boolean` |+| `int` | `bigint` |+| `float` | `double precision` |+| `decimal.Decimal` | `numeric` |+| `str` | `text` |+| `bytes` | `bytea` |+| `uuid.UUID` | `uuid` |+| `datetime.date` | `date` |+| `datetime.time` | `time with time zone` |+| `datetime.datetime` | `timestamp with time zone` |+| `datetime.timedelta` | `interval` |+| `list`, `dict`, nested structs | `jsonb` |+| `NDArray` (with vector schema) | `vector(n)` or `halfvec(n)` |++</Lang>++<Lang only="rust">++Rust field types are automatically mapped to PostgreSQL types:++| Rust Type | PostgreSQL Type |+|-----------|-----------------|+| `bool` | `boolean` |+| `i64` (`i16`: `smallint`, `i32`: `integer`) | `bigint` |+| `f64` (`f32`: `real`) | `double precision` |+| `Decimal` | `numeric` |+| `String` | `text` |+| `Vec<u8>` | `bytea` |+| `Uuid` | `uuid` |+| `NaiveDate` | `date` |+| `NaiveTime` | `time with time zone` |+| `DateTime`, `NaiveDateTime` | `timestamp with time zone` |+| `Duration` | `interval` |+| other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `jsonb` |+| `Vec<f32>` with `#[coco(vector)]` (`half` for `halfvec`) | `vector(n)` or `halfvec(n)` |++Unsigned integers map to the next signed width (`u32` to `bigint`, `u64` to `bigint`); a value above `i64::MAX` is rejected when the row is written.++</Lang>:::note[U+0000 (NUL) in strings]U+0000 (NUL) is a valid Unicode codepoint, but Postgres cannot store it β neither in `text`-family columns nor inside strings in `jsonb` (the `\u0000` escape is rejected at parse time). CocoIndex automatically strips U+0000 from strings before writing to Postgres, recursively for nested strings and dict keys in `jsonb` payloads. For example, `"Hello\0World"` is written as `"HelloWorld"`.:::+<Lang only="python">+To override the default mapping, provide a `PgType` or `VectorSchemaProvider` via:- **Type annotation** β using `typing.Annotated` on the field- **`column_overrides`** β passing overrides when constructing `TableSchema`-In Rust, the field attribute `#[coco(type = "β¦")]` plays the role of the annotation, and `with_column_type` / `with_vector_schema` play the role of `column_overrides`.-#### PgTypeUse `PgType` to specify a custom PostgreSQL type:+</Lang>++<Lang only="rust">++To override the default mapping, use:++- **Field attribute** β `#[coco(type = "β¦")]` or `#[coco(vector = N)]` on the struct field+- **Schema builder calls** β `with_column_type`, `with_vector_schema` or `with_vector_dim` on the `TableSchema` derived with `from_row`++#### Column types++Set a custom PostgreSQL type on a field:++</Lang>+{/* Rust: rust/sdk/cocoindex/src/row_schema.rs, rust/sdk/cocoindex/tests/postgres_target.rs */}<LangTabs><Fragment slot="python">@@ -791,7 +976,7 @@ class MyRow:Or via `column_overrides`:```python-schema = postgres.TableSchema(+schema = await postgres.TableSchema.from_class(MyRow,primary_key=["id"],column_overrides={@@ -824,15 +1009,29 @@ let table_schema = postgres::TableSchema::from_row::<ProviderRow>(["id"])?.with_column_type("title", "varchar(40)")?;```-`#[coco(type = "β¦")]` applies to every connector the struct is used with; `with_column_type` applies to one schema. Python's `PgType` encoder has no counterpart: encode a value with `#[serde(serialize_with = "β¦")]` on the field.+`#[coco(type = "β¦")]` applies to every connector the struct is used with; `with_column_type` applies to one schema and keeps the column's nullability.++<RustNote>+There is no `PgType` encoder. A field's `Serialize` impl produces the value that is bound: `uuid`, `chrono`, `rust_decimal`, `std::net::IpAddr` (for `inet`) and `Vec<f32>` (for pgvector) serialize to what their columns take. For another form, use `#[serde(serialize_with = "β¦")]` on the field.+</RustNote></Fragment></LangTabs>#### VectorSchemaProvider+<Lang only="python">+For `NDArray` fields, a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider) annotation specifies the vector dimension and dtype. The connector has built-in pgvector support and automatically creates the extension when needed. See [Vector Schema](../common_resources/vector_schema#vectorschemaprovider) for the full list of annotation options (`ContextKey`, embedder instance, or explicit `VectorSchema`).+</Lang>++<Lang only="rust">++For a `#[coco(vector)]` field, a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider) passed to `with_vector_schema` specifies the vector dimension and element type. The connector has built-in pgvector support and automatically creates the extension when needed.++</Lang>+{/* Rust: examples/rust/text_embedding/src/main.rs */}<LangTabs><Fragment slot="python">diff --git a/docs/src/content/docs/connectors/snowflake.mdx b/docs/src/content/docs/connectors/snowflake.mdxindex ec0db4aa..371d46fe 100644--- a/docs/src/content/docs/connectors/snowflake.mdx+++ b/docs/src/content/docs/connectors/snowflake.mdx@@ -4,6 +4,9 @@ toc_max_heading_level: 4description: >Write CocoIndex target rows into Snowflake tables with managed DDL, MERGEupserts, deletes, and automatic mapping from Python row types.+rust_description: >+ Write CocoIndex target rows into Snowflake tables with managed DDL, MERGE+ upserts, deletes, and automatic mapping from Rust row types.---import LangTabs from '../../../components/LangTabs.astro';@@ -26,11 +29,13 @@ use cocoindex::connectors::snowflake::{};```-The Rust SDK needs the `snowflake` Cargo feature of the `cocoindex` crate. The Rust connector speaks the Snowflake SQL REST API directly.+The module is compiled with the `snowflake` Cargo feature of the `cocoindex` crate. Snowflake has no official Rust client, so the connector speaks the HTTP protocol of the official connectors directly: a password login that yields a session token, then statements with server-side `?` bindings.</Fragment></LangTabs>+<Lang only="python">+:::note[Install]Install the optional Snowflake dependency before using this connector:@@ -39,10 +44,21 @@ pip install cocoindex[snowflake]```:::+</Lang>+## Connection setup+<Lang only="python">+Create a `ContextKey[snowflake.ConnectionConfig]` to identify the Snowflake connection, then provide it in your lifespan:+</Lang>+<Lang only="rust">++Declare a context key for a `SnowflakeConnection` to identify the Snowflake connection, then provide the connection on the environment builder:++</Lang>+:::noteThe key name is load-bearing across runs - it's the stable identity CocoIndex uses to track managed rows. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity) before renaming.:::@@ -105,13 +121,22 @@ let app = cocoindex::Environment::builder().await?;```-`SnowflakeConnection::new(config)` makes no request until the first statement. The connection is `Clone`; `conn.query(sql).await?` runs a statement and returns its rows as JSON objects.+`SnowflakeConnection::new(config)` makes no request until the first statement. Each batch of statements logs in, runs and closes its own session. The connection is cheap to clone; `conn.query(sql).await?` runs a statement in a fresh session and returns its rows as JSON objects keyed by column name.</Fragment></LangTabs>+<Lang only="python">+### ConnectionConfig+</Lang>+<Lang only="rust">++### SnowflakeConfig++</Lang>+{/* Rust: rust/sdk/cocoindex/src/connectors/snowflake.rs */}<LangTabs><Fragment slot="python">@@ -186,6 +211,21 @@ def declare_table_target(<Fragment slot="rust">```rust+pub fn declare_table_target(+ ctx: &Ctx,+ conn: &ContextKey<SnowflakeConnection>,+ table_name: impl Into<String>,+ table_schema: TableSchema,+) -> Result<TableTarget>++pub fn declare_table_target_with_options(+ ctx: &Ctx,+ conn: &ContextKey<SnowflakeConnection>,+ table_name: impl Into<String>,+ table_schema: TableSchema,+ options: SnowflakeTableOptions,+) -> Result<TableTarget>+pub async fn mount_table_target(ctx: &Ctx,conn: &ContextKey<SnowflakeConnection>,@@ -210,21 +250,27 @@ pub struct SnowflakeTableOptions {}```-`declare_table_target` and `declare_table_target_with_options` take the same arguments and declare the table in the current component. `ManagedBy::User` is Python's `managed_by="user"`.+`declare_table_target*` declares the table in the current component; its rows resolve when the component commits. `mount_table_target*` mounts the table first, so you can declare rows at once. `table_target` and `table_target_with_options` build the table target state without declaring it.</Fragment></LangTabs>**Parameters:**-- `db` - A `ContextKey[ConnectionConfig]` identifying the connection to use.+- <Lang only="python">`db` - A `ContextKey[ConnectionConfig]`</Lang><Lang only="rust">`conn` - A `&ContextKey<SnowflakeConnection>`</Lang> identifying the connection to use.- `table_name` - Name of the table.- `table_schema` - Schema definition including columns and primary key.- `database` - Optional Snowflake database name.- `schema` - Optional Snowflake schema name.-- `managed_by` - Whether CocoIndex manages the table lifecycle (`"system"`) or assumes it exists (`"user"`).+- `managed_by` - Whether CocoIndex manages the table lifecycle (<Lang only="python">`"system"`</Lang><Lang only="rust">`ManagedBy::System`, the default</Lang>) or assumes it exists (<Lang only="python">`"user"`</Lang><Lang only="rust">`ManagedBy::User`</Lang>).++When <Lang only="python">`managed_by="system"`</Lang><Lang only="rust">`managed_by` is `ManagedBy::System`</Lang>, CocoIndex creates the database, schema, and table if needed. Table changes use Snowflake DDL, and row changes use `MERGE` for upserts.++<Lang only="rust">++A batch of row changes runs in one session: rows are `MERGE`d and deleted by primary key in statements of up to 4,000 bindings each, so a batch takes a few statements, not one per row.-When `managed_by="system"`, CocoIndex creates the database, schema, and table if needed. Table changes use Snowflake DDL, and row changes use `MERGE` for upserts.+</Lang>### Rows@@ -256,12 +302,23 @@ The row serializes to an object whose keys are column names; keys outside the sc**Parameters:**-- `row` - A row object (dict, dataclass, NamedTuple, or Pydantic model). Must include all primary key columns.+- `row` - <Lang only="python">A row object (dict, dataclass, NamedTuple, or Pydantic model).</Lang><Lang only="rust">Any `Serialize` value whose entries are the table's columns.</Lang> Must include all primary key columns.++<Lang only="python">## Table schema: from Python classDefine the table structure using a Python class:+</Lang>+<Lang only="rust">++## Table schema: from a Rust struct++Define the table structure using a Rust struct that derives `SchemaFields`:++</Lang>+{/* Rust: examples/rust/snowflake_target/src/main.rs */}<LangTabs><Fragment slot="python">@@ -308,30 +365,67 @@ let schema = TableSchema::from_row::<SnowflakeOrder>(["order_id"])?;</Fragment></LangTabs>+<Lang only="python">+Python types are automatically mapped to Snowflake column types:-| Python Type | Rust Type | Snowflake Type |-|-------------|-----------|----------------|-| `bool` | `bool` | `BOOLEAN` |-| `int` | `i16`, `i32`, `i64` (and the unsigned widths) | `NUMBER` |-| `float` | `f32`, `f64` | `FLOAT` |-| `decimal.Decimal` | `rust_decimal::Decimal` | `NUMBER` |-| `str` | `String` | `VARCHAR` |-| `bytes` | `Vec<u8>` | `BINARY` |-| `uuid.UUID` | `uuid::Uuid` | `VARCHAR` |-| `datetime.date` | `chrono::NaiveDate` | `DATE` |-| `datetime.time` | `chrono::NaiveTime` | `TIME` |-| `datetime.datetime` | `chrono::DateTime`, `chrono::NaiveDateTime` | `TIMESTAMP_TZ` |-| `datetime.timedelta` | `std::time::Duration` | `NUMBER` |-| `list`, `dict`, nested structs | other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `VARIANT` |-| | `#[coco(vector)] Vec<f32>` | `ARRAY` |--`VARIANT` values are JSON-serialized and written with `PARSE_JSON`. An `Option<T>` field is a nullable column; every other Rust field is `NOT NULL`.+| Python Type | Snowflake Type |+|-------------|----------------|+| `bool` | `BOOLEAN` |+| `int` | `NUMBER` |+| `float` | `FLOAT` |+| `decimal.Decimal` | `NUMBER` |+| `str` | `VARCHAR` |+| `bytes` | `BINARY` |+| `uuid.UUID` | `VARCHAR` |+| `datetime.date` | `DATE` |+| `datetime.time` | `TIME` |+| `datetime.datetime` | `TIMESTAMP_TZ` |+| `datetime.timedelta` | `NUMBER` |+| `list`, `dict`, nested structs | `VARIANT` |++`VARIANT` values are JSON-serialized and written with `PARSE_JSON`.++</Lang>+<Lang only="rust">++Rust types are automatically mapped to Snowflake column types:++| Rust Type | Snowflake Type |+|-----------|----------------|+| `bool` | `BOOLEAN` |+| `i16`, `i32`, `i64` (and the unsigned widths) | `NUMBER` |+| `f32`, `f64` | `FLOAT` |+| `rust_decimal::Decimal` | `NUMBER` |+| `String` | `VARCHAR` |+| `Vec<u8>` | `BINARY` |+| `uuid::Uuid` | `VARCHAR` |+| `chrono::NaiveDate` | `DATE` |+| `chrono::NaiveTime` | `TIME` |+| `chrono::DateTime`, `chrono::NaiveDateTime` | `TIMESTAMP_TZ` |+| `std::time::Duration` | `NUMBER` |+| other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `VARIANT` |+| `#[coco(vector)] Vec<f32>` | `ARRAY` |++`VARIANT` and `ARRAY` values are JSON-serialized and written with `PARSE_JSON`. An `Option<T>` field is a nullable column; every other field is `NOT NULL`.++</Lang>++<Lang only="python">### SnowflakeTypeUse `SnowflakeType` to specify a custom Snowflake type and optional encoder:+</Lang>+<Lang only="rust">++### Custom column types++Use `#[coco(type = "β¦")]` to specify a custom Snowflake type:++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/snowflake_target.rs; #[coco(type)] from rust/sdk/cocoindex_macros/src/lib.rs */}<LangTabs><Fragment slot="python">@@ -361,13 +455,26 @@ struct ProductRow {}```-`#[coco(type = "β¦")]` sets the column type verbatim. The Rust SDK has no per-column `encoder`: a value is written as it serializes with serde. Explicit columns are also possible with `TableSchema::new(columns, primary_key)?` and `ColumnDef::new("VARIANT").parse_json()`; a Rust `ColumnDef` is nullable unless `.not_null()` is called.+`#[coco(type = "β¦")]` sets the column type verbatim. A value is written as it serializes with serde; for another form, put `#[serde(serialize_with = "β¦")]` on the field. Explicit columns are also possible with `TableSchema::new(columns, primary_key)?` and `ColumnDef::new("VARIANT").parse_json()`; a `ColumnDef` is nullable unless `.not_null()` is called.</Fragment></LangTabs>+<Lang only="python">+You can also pass `column_overrides` when constructing the schema:+</Lang>+<Lang only="rust">++You can also replace the type of one column on the derived schema, for this schema only. `with_column_type` keeps the column's derived nullability and takes the `parse_json` flag of the `ColumnDef` you pass:++</Lang>++{/* Rust: rust/sdk/cocoindex/src/connectors/snowflake.rs (TableSchema::with_column_type) */}+<LangTabs>+<Fragment slot="python">+```pythonschema = await snowflake.TableSchema.from_class(ProductRow,@@ -378,6 +485,19 @@ schema = await snowflake.TableSchema.from_class()```+</Fragment>+<Fragment slot="rust">++```rust+use cocoindex::connectors::snowflake::{ColumnDef, TableSchema};++let schema = TableSchema::from_row::<ProductRow>(["id"])?+ .with_column_type("id", ColumnDef::new("NUMBER(38, 0)"))?;+```++</Fragment>+</LangTabs>+## Example{/* Rust: examples/rust/snowflake_target/src/main.rs */}@@ -436,7 +556,7 @@ for row in &rows {</Fragment></LangTabs>-See `examples/snowflake_target` for a runnable project, and `examples/rust/snowflake_target` for the Rust one.+See <Lang only="python">`examples/snowflake_target`</Lang><Lang only="rust">`examples/rust/snowflake_target`</Lang> for a runnable project.## Identifier handlingdiff --git a/docs/src/content/docs/connectors/sqlite.mdx b/docs/src/content/docs/connectors/sqlite.mdxindex ab5e2ab7..dd3b1d26 100644--- a/docs/src/content/docs/connectors/sqlite.mdx+++ b/docs/src/content/docs/connectors/sqlite.mdx@@ -31,6 +31,8 @@ The module is compiled with the `sqlite` Cargo feature of the `cocoindex` crate.</LangTabs>:::note[Vector Support]+<Lang only="python">+For vector operations, install the sqlite-vec extension:```bash@@ -38,14 +40,32 @@ pip install cocoindex[sqlite]```Note: The default SQLite library bundled with macOS does not support extensions. Use Homebrew Python (`brew install python`) or build SQLite with extension support.++</Lang>+<Lang only="rust">++For vector operations, have the sqlite-vec loadable library (`vec0`) on disk and name it when you connect, with `Database::connect_with_vec`.++</Lang>:::## Connection setup+<Lang only="python">+### connect`connect()` creates a managed SQLite connection with sensible defaults, including automatic sqlite-vec loading and thread-safe access.+</Lang>+<Lang only="rust">++### Database::connect++`Database::connect()` opens a SQLite connection pool with sensible defaults. `connect_with_vec()` also loads sqlite-vec.++</Lang>+{/* Rust: rust/sdk/cocoindex/src/connectors/sqlite.rs */}<LangTabs><Fragment slot="python">@@ -67,16 +87,22 @@ def connect(impl Database {pub async fn connect(path: &str) -> Result<Self>pub async fn connect_with_vec(path: &str, vec_extension: &str) -> Result<Self>+ pub async fn connect_with_options(path: &str, options: ConnectOptions) -> Result<Self>pub fn from_pool(state_id: impl Into<String>, pool: SqlitePool) -> Selfpub fn pool(&self) -> &SqlitePool}-```-`Database::connect(path)` opens the file, creating it when missing, through an [`sqlx`](https://docs.rs/sqlx) pool of one connection. `connect_with_vec(path, vec_extension)` also loads the `sqlite-vec` extension and fails when it cannot be loaded; `vec_extension` names the loadable library, as a path or a bare name such as `"vec0"`. The Rust SDK has no `load_vec="auto"`: a Rust build has no `sqlite-vec` package to find the library in, so the caller names it. `timeout` and `**kwargs` have no counterpart; build a `SqlitePool` yourself and wrap it with `from_pool` for other options.+pub struct ConnectOptions {+ pub busy_timeout: Duration, // default DEFAULT_BUSY_TIMEOUT (5 seconds)+ pub vec_extension: Option<String>, // default None+}+```</Fragment></LangTabs>+<Lang only="python">+**Parameters:**- `database` β Path to the SQLite database file, or `":memory:"` for an in-memory database.@@ -89,9 +115,26 @@ impl Database {**Returns:** A `ManagedConnection` with thread-safe access and extension tracking.+</Lang>+<Lang only="rust">++**Parameters:**++- `path` β Path to the SQLite database file. The file is created when it is missing.+- `vec_extension` (`connect_with_vec`, `ConnectOptions`) β The sqlite-vec loadable library, as a path with or without the platform suffix, or a bare name such as `"vec0"` to search the system library path. Connecting fails when the library cannot be loaded.+- `busy_timeout` (`ConnectOptions`) β How long to wait for a lock held by another connection or process. The default is five seconds.++**Returns:** A `Database`, an [`sqlx`](https://docs.rs/sqlx) pool of one connection. It is cheap to clone.++</Lang>++<RustNote>+There is no `load_vec="auto"`: a Rust build has no `sqlite-vec` package to find the library in, so you name the library. To set other connection options, build a `SqlitePool` yourself and wrap it with `Database::from_pool(state_id, pool)`.+</RustNote>+**Example:**-{/* Rust: examples/rust/files_to_sqlite/src/main.rs, rust/sdk/SHOWCASE.md (verified against sqlite.rs) */}+{/* Rust: examples/rust/files_to_sqlite/src/main.rs, rust/sdk/SHOWCASE.md, rust/sdk/cocoindex/tests/sqlite_target.rs (verified against sqlite.rs) */}<LangTabs><Fragment slot="python">@@ -112,17 +155,26 @@ managed_conn = sqlite.connect("mydb.sqlite", load_vec=False)let db = sqlite::Database::connect(&db_path).await?;// With vector support, naming the sqlite-vec library:let db = sqlite::Database::connect_with_vec("app.db", "/usr/local/lib/vec0").await?;+// With a lock wait other than five seconds:+let db = sqlite::Database::connect_with_options(+ "app.db",+ sqlite::ConnectOptions {+ busy_timeout: std::time::Duration::from_millis(1234),+ vec_extension: None,+ },+)+.await?;```</Fragment></LangTabs>+<Lang only="python">+### ManagedConnectionA wrapper around `sqlite3.Connection` that provides thread-safe access and tracks loaded extensions. The connection uses autocommit mode internally.-The Rust counterpart is `sqlite::Database`. It has no `transaction()`, `readonly()` or `loaded_extensions`: use `db.pool()` (an `sqlx::SqlitePool`) to run your own queries, and drop the `Database` to close it.-**Methods:**- `transaction()` β Context manager that acquires a lock and executes within a transaction (`BEGIN`...`COMMIT`/`ROLLBACK`). Use for write operations that should be atomic.@@ -133,6 +185,20 @@ The Rust counterpart is `sqlite::Database`. It has no `transaction()`, `readonly- `loaded_extensions` β A read-only `Set[str]` of loaded extension names (e.g., `"sqlite-vec"`).+</Lang>+<Lang only="rust">++### Database++`sqlite::Database` is a pool that holds one connection, because SQLite is a single-writer engine. The pool serializes the statements that run on it. To run your own SQL on the same database, use `db.pool()`, an `sqlx::SqlitePool`:++- `db.pool().begin()` starts a transaction for writes that must be atomic.+- `db.pool()` runs a read directly.++Drop the last clone of the `Database` to close it.++</Lang>+## As targetThe `sqlite` connector provides target state APIs for writing rows to tables. With it, CocoIndex tracks what rows should exist and automatically handles upserts and deletions.@@ -141,8 +207,17 @@ The `sqlite` connector provides target state APIs for writing rows to tables. Wi#### Setting up a connection+<Lang only="python">+Create a `ContextKey[sqlite.ManagedConnection]` to identify your SQLite connection, then provide it in your lifespan using `sqlite.managed_connection()`:+</Lang>+<Lang only="rust">++Declare a context key for a `sqlite::Database` to identify your SQLite connection, then provide the connection on the environment builder:++</Lang>+:::noteThe key name is load-bearing across runs β it's the stable identity CocoIndex uses to track managed rows. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity) before renaming.:::@@ -209,6 +284,21 @@ def declare_table_target(<Fragment slot="rust">```rust+pub fn declare_table_target(+ ctx: &Ctx,+ db: &ContextKey<Database>,+ table_name: impl Into<String>,+ table_schema: TableSchema,+) -> Result<TableTarget>++pub fn declare_table_target_with_options(+ ctx: &Ctx,+ db: &ContextKey<Database>,+ table_name: impl Into<String>,+ table_schema: TableSchema,+ options: SqliteTableOptions,+) -> Result<TableTarget>+pub async fn mount_table_target(ctx: &Ctx,db: &ContextKey<Database>,@@ -230,21 +320,30 @@ pub struct SqliteTableOptions {}```-`declare_table_target` and `declare_table_target_with_options` have the same arguments and return a handle whose rows resolve when the current component commits. `managed_by` and `virtual_table_def` go in `SqliteTableOptions`.+`declare_table_target*` returns a handle whose rows resolve when the current component commits. `mount_table_target*` mounts the table first, so you can declare rows at once. `table_target` and `table_target_with_options` build the table target state without declaring it, to compose with other target states. `managed_by` and `virtual_table_def` go in `SqliteTableOptions`.</Fragment></LangTabs>**Parameters:**-- `db` β A `ContextKey[ManagedConnection]` identifying the connection to use.+- `db` β <Lang only="python">A `ContextKey[ManagedConnection]`</Lang><Lang only="rust">A `&ContextKey<Database>`</Lang> identifying the connection to use.- `table_name` β Name of the table.-- `table_schema` β Schema definition including columns and primary key (see [Table Schema](#table-schema-from-python-class)).-- `managed_by` β Whether CocoIndex manages the table lifecycle (`"system"`) or assumes it exists (`"user"`).+- `table_schema` β Schema definition including columns and primary key (see <Lang only="python">[Table Schema](#table-schema-from-python-class)</Lang><Lang only="rust">[Table Schema](#table-schema-from-a-rust-struct)</Lang>).+- `managed_by` β Whether CocoIndex manages the table lifecycle (<Lang only="python">`"system"`</Lang><Lang only="rust">`ManagedBy::System`, the default</Lang>) or assumes it exists (<Lang only="python">`"user"`</Lang><Lang only="rust">`ManagedBy::User`</Lang>).- `virtual_table_def` β Optional `Vec0TableDef` to create a vec0 virtual table instead of a regular table.+<Lang only="python">+**Returns:** A pending `TableTarget`. Use the convenience wrapper `await sqlite.mount_table_target(SQLITE_DB, table_name, table_schema)` to resolve.+</Lang>+<Lang only="rust">++**Returns:** A `TableTarget`. As an argument of `mount_each!` or `use_mount!`, it fingerprints by its table name; the schema is not part of the component memo.++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/sqlite_target.rs */}<LangTabs><Fragment slot="python">@@ -309,12 +408,38 @@ table.declare_row(ctx, &row)?;**Parameters:**-- `row` β A row object (dict, dataclass, NamedTuple, or Pydantic model). Must include all primary key columns with non-`None` values. Dict rows may omit nullable non-primary-key columns; omitted values are written as SQL `NULL`. In Rust, any `Serialize` value whose fields match the schema's columns.+<Lang only="python">++- `row` β A row object (dict, dataclass, NamedTuple, or Pydantic model). Must include all primary key columns with non-`None` values. Dict rows may omit nullable non-primary-key columns; omitted values are written as SQL `NULL`.++</Lang>+<Lang only="rust">++- `row` β Any `Serialize` value that serializes to an object whose entries are the table's columns. Extra entries are ignored, and missing ones are written as SQL `NULL`. Each value is bound by its column's declared type.++</Lang>++<Lang only="rust">++A batch of row changes is written in one transaction, in a few statements: a regular table takes multi-row `VALUES` upserts and `IN` deletes with bound parameters, as many rows per statement as SQLite's bind limit allows. A `vec0` table takes one row per statement.++</Lang>++<Lang only="python">### Table schema: from Python classDefine the table structure using a Python class (dataclass, NamedTuple, or Pydantic model):+</Lang>+<Lang only="rust">++### Table schema: from a Rust struct++Define the table structure using a Rust struct that derives `SchemaFields`:++</Lang>+{/* Rust: rust/sdk/cocoindex/src/connectors/sqlite.rs */}<LangTabs><Fragment slot="python">@@ -349,17 +474,32 @@ impl TableSchema {}```-The Rust row type is a struct that derives `SchemaFields` (and `Serialize`). Python's `column_overrides` become builder calls on the derived schema.+The row type also derives `Serialize`, so that its values can be declared as rows.</Fragment></LangTabs>+<Lang only="python">+**Parameters:**- `record_type` β A record type whose fields define table columns.- `primary_key` β List of column names forming the primary key.- `column_overrides` β Optional per-column overrides for type mapping or vector configuration.+</Lang>+<Lang only="rust">++**Parameters and builder methods:**++- `T` β A struct that derives `SchemaFields`; its fields define table columns.+- `primary_key` β The column names that form the primary key.+- `with_vector_dim(field, dim)` β Sets the dimension `N` of a `float[N]` vector column.+- `with_vector_schema(field, provider)` β Takes the dimension of a vector column from a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider), typically the embedder that fills it. For an embedder held in the context, pass `ctx.get_key(&EMBEDDER)?`.+- `with_column_type(field, sqlite_type)` β Replaces the SQLite type of one column and keeps its nullability.++</Lang>+**Example:**{/* Rust: examples/rust/files_to_sqlite/src/main.rs, rust/sdk/cocoindex/tests/sqlite_target.rs */}@@ -407,35 +547,74 @@ let schema = sqlite::TableSchema::from_row::<DocRow>(["id"])?</Fragment></LangTabs>+<Lang only="python">+Python types are automatically mapped to SQLite type affinities:-| Python Type | Rust Type | SQLite Type |-|-------------|-----------|-------------|-| `bool` | `bool` | `INTEGER` (0/1) |-| `int` | `i16`, `i32`, `i64` | `INTEGER` |-| `float` | `f32`, `f64` | `REAL` |-| `decimal.Decimal` | `Decimal` | `TEXT` |-| `str` | `String` | `TEXT` |-| `bytes` | `Vec<u8>` | `BLOB` |-| `uuid.UUID` | `Uuid` | `TEXT` |-| `datetime.date` | `NaiveDate` | `TEXT` (ISO format) |-| `datetime.time` | `NaiveTime` | `TEXT` (ISO format) |-| `datetime.datetime` | `DateTime`, `NaiveDateTime` | `TEXT` (ISO format) |-| `datetime.timedelta` | `Duration` | `REAL` (total seconds) |-| `list`, `dict`, nested structs | other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `TEXT` (JSON) |-| `NDArray` (with vector schema) | `Vec<f32>` with `#[coco(vector)]` | `float[N]` (sqlite-vec type, e.g., `float[384]`) |+| Python Type | SQLite Type |+|-------------|-------------|+| `bool` | `INTEGER` (0/1) |+| `int` | `INTEGER` |+| `float` | `REAL` |+| `decimal.Decimal` | `TEXT` |+| `str` | `TEXT` |+| `bytes` | `BLOB` |+| `uuid.UUID` | `TEXT` |+| `datetime.date` | `TEXT` (ISO format) |+| `datetime.time` | `TEXT` (ISO format) |+| `datetime.datetime` | `TEXT` (ISO format) |+| `datetime.timedelta` | `REAL` (total seconds) |+| `list`, `dict`, nested structs | `TEXT` (JSON) |+| `NDArray` (with vector schema) | `float[N]` (sqlite-vec type, e.g., `float[384]`) |To override the default mapping, provide a `SqliteType` or `VectorSchemaProvider` via:- **Type annotation** β using `typing.Annotated` on the field- **`column_overrides`** β passing overrides when constructing `TableSchema`-In Rust, the field attribute `#[coco(type = "β¦")]` plays the role of the annotation, and `with_column_type` / `with_vector_schema` play the role of `column_overrides`.+</Lang>+<Lang only="rust">++Rust types are automatically mapped to SQLite type affinities:++| Rust Type | SQLite Type |+|-----------|-------------|+| `bool` | `INTEGER` (0/1) |+| `i16`, `i32`, `i64` | `INTEGER` |+| `f32`, `f64` | `REAL` |+| `Decimal` | `TEXT` |+| `String` | `TEXT` |+| `Vec<u8>` | `BLOB` |+| `Uuid` | `TEXT` |+| `NaiveDate` | `TEXT` (ISO format) |+| `NaiveTime` | `TEXT` (ISO format) |+| `DateTime`, `NaiveDateTime` | `TEXT` (ISO format) |+| `Duration` | `REAL` (total seconds) |+| other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `TEXT` (JSON) |+| `Vec<f32>` with `#[coco(vector)]` | `float[N]` (sqlite-vec type, e.g., `float[384]`) |++To override the default mapping, use:++- **A field attribute** β `#[coco(type = "β¦")]` on the field+- **A builder method** β `with_column_type` or `with_vector_schema` on the derived schema++</Lang>++<Lang only="python">#### SqliteTypeUse `SqliteType` to specify a custom SQLite type and optional encoder:+</Lang>+<Lang only="rust">++#### Custom column types++Use `#[coco(type = "β¦")]` to specify a custom SQLite type:++</Lang>+{/* Rust: rust/sdk/cocoindex/src/row_schema.rs, rust/sdk/SHOWCASE.md (verified against sqlite.rs) */}<LangTabs><Fragment slot="python">@@ -454,7 +633,7 @@ class MyRow:Or via `column_overrides`:```python-schema = sqlite.TableSchema(+schema = await sqlite.TableSchema.from_class(MyRow,primary_key=["id"],column_overrides={@@ -485,15 +664,24 @@ let schema = sqlite::TableSchema::from_row::<DocEmbedding>(["id"])?.with_column_type("text", "VARCHAR(2000)")?;```-Python's encoder has no counterpart: a Rust row is encoded by its `Serialize` impl, so put `#[serde(serialize_with = "β¦")]` on the field.+A row is encoded by its `Serialize` impl. The defaults of `uuid`, `chrono` and `rust_decimal` serialize to the text these columns take, and a collection serializes to JSON text. For another form, put `#[serde(serialize_with = "β¦")]` on the field.</Fragment></LangTabs>#### VectorSchemaProvider+<Lang only="python">+For `NDArray` fields, a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider) annotation specifies the vector dimension and dtype. Vectors are stored as BLOBs in sqlite-vec compatible float32 format. See [Vector Schema](../common_resources/vector_schema#vectorschemaprovider) for the full list of annotation options (`ContextKey`, embedder instance, or explicit `VectorSchema`).+</Lang>+<Lang only="rust">++For a `Vec<f32>` field marked `#[coco(vector)]`, pass a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider) to `with_vector_schema` to set the vector dimension. sqlite-vec columns are `float[N]` whatever the element type. Vectors are stored as BLOBs in sqlite-vec compatible float32 format.++</Lang>+### Table schema: explicit column definitionsDefine columns directly using `ColumnDef`:@@ -574,7 +762,7 @@ The `vec0` module from sqlite-vec provides optimized vector storage for similari- Exactly one `INTEGER` primary key column- At least one `float[N]` vector column-- The sqlite-vec extension must be loaded (`load_vec=True`)+- The sqlite-vec extension must be loaded (<Lang only="python">`load_vec=True`</Lang><Lang only="rust">`Database::connect_with_vec`</Lang>)#### Vec0TableDef@@ -615,8 +803,17 @@ pub struct Vec0TableDef {#### Creating vec0 virtual tables+<Lang only="python">+Pass `virtual_table_def` to `declare_table_target()`:+</Lang>+<Lang only="rust">++Set `virtual_table_def` in the `SqliteTableOptions` of `declare_table_target_with_options()` or `mount_table_target_with_options()`:++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/sqlite_target.rs */}<LangTabs><Fragment slot="python">@@ -813,7 +1010,12 @@ See `examples/rust/files_to_sqlite` for the full program.### Example: Vec0 Virtual Table-For Rust, see the `vec0` snippet under [Creating vec0 virtual tables](#creating-vec0-virtual-tables): `connect_with_vec`, then `mount_table_target_with_options` with a `Vec0TableDef`.+<Lang only="rust">++See the `vec0` snippet under [Creating vec0 virtual tables](#creating-vec0-virtual-tables): `connect_with_vec`, then `mount_table_target_with_options` with a `Vec0TableDef`. `rust/sdk/cocoindex/tests/sqlite_target.rs` has the full program, which also searches the table.++</Lang>+<Lang only="python">```pythonimport cocoindex as coco@@ -875,3 +1077,5 @@ async def app_main() -> None:for doc in docs:table.declare_row(row=doc)```++</Lang>diff --git a/docs/src/content/docs/connectors/valkey.mdx b/docs/src/content/docs/connectors/valkey.mdxindex b6ea77b1..91f57dbf 100644--- a/docs/src/content/docs/connectors/valkey.mdx+++ b/docs/src/content/docs/connectors/valkey.mdx@@ -32,19 +32,32 @@ The module is compiled with the `valkey` Cargo feature of the `cocoindex` crate.</LangTabs>:::note[Dependencies]+<Lang only="python">+This connector requires additional dependencies. Install with:```bashpip install cocoindex[valkey]```+</Lang>+Requires a Valkey server with the [valkey-search](https://github.com/valkey-io/valkey-search) module loaded.:::## Connection setup+<Lang only="python">+`create_client_config()` creates a configuration for connecting to Valkey.+</Lang>+<Lang only="rust">++`Valkey::connect()` and `Valkey::connect_with_config()` open a connection to Valkey.++</Lang>+{/* Rust: rust/sdk/cocoindex/src/connectors/valkey.rs */}<LangTabs><Fragment slot="python">@@ -80,11 +93,13 @@ impl Valkey {}```-`Valkey::connect_with_config(ClientConfig { .. })` is the counterpart of `create_client_config` plus `GlideClient.create`. `Valkey::connect("redis://localhost:6379")` takes a URI. For anything `ClientConfig` does not cover (`**kwargs` in Python: client certificates, a username, a database number), build a `redis::Client` yourself and pass it to `from_client`.+`Valkey::connect("redis://localhost:6379")` takes a URI. `Valkey::connect_with_config(ClientConfig { .. })` takes the fields below. For anything `ClientConfig` does not cover (client certificates, a username, a database number), build a `redis::Client` yourself and pass it to `from_client`.</Fragment></LangTabs>+<Lang only="python">+**Parameters:**- `host` β Valkey server host (default: `"localhost"`).@@ -98,6 +113,23 @@ For advanced configurations not covered by these parameters, construct `GlideCli**Returns:** A `GlideClientConfiguration` instance.+</Lang>+<Lang only="rust">++**`ClientConfig` fields:**++- `host` β Valkey server host (default: `"localhost"`).+- `port` β Valkey server port (default: `6379`).+- `password` β Optional authentication password. The `Debug` output of `ClientConfig` shows it as redacted.+- `use_tls` β Whether to use TLS for the connection (default: `false`).+- `client_name` β Client name for the connection, set with `CLIENT SETNAME` and visible in `CLIENT LIST` and monitoring dashboards (default: `Some("cocoindex_vector_store")`). Pass `None` to set no name.++**Returns:** A `Valkey` handle. It is cheap to clone: the multiplexed connection is shared, and every command or pipeline runs on a clone of it.++The handle's `state_id()` is the server's address and database number as a URI, for example `redis://localhost:6379`. It never holds the username or password, so a credential does not leak into memo dependencies or the target-state store, and rotating a credential does not invalidate them. With `from_client(state_id, client)`, you choose the `state_id`: name the server, not a secret.++</Lang>+**Example:**{/* Rust: rust/sdk/cocoindex/tests/valkey_target.rs, rust/sdk/cocoindex/src/connectors/valkey.rs (ClientConfig doctest) */}@@ -138,8 +170,17 @@ The `valkey` connector provides target state APIs for writing documents to searc#### Setting up a connection+<Lang only="python">+Create a `ContextKey[GlideClient]` to identify your Valkey client, then provide it in your lifespan:+</Lang>+<Lang only="rust">++Declare a context key for a `valkey::Valkey` to identify your Valkey connection, then provide the connection on the environment builder:++</Lang>+:::noteThe key name is load-bearing across runs β it's the stable identity CocoIndex uses to track managed indexes. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity) before renaming.:::@@ -213,6 +254,14 @@ pub fn declare_index_target(schema: IndexSchema,) -> Result<IndexTarget>+pub fn declare_index_target_with_options(+ ctx: &Ctx,+ db: &ContextKey<Valkey>,+ index_name: impl Into<String>,+ schema: IndexSchema,+ options: ManagedTargetOptions,+) -> Result<IndexTarget>+pub async fn mount_index_target(ctx: &Ctx,db: &ContextKey<Valkey>,@@ -220,29 +269,50 @@ pub async fn mount_index_target(schema: IndexSchema,) -> Result<IndexTarget>-pub fn index_target_with_options(+pub async fn mount_index_target_with_options(ctx: &Ctx,db: &ContextKey<Valkey>,index_name: impl Into<String>,schema: IndexSchema,options: ManagedTargetOptions,-) -> Result<TargetState<IndexSpec>>+) -> Result<IndexTarget>```-`managed_by` is set with `ManagedTargetOptions::user_managed()` on `index_target_with_options`, which returns the raw `TargetState` for `mount_target` / `declare_target_state_with_child`. `declare_index_target` returns a handle whose documents resolve when the current component commits; `mount_index_target(...).await?` returns a handle that accepts documents at once.+`declare_index_target*` returns a handle whose documents resolve when the current component commits; `mount_index_target*(...).await?` returns a handle that accepts documents at once. `managed_by` is set with `ManagedTargetOptions::user_managed()` on the `*_with_options` forms. `index_target` and `index_target_with_options` return the raw `TargetState`, to compose with `mount_target` or `declare_target_state_with_child`.</Fragment></LangTabs>+<Lang only="rust">++{/* Rust: rust/sdk/cocoindex/tests/valkey_target.rs */}++```rust+let index = valkey::mount_index_target_with_options(+ &ctx,+ &VK,+ index_name,+ schema().await,+ ManagedTargetOptions::user_managed(),+)+.await?;+```++</Lang>+**Parameters:**-- `db` β A `ContextKey[GlideClient]` identifying the Valkey client to use.+- `db` β <Lang only="python">A `ContextKey[GlideClient]`</Lang><Lang only="rust">A `&ContextKey<Valkey>`</Lang> identifying the Valkey client to use.- `index_name` β Name of the search index.- `schema` β Schema definition specifying vector configuration (see [Index Schema](#index-schema)).-- `managed_by` β `ManagedBy.SYSTEM` (default): CocoIndex creates and drops the index automatically. `ManagedBy.USER`: assumes the index already exists and never drops it.+- `managed_by` β <Lang only="python">`ManagedBy.SYSTEM`</Lang><Lang only="rust">`ManagedBy::System`</Lang> (default): CocoIndex creates and drops the index automatically. <Lang only="python">`ManagedBy.USER`</Lang><Lang only="rust">`ManagedBy::User`</Lang>: assumes the index already exists and never drops it.++<Lang only="python">**Returns:** A pending `IndexTarget`. Use the convenience wrapper `await valkey.mount_index_target(VALKEY_DB, index_name, schema)` to resolve.+</Lang>+#### Documents (child states)Once an `IndexTarget` is resolved, declare documents to be upserted:@@ -269,26 +339,53 @@ impl IndexTarget {pub struct Document {pub id: String,pub vector: Vec<f32>,- pub payload: Option<BTreeMap<String, String>>,+ pub payload: Option<BTreeMap<String, PayloadValue>>,+}++pub enum PayloadValue {+ Str(String),+ Int(i64),+ Float(f64),}let mut payload = BTreeMap::new();payload.insert("text".to_string(), text.to_string());index.declare_document(&ctx, Document::new(id, vector).with_payload(payload))?;++// A numeric payload value for a NUMERIC field:+index.declare_document(+ &ctx,+ Document::new("d3", vec![0.7, 0.8, 0.9]).with_payload([+ ("text", PayloadValue::from("priced")),+ ("price", PayloadValue::from(42i64)),+ ]),+)?;```-The Rust payload holds string values only.+`with_payload` takes any iterator of `(key, value)` pairs whose values convert into `PayloadValue` (`String`, `&str`, `i64` or `f64`).</Fragment></LangTabs>**Parameters:**+<Lang only="python">+- `document` β A `valkey.Document` containing:- `id` β Document ID (string)- `vector` β Vector data (list of floats or numpy array)- `payload` β Optional metadata dict (values must be str, int, or float). The key `vector` is reserved for the vector field (see [Data storage](#data-storage)), so a payload with that key raises a `ValueError`.+</Lang>+<Lang only="rust">++- `document` β A `valkey::Document` containing:+ - `id` β Document ID (string)+ - `vector` β Vector data (`Vec<f32>`)+ - `payload` β Optional metadata map (values are text, `i64` or `f64`). The key `vector` is reserved for the vector field (see [Data storage](#data-storage)), so `declare_document` returns an error for a payload with that key.++</Lang>+### Index schemaDefine vector configuration for an index using `IndexSchema`.@@ -326,7 +423,7 @@ IndexSchema::create(.await?```-`fields` is required in Rust; pass `vec![]` for none. `FieldDef::new(name, FieldType::Text | Tag | Numeric)` and `.sortable()` describe an indexed payload field.+Pass `vec![]` for no indexed payload fields. `FieldDef::new(name, FieldType::Text | Tag | Numeric)` and `.sortable()` describe an indexed payload field.</Fragment></LangTabs>@@ -334,7 +431,7 @@ IndexSchema::create(**Parameters:**- `vectors` β A `VectorDef` specifying the vector field configuration.-- `fields` β Optional list of `FieldDef` for indexed payload fields (enables search/filtering). A `FieldDef` named `vector` raises a `ValueError`: that name is reserved for the vector field.+- `fields` β <Lang only="python">Optional list</Lang><Lang only="rust">List</Lang> of `FieldDef` for indexed payload fields (enables search/filtering). A `FieldDef` named `vector` <Lang only="python">raises a `ValueError`</Lang><Lang only="rust">is an error</Lang>: that name is reserved for the vector field.#### VectorDef@@ -373,32 +470,58 @@ impl<'a> VectorDef<'a> {**Parameters:**-- `schema` β A `VectorSchemaProvider` or `ContextKey` that defines vector dimensions.-- `distance` β Distance metric for similarity search (default: `"cosine"`).-- `algorithm` β Vector index algorithm (default: `"hnsw"`).+- `schema` β A `VectorSchemaProvider`<Lang only="python"> or `ContextKey`</Lang> that defines vector dimensions.+- `distance` β Distance metric for similarity search (default: <Lang only="python">`"cosine"`</Lang><Lang only="rust">`Distance::Cosine`</Lang>).+- `algorithm` β Vector index algorithm (default: <Lang only="python">`"hnsw"`</Lang><Lang only="rust">`VectorAlgorithm::Hnsw`</Lang>).#### VectorSchemaProvider-The `schema` field of `VectorDef` accepts a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider), a `ContextKey`, or an explicit `VectorSchema` to specify the vector dimension and dtype. See [Vector Schema](../common_resources/vector_schema#vectorschemaprovider) for details. In Rust, pass `&VectorSchema::f32(n)` or a reference to an embedder; for one held in the context, `ctx.get_key(&EMBEDDER)?`.+<Lang only="python">++The `schema` field of `VectorDef` accepts a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider), a `ContextKey`, or an explicit `VectorSchema` to specify the vector dimension and dtype. See [Vector Schema](../common_resources/vector_schema#vectorschemaprovider) for details.++</Lang>+<Lang only="rust">++The `schema` field of `VectorDef` borrows a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider) to specify the vector dimension and dtype: an explicit `&VectorSchema::f32(n)` or a reference to an embedder. For an embedder held in the context, pass `ctx.get_key(&EMBEDDER)?`. See [Vector Schema](../common_resources/vector_schema#vectorschemaprovider) for details.++</Lang>### Distance metricsThe `distance` parameter in `VectorDef` specifies the similarity metric:+<Lang only="python">+- `"cosine"` β Cosine similarity (default)- `"l2"` β Euclidean distance (L2)- `"ip"` β Inner product (dot product)-In Rust: `Distance::Cosine`, `Distance::L2`, `Distance::Ip`.+</Lang>+<Lang only="rust">++- `Distance::Cosine` β Cosine similarity (default)+- `Distance::L2` β Euclidean distance (L2)+- `Distance::Ip` β Inner product (dot product)++</Lang>### Index algorithmsThe `algorithm` parameter specifies the vector indexing strategy:+<Lang only="python">+- `"hnsw"` β Hierarchical Navigable Small World graph (default, best for most use cases)- `"flat"` β Brute-force flat index (exact results, slower for large datasets)-In Rust: `VectorAlgorithm::Hnsw`, `VectorAlgorithm::Flat`.+</Lang>+<Lang only="rust">++- `VectorAlgorithm::Hnsw` β Hierarchical Navigable Small World graph (default, best for most use cases)+- `VectorAlgorithm::Flat` β Brute-force flat index (exact results, slower for large datasets)++</Lang>### Data storage@@ -410,6 +533,12 @@ Documents are stored as Valkey HASH keys with a prefix pattern:The search index is created with `FT.CREATE ON HASH PREFIX 1 {index_name}:` to automatically index all documents with the matching prefix.+<Lang only="rust">++A batch of document changes is sent in pipelines: one `DEL` for every deleted key, then the upserts in pipelines of up to 1,000 documents. Each document is written as its own `MULTI` `DEL` `HSET` `EXEC` transaction, so no stale payload field survives an update and a document is never half written. A batch of `n` documents costs `1 + ceil(n / 1000)` round trips, not `n`.++</Lang>+### Example{/* Rust: rust/sdk/cocoindex/tests/valkey_target.rs */}@@ -510,14 +639,16 @@ index.declare_document(&ctx, doc("d1", vec![0.1, 0.2, 0.3], "hello"))?;index.declare_document(&ctx, doc("d2", vec![0.4, 0.5, 0.6], "world"))?;```-There is no Rust example program for Valkey yet; `rust/sdk/cocoindex/tests/valkey_target.rs` is the end-to-end reference.+There is no example program for Valkey yet; `rust/sdk/cocoindex/tests/valkey_target.rs` is the end-to-end reference.</Fragment></LangTabs>## Vector search-The connector focuses on writing documents to Valkey. For vector search queries, use the Valkey GLIDE client directly. The Rust SDK has no search helper for Valkey: run `FT.SEARCH` through the `redis` crate.+<Lang only="python">++The connector focuses on writing documents to Valkey. For vector search queries, use the Valkey GLIDE client directly.```pythonfrom glide import GlideClient@@ -536,3 +667,10 @@ results = await ft.search(options=FtSearchOptions(params={"query_vec": query_vec}),)```++</Lang>+<Lang only="rust">++The connector focuses on writing documents to Valkey and has no search helper. For vector search queries, run `FT.SEARCH` through the `redis` crate directly.++</Lang>