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
feat(rust-sdk): batched SQL table writes and streaming Postgres reads (#2729)
LJ π₯₯π΄1e103fb8e66c
diff --git a/examples/rust/postgres_source/Cargo.lock b/examples/rust/postgres_source/Cargo.lockindex db14bb13..fe8a6c40 100644--- a/examples/rust/postgres_source/Cargo.lock+++ b/examples/rust/postgres_source/Cargo.lock@@ -2788,6 +2788,7 @@ version = "0.1.0"dependencies = ["cocoindex","dotenvy",+ "futures","serde","sqlx","tokio",diff --git a/examples/rust/postgres_source/Cargo.toml b/examples/rust/postgres_source/Cargo.tomlindex df8bf116..c2e453e9 100644--- a/examples/rust/postgres_source/Cargo.toml+++ b/examples/rust/postgres_source/Cargo.toml@@ -9,6 +9,7 @@ edition = "2024"cocoindex = { path = "../../../rust/sdk/cocoindex", features = ["postgres", "fastembed"] }tokio = { version = "1", features = ["full"] }serde = { version = "1", features = ["derive"] }+futures = "0.3"# Query path (pgvector similarity); target writes go through cocoindex::connectors::postgres.sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio",diff --git a/examples/rust/postgres_source/src/main.rs b/examples/rust/postgres_source/src/main.rsindex 554ae2ca..dcfc6576 100644--- a/examples/rust/postgres_source/src/main.rs+++ b/examples/rust/postgres_source/src/main.rs@@ -20,6 +20,7 @@use cocoindex::connectors::postgres;use cocoindex::ops::sentence_transformers::SentenceTransformerEmbedder;use cocoindex::prelude::*;+use futures::TryStreamExt as _;use sqlx::Row;use sqlx::postgres::{PgPool, PgPoolOptions};@@ -122,7 +123,10 @@ async fn app_main(ctx: Ctx) -> Result<()> {)?;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?;println!("read {} source product(s)", products.len());// One processing component per source row: each row's output syncs anddiff --git a/rust/sdk/SHOWCASE.md b/rust/sdk/SHOWCASE.mdindex c6efef7d..c4820444 100644--- a/rust/sdk/SHOWCASE.md+++ b/rust/sdk/SHOWCASE.md@@ -757,6 +757,10 @@ let schema = sqlite::TableSchema::from_row::<DocEmbedding>(["id"])?.with_column_type("text", "VARCHAR(2000)")?;```+BigQuery and Snowflake take a `ColumnDef`, so an override can also write the+value through `PARSE_JSON`:+`.with_column_type("payload", bigquery::ColumnDef::new("JSON").parse_json())?`.+To encode a value differently on the way to the store, put`#[serde(serialize_with = "β¦")]` on the field.@@ -767,6 +771,16 @@ SQLite `vec0` tables need the `sqlite-vec` extension in the connection.let db = sqlite::Database::connect_with_vec("app.db", "/usr/local/lib/vec0").await?;```+`connect_with_options` sets the lock wait (`busy_timeout`, five seconds by+default) and the extension together.++Postgres and SQLite targets write a batch of rows in a few statements, not one+per row: Postgres sends parameterized `unnest` statements of 2,000 rows each,+run concurrently, and SQLite sends multi-row `VALUES` statements as large as+its bind limit allows. `postgres::read_table` streams a table's rows from one+snapshot instead of loading them all; collect them for `mount_each!` with+`try_collect()`.+Doris has a query builder for vector search over a table CocoIndex maintains:```rustdiff --git a/rust/sdk/cocoindex/src/connectors/bigquery.rs b/rust/sdk/cocoindex/src/connectors/bigquery.rsindex 814a1c96..336ee6e3 100644--- a/rust/sdk/cocoindex/src/connectors/bigquery.rs+++ b/rust/sdk/cocoindex/src/connectors/bigquery.rs@@ -717,6 +717,21 @@ impl TableSchema {Self::new(columns, primary_key)}+ /// Replace the type of one column of a schema derived from a row with+ /// `column`'s type and its [`ColumnDef::parse_json`] flag (Python's+ /// `column_overrides={"col": BigQueryType("JSON", use_parse_json=True)}`), keeping the column's derived+ /// nullability.+ pub fn with_column_type(mut self, field_name: &str, column: ColumnDef) -> Result<Self> {+ validate_sql_type(&column.bigquery_type)?;+ let def = self+ .columns+ .get_mut(field_name)+ .ok_or_else(|| crate::row_schema::unknown_column_error("BigQuery", field_name))?;+ def.bigquery_type = column.bigquery_type;+ def.use_parse_json = column.use_parse_json;+ Ok(self)+ }+/// Columns in DDL order: primary-key columns first (in key order), then the/// rest by name.fn ordered_columns(&self) -> Vec<(&String, &ColumnDef)> {@@ -1948,6 +1963,35 @@ mod tests {);}+ #[test]+ fn column_type_override_changes_type_and_parse_json() {+ #[derive(crate::SchemaFields)]+ #[allow(dead_code)]+ struct Row {+ id: i64,+ payload: Option<String>,+ }+ let schema = TableSchema::from_row::<Row>(["id"])+ .unwrap()+ .with_column_type("payload", ColumnDef::new("JSON").parse_json())+ .unwrap();+ // The derived nullability stays.+ assert_eq!(+ schema.columns()["payload"],+ ColumnDef::new("JSON").parse_json()+ );+ let row = json!({"id": 1, "payload": "{\"a\":1}"});+ let (sql, _) =+ merge_statement("`t`", &schema, &[row.as_object().unwrap().clone()]).unwrap();+ assert!(sql.contains("PARSE_JSON(@p1) AS `payload`"), "{sql}");+ assert!(+ TableSchema::from_row::<Row>(["id"])+ .unwrap()+ .with_column_type("missing", ColumnDef::new("JSON"))+ .is_err()+ );+ }+#[test]fn merge_statement_uses_parse_json_and_named_params() {let row = json!({"id": 1, "payload": {"b": 2, "a": [1]}});diff --git a/rust/sdk/cocoindex/src/connectors/postgres.rs b/rust/sdk/cocoindex/src/connectors/postgres.rsindex cb01bf36..2bf3c8b2 100644--- a/rust/sdk/cocoindex/src/connectors/postgres.rs+++ b/rust/sdk/cocoindex/src/connectors/postgres.rs@@ -7,13 +7,18 @@//!//! Use [`table_target`] to build a composable target state, [`declare_table_target`]//! inside the current component, or [`mount_table_target`] when rows must be-//! declared immediately. [`read_table`] and [`read_table_items`] read source rows-//! for use with `Ctx::mount_each`.+//! declared immediately. [`read_table`] and [`read_table_items`] stream source+//! rows for use with `Ctx::mount_each`.+//!+//! Rows are written in batches: one parameterized `unnest` statement per+//! chunk of [`ROWS_PER_STATEMENT`] rows (see [`RowStatements`]), the statements+//! of a batch running concurrently over the pool.use std::collections::{BTreeMap, BTreeSet};use std::sync::Arc;use cocoindex_utils::fingerprint::Fingerprint;+use futures::{SinkExt as _, Stream, StreamExt as _};use serde::{Deserialize, Serialize};use serde_json::{Map, Value as JsonValue};use sqlx::PgPool;@@ -369,7 +374,26 @@ pub fn declare_table_target(table_schema: TableSchema,pg_schema_name: Option<&str>,) -> Result<TableTarget> {- let ts = table_target(ctx, db, table_name, table_schema, pg_schema_name)?;+ declare_table_target_with_options(+ ctx,+ db,+ table_name,+ table_schema,+ pg_schema_name,+ ManagedTargetOptions::default(),+ )+}++/// [`declare_table_target`] with explicit [`ManagedTargetOptions`] (`managed_by`).+pub fn declare_table_target_with_options(+ ctx: &Ctx,+ db: &ContextKey<Database>,+ table_name: impl Into<String>,+ table_schema: TableSchema,+ pg_schema_name: Option<&str>,+ options: ManagedTargetOptions,+) -> Result<TableTarget> {+ let ts = table_target_with_options(ctx, db, table_name, table_schema, pg_schema_name, options)?;let spec = ts.value().clone();let rows = declare_target_state_with_child::<TableSpec, RowState>(ctx, ts)?;Ok(table_target_handle(spec, rows))@@ -425,6 +449,15 @@ impl TableTarget {&self.table_name}+ /// Declare a row. `row` serializes to an object whose entries are the+ /// table's columns (extra entries are ignored, missing ones are NULL); a+ /// value is written in its column type's input syntax.+ ///+ /// Python's `ColumnDef.encoder` converts a field's value before it is+ /// bound. Here the row's `Serialize` impl does that: `uuid`, `chrono`,+ /// `rust_decimal`, `std::net::IpAddr` (for `inet`) and `Vec<f32>` (for+ /// pgvector) serialize to what their columns take, and a field needing+ /// another form uses `#[serde(serialize_with = "β¦")]`.pub fn declare_row<R: Serialize>(&self, ctx: &Ctx, row: &R) -> Result<()> {let row = row_state(row, &self.table_schema)?;let key = pk_stable_key(&row, self.table_schema.primary_key())?;@@ -895,11 +928,15 @@ fn resolve_db(host_ctx: &Arc<ContextStore>, db_key: &str) -> Result<Arc<Databaseimpl RowHandler {fn row_sink(&self) -> TargetActionSink<RowAction> {let db_key = self.db_key.clone();- let spec = self.spec.clone();+ let spec = Arc::new(self.spec.clone());+ let statements = Arc::new(RowStatements::new(&self.spec));+ let table_defined = Arc::new(tokio::sync::OnceCell::new());TargetActionSink::from_async_fn_with_ctx(move |host_ctx, actions: Vec<TargetAction<RowAction>>| {let db_key = db_key.clone();let spec = spec.clone();+ let statements = statements.clone();+ let table_defined = table_defined.clone();async move {let db = resolve_db(&host_ctx, &db_key)?;let mut mutations = Vec::with_capacity(actions.len());@@ -911,7 +948,19 @@ impl RowHandler {};mutations.push((row.pk, row.state));}- apply_rows(&db, &spec, mutations).await+ if mutations.is_empty() {+ return Ok(());+ }+ // Ensure the table exists before this sink's first row+ // mutation (once per sink, not per batch). This keeps a+ // delete-only reconciliation idempotent after a crash or an+ // external table cleanup.+ if spec.managed_by.is_system() {+ table_defined+ .get_or_try_init(|| define_table(&db, &spec))+ .await?;+ }+ apply_rows(&db, &statements, mutations).await}},)@@ -1284,34 +1333,61 @@ async fn drop_table(db: &Database, pg_schema_name: Option<&str>, table_name: &stOk(())}+/// Rows per upsert / delete statement. A statement's parameter count doesn't+/// grow with its row count (one `text[]` per column), so the bind limit doesn't+/// apply; throughput is flat from about 1,000 to 8,000 rows per statement, and+/// smaller statements spread a large batch over more connections (Python's+/// `_UNNEST_UPSERT_ROWS`).+const ROWS_PER_STATEMENT: usize = 2000;++/// Apply a batch of row mutations: upserts and deletes, each in statements of+/// up to [`ROWS_PER_STATEMENT`] rows. The statements of a batch run+/// concurrently, each on its own pool connection and committing on its own, as+/// the Python connector's do: a batch is not atomic, and a statement that+/// fails is retried by the next run.async fn apply_rows(db: &Database,- spec: &TableSpec,+ statements: &RowStatements,mutations: Vec<(Vec<JsonValue>, Option<RowState>)>,) -> Result<()> {- if mutations.is_empty() {- return Ok(());- }- // Ensure the table exists before any row mutation. This keeps delete-only- // reconciliation idempotent after a crash or external table cleanup.- if spec.managed_by.is_system() {- define_table(db, spec).await?;- }- // Apply the whole batch atomically.- let mut tx = db.pool().begin().await.map_err(pg_err)?;+ let mut upserts = Vec::new();+ let mut deletes = Vec::new();for (pk, state) in mutations {match state {- Some(state) => {- let sql = upsert_sql(spec, &state.fields)?;- sqlx::query(&sql).execute(&mut *tx).await.map_err(pg_err)?;- }- None => {- let sql = delete_sql(spec, &pk)?;- sqlx::query(&sql).execute(&mut *tx).await.map_err(pg_err)?;- }+ Some(state) => upserts.push(state.fields),+ None => deletes.push(pk),}}- tx.commit().await.map_err(pg_err)?;+ let mut executions = Vec::new();+ for chunk in upserts.chunks(ROWS_PER_STATEMENT) {+ executions.push(execute_with_columns(+ db,+ &statements.upsert_sql,+ statements.upsert_params(chunk)?,+ ));+ }+ for chunk in deletes.chunks(ROWS_PER_STATEMENT) {+ executions.push(execute_with_columns(+ db,+ &statements.delete_sql,+ statements.delete_params(chunk)?,+ ));+ }+ futures::future::try_join_all(executions).await?;+ Ok(())+}++/// Run `sql` with one `text[]` parameter per column.+async fn execute_with_columns(+ db: &Database,+ sql: &str,+ columns: Vec<Vec<Option<String>>>,+) -> Result<()> {+ let mut query = sqlx::query(sql);+ for column in columns {+ query = query.bind(column);+ }+ query.execute(db.pool()).await.map_err(pg_err)?;Ok(())}@@ -1348,78 +1424,137 @@ async fn drop_vector_index(db: &Database, spec: &VectorIndexSpec) -> Result<()>// SQL builders + helpers// ----------------------------------------------------------------------------fn upsert_sql(spec: &TableSpec, fields: &Map<String, JsonValue>) -> Result<String> {- let cols = spec- .table_schema- .columns()- .keys()- .cloned()- .collect::<Vec<_>>();- let col_sql = cols+/// The row statements of one table, built once per row sink.+///+/// Every column travels as one `text[]` parameter holding the chunk's values in+/// Postgres input syntax, and the statement casts each back to the declared+/// column type (an I/O conversion cast). One statement shape thus covers every+/// column type, pgvector, `jsonb`, `bytea`, `interval` and `inet` included, and+/// its text and parameter count don't grow with the row count. Python's+/// connector upserts through the same `unnest` shape with typed arrays.+struct RowStatements {+ /// Every column, in statement order.+ columns: Vec<(String, ColumnDef)>,+ /// `INSERT β¦ SELECT β¦ FROM unnest(β¦) β¦ ON CONFLICT β¦`.+ upsert_sql: String,+ /// The primary-key columns, in key order.+ pk_columns: Vec<(String, ColumnDef)>,+ /// `DELETE β¦ WHERE (pk) IN (SELECT β¦ FROM unnest(β¦))`.+ delete_sql: String,+}++impl RowStatements {+ fn new(spec: &TableSpec) -> Self {+ let schema = &spec.table_schema;+ let columns: Vec<(String, ColumnDef)> = schema+ .columns()+ .iter()+ .map(|(name, col)| (name.clone(), col.clone()))+ .collect();+ let pk_columns: Vec<(String, ColumnDef)> = schema+ .primary_key()+ .iter()+ .map(|name| (name.clone(), schema.columns()[name].clone()))+ .collect();+ let table = qualified_table_name(spec);++ let col_list = ident_list(&columns);+ let pk_list = ident_list(&pk_columns);+ let non_pk: Vec<String> = columns+ .iter()+ .filter(|(name, _)| !schema.primary_key().contains(name))+ .map(|(name, _)| format!("{0} = EXCLUDED.{0}", quote_ident(name)))+ .collect();+ let conflict = if non_pk.is_empty() {+ format!("ON CONFLICT ({pk_list}) DO NOTHING")+ } else {+ format!(+ "ON CONFLICT ({pk_list}) DO UPDATE SET {}",+ non_pk.join(", ")+ )+ };+ let upsert_sql = format!(+ "INSERT INTO {table} ({col_list}) SELECT {} FROM unnest({}) AS r({col_list}) {conflict}",+ cast_list(&columns),+ param_list(columns.len()),+ );+ let delete_sql = format!(+ "DELETE FROM {table} WHERE ({pk_list}) IN (SELECT {} FROM unnest({}) AS r({pk_list}))",+ cast_list(&pk_columns),+ param_list(pk_columns.len()),+ );+ Self {+ columns,+ upsert_sql,+ pk_columns,+ delete_sql,+ }+ }++ /// The parameters of [`Self::upsert_sql`] for `rows`: one `text[]` per+ /// column.+ fn upsert_params(&self, rows: &[Map<String, JsonValue>]) -> Result<Vec<Vec<Option<String>>>> {+ let mut params: Vec<Vec<Option<String>>> = self+ .columns+ .iter()+ .map(|_| Vec::with_capacity(rows.len()))+ .collect();+ for row in rows {+ for (param, (name, col)) in params.iter_mut().zip(&self.columns) {+ let value = row.get(name).unwrap_or(&JsonValue::Null);+ param.push(sql_text(value, col)?);+ }+ }+ Ok(params)+ }++ /// The parameters of [`Self::delete_sql`] for `keys`: one `text[]` per+ /// primary-key column.+ fn delete_params(&self, keys: &[Vec<JsonValue>]) -> Result<Vec<Vec<Option<String>>>> {+ let mut params: Vec<Vec<Option<String>>> = self+ .pk_columns+ .iter()+ .map(|_| Vec::with_capacity(keys.len()))+ .collect();+ for key in keys {+ if key.len() != self.pk_columns.len() {+ return Err(Error::engine(+ "Postgres row target primary key length mismatch",+ ));+ }+ for ((param, (_, col)), part) in params.iter_mut().zip(&self.pk_columns).zip(key) {+ param.push(sql_text(&key_part_value(part, col), col)?);+ }+ }+ Ok(params)+ }+}++/// `"a", "b", β¦`+fn ident_list(columns: &[(String, ColumnDef)]) -> String {+ columns.iter()- .map(|name| quote_ident(name))+ .map(|(name, _)| quote_ident(name)).collect::<Vec<_>>()- .join(", ");- let values = cols- .iter()- .map(|name| {- let col = spec- .table_schema- .columns()- .get(name)- .expect("schema column");- let value = fields.get(name).unwrap_or(&JsonValue::Null);- sql_literal(value, col)- })- .collect::<Result<Vec<_>>>()?- .join(", ");- let pk_sql = spec- .table_schema- .primary_key()+ .join(", ")+}++/// `r."a"::type_a, r."b"::type_b, β¦`: the unnested text values cast back to+/// their column types.+fn cast_list(columns: &[(String, ColumnDef)]) -> String {+ columns.iter()- .map(|name| quote_ident(name))+ .map(|(name, col)| format!("r.{}::{}", quote_ident(name), col.pg_type)).collect::<Vec<_>>()- .join(", ");- let non_pk = cols- .iter()- .filter(|name| !spec.table_schema.primary_key().contains(name))- .map(|name| format!("{} = EXCLUDED.{}", quote_ident(name), quote_ident(name)))- .collect::<Vec<_>>();- let conflict = if non_pk.is_empty() {- format!("ON CONFLICT ({pk_sql}) DO NOTHING")- } else {- format!("ON CONFLICT ({pk_sql}) DO UPDATE SET {}", non_pk.join(", "))- };- Ok(format!(- "INSERT INTO {} ({col_sql}) VALUES ({values}) {conflict}",- qualified_table_name(spec)- ))+ .join(", ")}-fn delete_sql(spec: &TableSpec, pk: &[JsonValue]) -> Result<String> {- if pk.len() != spec.table_schema.primary_key().len() {- return Err(Error::engine(- "Postgres row target primary key length mismatch",- ));- }- let mut predicates = Vec::with_capacity(pk.len());- for (idx, name) in spec.table_schema.primary_key().iter().enumerate() {- let col = spec.table_schema.columns().get(name).ok_or_else(|| {- Error::engine(format!(- "primary key column {name:?} is not in the table schema"- ))- })?;- predicates.push(format!(- "{} = {}",- quote_ident(name),- sql_literal(&key_part_value(&pk[idx], col), col)?- ));- }- Ok(format!(- "DELETE FROM {} WHERE {}",- qualified_table_name(spec),- predicates.join(" AND ")- ))+/// `$1::text[], $2::text[], β¦`+fn param_list(count: usize) -> String {+ (1..=count)+ .map(|i| format!("${i}::text[]"))+ .collect::<Vec<_>>()+ .join(", ")}fn row_state<R: Serialize>(row: &R, schema: &TableSchema) -> Result<Map<String, JsonValue>> {@@ -1505,10 +1640,13 @@ fn json_scalar_to_stable_key(value: &JsonValue) -> Result<StableKey> {}}-fn sql_literal(value: &JsonValue, col: &ColumnDef) -> Result<String> {+/// A column value in Postgres input syntax for its declared type (`None` for+/// SQL NULL), as the row statements bind it. Postgres rejects U+0000 in any+/// text parameter, so it is stripped from every value.+fn sql_text(value: &JsonValue, col: &ColumnDef) -> Result<Option<String>> {if value.is_null() {return if col.nullable {- Ok("NULL".to_string())+ Ok(None)} else {Err(Error::engine(format!("non-nullable Postgres column of type {} got null",@@ -1517,75 +1655,58 @@ fn sql_literal(value: &JsonValue, col: &ColumnDef) -> Result<String> {};}let lower = col.pg_type.to_ascii_lowercase();- if is_text_type(&lower) {- return Ok(quote_string(value_to_string(value)?));- }- if lower == "boolean" || lower == "bool" {- return value+ let text = if is_text_type(&lower) {+ value_to_string(value)?.to_string()+ } else if lower == "boolean" || lower == "bool" {+ value.as_bool()- .map(|b| if b { "TRUE" } else { "FALSE" }.to_string())- .ok_or_else(|| Error::engine("boolean column requires bool JSON value"));- }- if lower.starts_with("interval") {- return interval_literal(value, &col.pg_type);- }- if is_numeric_type(&lower) {- return match value {- JsonValue::Number(n) => Ok(n.to_string()),- JsonValue::String(s) if is_decimal_type(&lower) && is_decimal_literal(s) => {- Ok(s.clone())+ .map(|b| b.to_string())+ .ok_or_else(|| Error::engine("boolean column requires bool JSON value"))?+ } else if lower.starts_with("interval") {+ interval_text(value)?+ } else if is_numeric_type(&lower) {+ match value {+ JsonValue::Number(n) => n.to_string(),+ JsonValue::String(s) if is_decimal_type(&lower) && is_decimal_literal(s) => s.clone(),+ _ => {+ return Err(Error::engine(format!(+ "numeric column {} requires numeric JSON value",+ col.pg_type+ )));}- _ => Err(Error::engine(format!(- "numeric column {} requires numeric JSON value",- col.pg_type- ))),- };- }- if _is_pgvector_type(&lower) {- return vector_literal(value, &col.pg_type);- }- if lower == "bytea" {+ }+ } else if _is_pgvector_type(&lower) {+ vector_text(value)?+ } else if lower == "bytea" {// A Rust `Vec<u8>` serializes to a JSON array of byte values; encode it- // as Postgres hex bytea (`'\x..'::bytea`). The fallback `'[104,105]'`+ // as Postgres hex bytea input (`\xβ¦`). Its JSON text (`[104,105]`)// would be invalid bytea input.- return bytea_literal(value);- }- if lower == "json" || lower == "jsonb" {+ bytea_text(value)?+ } else if lower == "json" || lower == "jsonb" {// Postgres rejects U+0000 in json/jsonb on parse, and serde serializes a- // NUL inside a nested string/key as the `\x00` escape (which- // `quote_string`'s byte-level strip can't catch). Remove NULs from every- // string and object key before serializing.- return Ok(format!(- "{}::{}",- quote_string(sanitize_json_nul(value).to_string()),- col.pg_type- ));- }- match value {- JsonValue::String(s) => Ok(format!("{}::{}", quote_string(s), col.pg_type)),- JsonValue::Number(n) => Ok(format!("{}::{}", n, col.pg_type)),- JsonValue::Bool(b) => Ok(format!(- "{}::{}",- if *b { "TRUE" } else { "FALSE" },- col.pg_type- )),- _ => Ok(format!(- "{}::{}",- quote_string(value.to_string()),- col.pg_type- )),- }+ // NUL inside a nested string/key as the `\u0000` escape (which the+ // final byte-level strip can't catch). Remove NULs from every string+ // and object key before serializing.+ sanitize_json_nul(value).to_string()+ } else {+ // Any other type (uuid, date/time, inet, β¦) takes its value's text, or+ // its JSON text for a non-scalar.+ match value {+ JsonValue::String(s) => s.clone(),+ JsonValue::Number(n) => n.to_string(),+ JsonValue::Bool(b) => b.to_string(),+ other => other.to_string(),+ }+ };+ Ok(Some(strip_nul(text)))}-fn interval_literal(value: &JsonValue, pg_type: &str) -> Result<String> {+fn interval_text(value: &JsonValue) -> Result<String> {if let Some((secs, nanos)) = crate::row_schema::serialized_duration_parts(value) {- return Ok(format!(- "{}::{pg_type}",- quote_string(format!("{secs}.{nanos:09} seconds"))- ));+ return Ok(format!("{secs}.{nanos:09} seconds"));}match value {- JsonValue::String(s) => Ok(format!("{}::{pg_type}", quote_string(s))),+ JsonValue::String(s) => Ok(s.clone()),_ => Err(Error::engine("interval column requires a duration or string JSON value",)),@@ -1598,9 +1719,9 @@ fn value_to_string(value: &JsonValue) -> Result<&str> {.ok_or_else(|| Error::engine("text column requires string JSON value"))}-/// Encode a JSON value as a Postgres hex `bytea` literal. Accepts a byte array-/// (the serde default for `Vec<u8>`) or a string (encoded as its UTF-8 bytes).-fn bytea_literal(value: &JsonValue) -> Result<String> {+/// Encode a JSON value as Postgres hex `bytea` input. Accepts a byte array (the+/// serde default for `Vec<u8>`) or a string (encoded as its UTF-8 bytes).+fn bytea_text(value: &JsonValue) -> Result<String> {let bytes: Vec<u8> = match value {JsonValue::Array(arr) => arr.iter()@@ -1623,10 +1744,11 @@ fn bytea_literal(value: &JsonValue) -> Result<String> {for b in &bytes {hex.push_str(&format!("{b:02x}"));}- Ok(format!("{}::bytea", quote_string(hex)))+ Ok(hex)}-fn vector_literal(value: &JsonValue, pg_type: &str) -> Result<String> {+/// A JSON number array as pgvector input: `[1,2,3]`.+fn vector_text(value: &JsonValue) -> Result<String> {let arr = value.as_array().ok_or_else(|| Error::engine("vector column requires JSON array"))?;@@ -1640,16 +1762,16 @@ fn vector_literal(value: &JsonValue, pg_type: &str) -> Result<String> {}parts.push(n.to_string());}- Ok(format!(- "{}::{}",- quote_string(format!("[{}]", parts.join(","))),- pg_type- ))+ Ok(format!("[{}]", parts.join(",")))}-fn quote_string(value: impl AsRef<str>) -> String {- let value = value.as_ref().replace('\0', "").replace('\'', "''");- format!("'{value}'")+/// Strip U+0000, which Postgres rejects in text, from a value's text.+fn strip_nul(value: String) -> String {+ if value.contains('\0') {+ value.replace('\0', "")+ } else {+ value+ }}/// Build the pgvector index `WITH (...)` clause, gating each parameter by the@@ -1889,7 +2011,8 @@ mod tests {id: 42,filename: "src/lib.rs".to_string(),code: "fn answer() -> i32 { 42 }".to_string(),- embedding: vec![0.1, 0.2, 0.3],+ // Exact in f32, so the text is the same through the f64 JSON form.+ embedding: vec![0.5, 0.25, 0.75],start_line: 1,end_line: 3,};@@ -1900,15 +2023,27 @@ mod tests {StableKey::Int(42));- let sql = upsert_sql(&spec, &fields).unwrap();- assert!(sql.contains("INSERT INTO \"coco_examples\".\"code_embeddings\""));- assert!(sql.contains("'["));- assert!(sql.contains("]'::vector(3)"));- assert!(sql.contains("ON CONFLICT (\"id\") DO UPDATE SET"));+ let statements = RowStatements::new(&spec);+ assert_eq!(+ statements.upsert_sql,+ "INSERT INTO \"coco_examples\".\"code_embeddings\" (\"code\", \"embedding\", \"end_line\", \+ \"filename\", \"id\", \"start_line\") SELECT r.\"code\"::text, r.\"embedding\"::vector(3), \+ r.\"end_line\"::integer, r.\"filename\"::text, r.\"id\"::bigint, r.\"start_line\"::integer \+ FROM unnest($1::text[], $2::text[], $3::text[], $4::text[], $5::text[], $6::text[]) \+ AS r(\"code\", \"embedding\", \"end_line\", \"filename\", \"id\", \"start_line\") \+ ON CONFLICT (\"id\") DO UPDATE SET \"code\" = EXCLUDED.\"code\", \+ \"embedding\" = EXCLUDED.\"embedding\", \"end_line\" = EXCLUDED.\"end_line\", \+ \"filename\" = EXCLUDED.\"filename\", \"start_line\" = EXCLUDED.\"start_line\""+ );+ // One `text[]` per column, in statement order, over every row.+ let params = statements.upsert_params(&[fields.clone(), fields]).unwrap();+ assert_eq!(params.len(), 6);+ assert_eq!(params[1], vec![Some("[0.5,0.25,0.75]".to_string()); 2]);+ assert_eq!(params[4], vec![Some("42".to_string()); 2]);}#[test]- fn delete_sql_uses_typed_primary_key_literal() {+ fn delete_statement_takes_one_array_per_primary_key_column() {let schema = code_schema();let spec = TableSpec {pg_schema_name: Some("coco_examples".to_string()),@@ -1916,11 +2051,20 @@ mod tests {table_schema: schema,managed_by: ManagedBy::System,};- let sql = delete_sql(&spec, &[JsonValue::from(42)]).unwrap();+ let statements = RowStatements::new(&spec);assert_eq!(- sql,- "DELETE FROM \"coco_examples\".\"code_embeddings\" WHERE \"id\" = 42"+ statements.delete_sql,+ "DELETE FROM \"coco_examples\".\"code_embeddings\" WHERE (\"id\") IN \+ (SELECT r.\"id\"::bigint FROM unnest($1::text[]) AS r(\"id\"))");+ let params = statements+ .delete_params(&[vec![JsonValue::from(42)], vec![JsonValue::from(43)]])+ .unwrap();+ assert_eq!(+ params,+ vec![vec![Some("42".to_string()), Some("43".to_string())]]+ );+ assert!(statements.delete_params(&[vec![]]).is_err());}#[test]@@ -1942,12 +2086,20 @@ mod tests {json_scalar_to_stable_key(&JsonValue::from("true")).unwrap(),json_scalar_to_stable_key(&JsonValue::Bool(true)).unwrap(),]));- let sql = delete_sql(&spec, &stable_key_to_pk(&key).unwrap()).unwrap();- // A text key part spelled "true" stays a string.+ let statements = RowStatements::new(&spec);+ let params = statements+ .delete_params(&[stable_key_to_pk(&key).unwrap()])+ .unwrap();+ // A text key part spelled "true" stays a string; the boolean key part+ // is bound as a boolean's text.assert_eq!(- sql,- "DELETE FROM \"flags\" WHERE \"tenant\" = 'true' AND \"active\" = TRUE"+ params,+ vec![+ vec![Some("true".to_string())],+ vec![Some("true".to_string())]+ ]);+ assert!(statements.delete_sql.contains("r.\"active\"::boolean"));}#[test]@@ -1964,11 +2116,20 @@ mod tests {}#[test]- fn quote_string_strips_nul_and_escapes_quotes() {- // Postgres text/jsonb reject U+0000; it must be stripped, and single- // quotes doubled.- assert_eq!(quote_string("a\0b'c"), "'ab''c'");- assert_eq!(quote_string("plain"), "'plain'");+ fn sql_text_strips_nul_and_keeps_quotes() {+ // Postgres rejects U+0000 in a text parameter; a quote needs no escape+ // in a bound parameter.+ let col = ColumnDef::new("text");+ assert_eq!(+ sql_text(&JsonValue::from("a\0b'c"), &col).unwrap(),+ Some("ab'c".to_string())+ );+ assert_eq!(+ sql_text(&JsonValue::from("plain"), &col).unwrap(),+ Some("plain".to_string())+ );+ assert!(sql_text(&JsonValue::Null, &col).is_err());+ assert_eq!(sql_text(&JsonValue::Null, &col.nullable()).unwrap(), None);}}@@ -1976,26 +2137,45 @@ mod tests {// Source: read rows from a Postgres table// ---------------------------------------------------------------------------+/// Rows buffered between the reading task and the consumer of a+/// [`read_table`] stream.+const READ_BUFFER_ROWS: usize = 256;+/// Read every row of `table_name` (in the connection's default search path) as-/// `T`.+/// `T`, as a stream.+///+/// The rows are read inside one `REPEATABLE READ, READ ONLY` transaction, so+/// the whole table is observed as one consistent snapshot, and they are+/// streamed from the server as the consumer takes them (Python's+/// `PgTableSource.fetch_rows()` cursor): at most [`READ_BUFFER_ROWS`] rows are+/// held ahead of the consumer. Dropping the stream ends the read.////// `T` must be `Deserialize` (column names map to struct fields; unknown columns/// are ignored) and is usually also `Serialize` so each row can key memoized-/// per-row work via `ctx.mount_each`. Incrementality comes from memoization-/// (unchanged rows skip processing) plus target-state reconciliation (rows that-/// disappear from the source have their derived target states deleted).-pub async fn read_table<T: serde::de::DeserializeOwned>(+/// per-row work via `ctx.mount_each`, which takes the collected rows+/// (`futures::TryStreamExt::try_collect`). Incrementality comes from+/// memoization (unchanged rows skip processing) plus target-state+/// reconciliation (rows that disappear from the source have their derived+/// target states deleted).+pub async fn read_table<T>(db: &Database,table_name: &str,-) -> Result<Vec<T>> {+) -> Result<impl Stream<Item = Result<T>> + Send + 'static>+where+ T: serde::de::DeserializeOwned + Send + 'static,+{read_table_with_options(db, table_name, ReadTableOptions::default()).await}-pub async fn read_table_with_options<T: serde::de::DeserializeOwned>(+/// [`read_table`] with explicit [`ReadTableOptions`].+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,+{validate_ident(table_name, "table name")?;if let Some(schema) = &options.pg_schema_name {validate_ident(schema, "schema name")?;@@ -2020,39 +2200,45 @@ pub async fn read_table_with_options<T: serde::de::DeserializeOwned>("SELECT {select_list} FROM {}",qualified_table_name_from_parts(options.pg_schema_name.as_deref(), table_name));- // Read inside a REPEATABLE READ, READ ONLY transaction so the whole table is- // observed as one consistent snapshot.let mut tx = db.pool().begin().await.map_err(pg_err)?;sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY").execute(&mut *tx).await.map_err(pg_err)?;- let rows = sqlx::query(&sql)- .fetch_all(&mut *tx)- .await- .map_err(|e| Error::engine(format!("postgres source read failed: {e}")))?;- tx.commit().await.map_err(pg_err)?;- let mut out = Vec::with_capacity(rows.len());- for row in &rows {- let json = pg_row_to_json(row)?;- out.push(serde_json::from_value(json).map_err(|e| {- Error::engine(format!("postgres source row does not match row type: {e}"))- })?);- }- Ok(out)+ let (mut sender, receiver) = futures::channel::mpsc::channel::<Result<T>>(READ_BUFFER_ROWS);+ // The reading task owns the transaction; the stream is the channel's+ // receiving end. The task stops at the first error, or when the receiver+ // is dropped.+ tokio::spawn(async move {+ let mut rows = sqlx::query(&sql).fetch(&mut *tx);+ while let Some(row) = rows.next().await {+ let item = row+ .map_err(|e| Error::engine(format!("postgres source read failed: {e}")))+ .and_then(|row| source_row::<T>(&row));+ let failed = item.is_err();+ if sender.send(item).await.is_err() || failed {+ break;+ }+ }+ drop(rows);+ // Nothing to commit in a read-only transaction; ending it releases the+ // snapshot and returns the connection to the pool.+ let _ = tx.commit().await;+ });+ Ok(receiver)}/// Read every row paired with a stable key derived by `key_fn`, ready to feed-/// [`Ctx::mount_each`](crate::Ctx::mount_each). Reads use the same-/// repeatable-read snapshot as [`read_table`].+/// [`Ctx::mount_each`](crate::Ctx::mount_each) once collected. Reads use the+/// same repeatable-read snapshot and streaming as [`read_table`].pub async fn read_table_items<T, K, S>(db: &Database,table_name: &str,key_fn: K,-) -> Result<Vec<(StableKey, T)>>+) -> Result<impl Stream<Item = Result<(StableKey, T)>> + Send + 'static>where- T: serde::de::DeserializeOwned,- K: Fn(&T) -> S,+ T: serde::de::DeserializeOwned + Send + 'static,+ K: Fn(&T) -> S + Send + 'static,S: crate::target_state::IntoStableKey,{read_table_items_with_options(db, table_name, ReadTableOptions::default(), key_fn).await@@ -2064,20 +2250,26 @@ pub async fn read_table_items_with_options<T, K, S>(table_name: &str,options: ReadTableOptions,key_fn: K,-) -> Result<Vec<(StableKey, T)>>+) -> Result<impl Stream<Item = Result<(StableKey, T)>> + Send + 'static>where- T: serde::de::DeserializeOwned,- K: Fn(&T) -> S,+ T: serde::de::DeserializeOwned + Send + 'static,+ K: Fn(&T) -> S + Send + 'static,S: crate::target_state::IntoStableKey,{- let rows: Vec<T> = read_table_with_options(db, table_name, options).await?;- Ok(rows- .into_iter()- .map(|row| {+ let rows = read_table_with_options::<T>(db, table_name, options).await?;+ Ok(rows.map(move |row| {+ row.map(|row| {let key = key_fn(&row).into_stable_key();(key, row)})- .collect())+ }))+}++/// Convert one source row to `T` through its JSON form.+fn source_row<T: serde::de::DeserializeOwned>(row: &sqlx::postgres::PgRow) -> Result<T> {+ let json = pg_row_to_json(row)?;+ serde_json::from_value(json)+ .map_err(|e| Error::engine(format!("postgres source row does not match row type: {e}")))}fn pg_row_to_json(row: &sqlx::postgres::PgRow) -> Result<JsonValue> {@@ -2174,12 +2366,10 @@ mod review_fix_tests {"na\0me": "al\0ice","tags": ["a\0b", {"k\0": "v\0"}],});- let lit = sql_literal(&value, &ColumnDef::new("jsonb")).unwrap();- assert!(!lit.contains('\0'), "raw NUL leaked: {lit}");- assert!(!lit.contains("\\u0000"), "escaped NUL leaked: {lit}");- assert!(lit.ends_with("::jsonb"));- let inner = lit.trim_start_matches('\'').trim_end_matches("'::jsonb");- let parsed: JsonValue = serde_json::from_str(&inner.replace("''", "'")).unwrap();+ let text = sql_text(&value, &ColumnDef::new("jsonb")).unwrap().unwrap();+ assert!(!text.contains('\0'), "raw NUL leaked: {text}");+ assert!(!text.contains("\\u0000"), "escaped NUL leaked: {text}");+ let parsed: JsonValue = serde_json::from_str(&text).unwrap();assert_eq!(parsed["name"], serde_json::json!("alice"));assert_eq!(parsed["tags"][0], serde_json::json!("ab"));assert_eq!(parsed["tags"][1]["k"], serde_json::json!("v"));@@ -2195,11 +2385,11 @@ mod review_fix_tests {fn numeric_literal_accepts_rust_decimal_string_encoding() {let value = serde_json::to_value(Decimal::from_str("1234567890.012300").unwrap()).unwrap();assert_eq!(- sql_literal(&value, &ColumnDef::new("numeric(28, 6)")).unwrap(),- "1234567890.012300"+ sql_text(&value, &ColumnDef::new("numeric(28, 6)")).unwrap(),+ Some("1234567890.012300".to_string()));assert!(- sql_literal(+ sql_text(&JsonValue::String("1); DROP TABLE rows; --".to_string()),&ColumnDef::new("numeric"))@@ -2211,8 +2401,8 @@ mod review_fix_tests {fn interval_literal_accepts_std_duration_encoding() {let value = serde_json::to_value(std::time::Duration::new(12, 345_000_000)).unwrap();assert_eq!(- sql_literal(&value, &ColumnDef::new("interval")).unwrap(),- "'12.345000000 seconds'::interval"+ sql_text(&value, &ColumnDef::new("interval")).unwrap(),+ Some("12.345000000 seconds".to_string()));}diff --git a/rust/sdk/cocoindex/src/connectors/snowflake.rs b/rust/sdk/cocoindex/src/connectors/snowflake.rsindex 696c8bc4..e07b90e9 100644--- a/rust/sdk/cocoindex/src/connectors/snowflake.rs+++ b/rust/sdk/cocoindex/src/connectors/snowflake.rs@@ -535,6 +535,21 @@ impl TableSchema {Self::new(columns, primary_key)}+ /// Replace the type of one column of a schema derived from a row with+ /// `column`'s type and its [`ColumnDef::parse_json`] flag (Python's+ /// `column_overrides={"col": SnowflakeType("VARIANT", use_parse_json=True)}`), keeping the column's derived+ /// nullability.+ pub fn with_column_type(mut self, field_name: &str, column: ColumnDef) -> Result<Self> {+ validate_sql_type(&column.snowflake_type)?;+ let def = self+ .columns+ .get_mut(field_name)+ .ok_or_else(|| crate::row_schema::unknown_column_error("Snowflake", field_name))?;+ def.snowflake_type = column.snowflake_type;+ def.use_parse_json = column.use_parse_json;+ Ok(self)+ }+/// Columns in DDL order: primary-key columns first (in key order), then the/// rest by name.fn ordered_columns(&self) -> Vec<(&String, &ColumnDef)> {@@ -1721,6 +1736,35 @@ mod tests {);}+ #[test]+ fn column_type_override_changes_type_and_parse_json() {+ #[derive(crate::SchemaFields)]+ #[allow(dead_code)]+ struct Row {+ id: i64,+ payload: Option<String>,+ }+ let schema = TableSchema::from_row::<Row>(["id"])+ .unwrap()+ .with_column_type("payload", ColumnDef::new("VARIANT").parse_json())+ .unwrap();+ // The derived nullability stays.+ assert_eq!(+ schema.columns()["payload"],+ ColumnDef::new("VARIANT").parse_json()+ );+ let row = json!({"id": 1, "payload": "{\"a\":1}"});+ let (sql, _) =+ merge_statement("\"t\"", &schema, &[row.as_object().unwrap().clone()]).unwrap();+ assert!(sql.contains("PARSE_JSON(?) AS \"payload\""), "{sql}");+ assert!(+ TableSchema::from_row::<Row>(["id"])+ .unwrap()+ .with_column_type("missing", ColumnDef::new("VARIANT"))+ .is_err()+ );+ }+#[test]fn merge_statement_uses_parse_json_and_bindings() {let row = json!({"id": 1, "payload": {"b": 2, "a": [1]}});diff --git a/rust/sdk/cocoindex/src/connectors/sqlite.rs b/rust/sdk/cocoindex/src/connectors/sqlite.rsindex f4366d5e..6d07b251 100644--- a/rust/sdk/cocoindex/src/connectors/sqlite.rs+++ b/rust/sdk/cocoindex/src/connectors/sqlite.rs@@ -14,6 +14,7 @@use std::collections::{BTreeMap, HashMap};use std::sync::Arc;+use std::time::Duration;use cocoindex_utils::fingerprint::Fingerprint;use serde::{Deserialize, Serialize};@@ -39,7 +40,41 @@ use crate::target_state::{// Connection// ---------------------------------------------------------------------------+/// How long a connection waits for a lock held by another connection or+/// process before failing (Python's `connect(timeout=5.0)` default).+pub const DEFAULT_BUSY_TIMEOUT: Duration = Duration::from_secs(5);++/// Options for [`Database::connect_with_options`] (Python's `connect(database,+/// timeout=β¦, load_vec=β¦)`).+#[derive(Clone, Debug)]+pub struct ConnectOptions {+ /// How long to wait for a lock held by another connection or process.+ pub busy_timeout: Duration,+ /// The `sqlite-vec` extension to load so [`Vec0TableDef`] tables work:+ /// the loadable library as SQLite's extension loader takes it, a path with+ /// or without the platform suffix, or a bare name such as `"vec0"` to+ /// search the system library path. Connecting fails when it cannot be+ /// loaded. Python finds the library inside its `sqlite-vec` package; a+ /// Rust build has no such package, so the caller names the library.+ pub vec_extension: Option<String>,+}++impl Default for ConnectOptions {+ fn default() -> Self {+ Self {+ busy_timeout: DEFAULT_BUSY_TIMEOUT,+ vec_extension: None,+ }+ }+}+/// A SQLite connection pool. Clone-cheap (the underlying pool is shared).+///+/// SQLite is a single-writer engine, so the pool holds one connection and+/// serializes the statements run on it, as Python's `ManagedConnection` lock+/// does. For your own SQL on the same database, `pool().begin()` gives a+/// transaction (Python's `transaction()`), and `pool()` runs a read directly+/// (Python's `readonly()`).#[derive(Clone)]pub struct Database {pool: SqlitePool,@@ -47,36 +82,39 @@ pub struct Database {}impl Database {- /// Open (creating if missing) a SQLite database at `path`. SQLite is a- /// single-writer engine, so the pool is capped at one connection.+ /// Open (creating if missing) a SQLite database at `path` with the default+ /// [`ConnectOptions`].pub async fn connect(path: &str) -> Result<Self> {- Self::connect_with(path, Self::connect_options(path)).await+ Self::connect_with_options(path, ConnectOptions::default()).await}- /// [`connect`](Self::connect), loading the `sqlite-vec` extension into the- /// connection so [`Vec0TableDef`] tables work (Python's- /// `connect(database, load_vec=True)`). `vec_extension` is the loadable- /// library, as SQLite's extension loader takes it: a path with or without- /// the platform suffix, or a bare name such as `"vec0"` to search the- /// system library path. Fails when the library cannot be loaded.- ///- /// Python finds the library inside its `sqlite-vec` package; a Rust build- /// has no such package, so the caller names the library.+ /// [`connect`](Self::connect), loading the `sqlite-vec` extension named by+ /// `vec_extension` (see [`ConnectOptions::vec_extension`]; Python's+ /// `connect(database, load_vec=True)`).pub async fn connect_with_vec(path: &str, vec_extension: &str) -> Result<Self> {- let options = Self::connect_options(path).extension(vec_extension.to_string());- Self::connect_with(path, options).await+ Self::connect_with_options(+ path,+ ConnectOptions {+ vec_extension: Some(vec_extension.to_string()),+ ..ConnectOptions::default()+ },+ )+ .await}- fn connect_options(path: &str) -> SqliteConnectOptions {- SqliteConnectOptions::new()+ /// Open (creating if missing) a SQLite database at `path` with explicit+ /// [`ConnectOptions`].+ pub async fn connect_with_options(path: &str, options: ConnectOptions) -> Result<Self> {+ let mut connect_options = SqliteConnectOptions::new().filename(path).create_if_missing(true)- }-- async fn connect_with(path: &str, options: SqliteConnectOptions) -> Result<Self> {+ .busy_timeout(options.busy_timeout);+ if let Some(extension) = options.vec_extension {+ connect_options = connect_options.extension(extension);+ }let pool = SqlitePoolOptions::new().max_connections(1)- .connect_with(options)+ .connect_with(connect_options).await.map_err(sqlite_err)?;Ok(Self {@@ -439,6 +477,16 @@ impl TableTarget {&self.table_name}+ /// Declare a row. `row` serializes to an object whose entries are the+ /// table's columns (extra entries are ignored, missing ones are NULL); a+ /// value is bound by its column's declared type.+ ///+ /// Python's `ColumnDef.encoder` converts a field's value before it is+ /// bound (a `Decimal` or `UUID` to text, a `datetime` to ISO 8601, a+ /// collection to JSON). Here the row's `Serialize` impl does that: the+ /// defaults of `uuid`, `chrono` and `rust_decimal` serialize to the text+ /// these columns take, a collection serializes to JSON text, and a field+ /// needing another form uses `#[serde(serialize_with = "β¦")]`.pub fn declare_row<R: Serialize>(&self, ctx: &Ctx, row: &R) -> Result<()> {let fields = row_state(row, &self.table_schema)?;let key = pk_stable_key(&fields, self.table_schema.primary_key())?;@@ -833,11 +881,15 @@ impl TargetHandler<RowState> for RowHandler {impl RowHandler {fn row_sink(&self) -> TargetActionSink<RowAction> {let db_key = self.db_key.clone();- let spec = self.spec.clone();+ let spec = Arc::new(self.spec.clone());+ let statements = Arc::new(RowStatements::new(&self.spec));+ let table_created = Arc::new(tokio::sync::OnceCell::new());TargetActionSink::from_async_fn_with_ctx(move |host_ctx, actions: Vec<TargetAction<RowAction>>| {let db_key = db_key.clone();let spec = spec.clone();+ let statements = statements.clone();+ let table_created = table_created.clone();async move {let db = resolve_db(&host_ctx, &db_key)?;let mut mutations = Vec::with_capacity(actions.len());@@ -849,7 +901,19 @@ impl RowHandler {};mutations.push((row.pk, row.state));}- apply_rows(&db, &spec, mutations).await+ if mutations.is_empty() {+ return Ok(());+ }+ // Ensure the table exists before this sink's first row+ // mutation (once per sink, not per batch). This keeps a+ // delete-only reconciliation idempotent after a crash or+ // an external table cleanup.+ if spec.managed_by.is_system() {+ table_created+ .get_or_try_init(|| create_table(&db, &spec))+ .await?;+ }+ apply_rows(&db, &statements, mutations).await}},)@@ -976,34 +1040,88 @@ async fn add_column(db: &Database, table: &str, col_ident: &str, sqlite_type: &s}}+/// SQLite's default `SQLITE_MAX_VARIABLE_NUMBER` since 3.32 (the build `sqlx`+/// bundles); a statement binds at most this many parameters.+const BIND_LIMIT: usize = 32766;++/// Apply a batch of row mutations in one transaction: upserts through+/// multi-row `VALUES` statements of as many rows as the bind limit allows (one+/// `DELETE` + `INSERT` per row for a `vec0` table, which has no UPSERT), then+/// deletes through `IN` lists of keys (one `DELETE` per row for a `vec0`+/// table).async fn apply_rows(db: &Database,- spec: &TableSpec,+ statements: &RowStatements,mutations: Vec<(Vec<JsonValue>, Option<RowState>)>,) -> Result<()> {- if mutations.is_empty() {- return Ok(());- }- if spec.managed_by.is_system() {- create_table(db, spec).await?;+ let mut upserts = Vec::new();+ let mut deletes = Vec::new();+ for (pk, state) in mutations {+ match state {+ Some(state) => upserts.push(state.fields),+ None => deletes.push(pk),+ }}let mut tx = db.pool().begin().await.map_err(sqlite_err)?;- for (pk, state) in mutations {- let stmts = match state {- Some(state) => upsert_sql(spec, &state.fields)?,- None => vec![delete_sql(spec, &pk)?],- };- for sql in stmts {- sqlx::query(&sql)- .execute(&mut *tx)- .await- .map_err(sqlite_err)?;+ if statements.virtual_table {+ for row in &upserts {+ let key = statements.row_key(row)?;+ execute_with_values(&mut tx, &statements.delete_sql(1), key).await?;+ execute_with_values(+ &mut tx,+ &statements.upsert_sql(1),+ statements.row_values(row)?,+ )+ .await?;+ }+ for key in &deletes {+ execute_with_values(+ &mut tx,+ &statements.delete_sql(1),+ statements.key_values(key)?,+ )+ .await?;+ }+ } else {+ for chunk in upserts.chunks(statements.upsert_rows_per_statement()) {+ let mut values = Vec::with_capacity(chunk.len() * statements.columns.len());+ for row in chunk {+ values.extend(statements.row_values(row)?);+ }+ execute_with_values(&mut tx, &statements.upsert_sql(chunk.len()), values).await?;+ }+ for chunk in deletes.chunks(statements.delete_rows_per_statement()) {+ let mut values = Vec::with_capacity(chunk.len() * statements.pk_columns.len());+ for key in chunk {+ values.extend(statements.key_values(key)?);+ }+ execute_with_values(&mut tx, &statements.delete_sql(chunk.len()), values).await?;}}tx.commit().await.map_err(sqlite_err)?;Ok(())}+/// Run `sql` with `values` bound to its `?` placeholders, in order.+async fn execute_with_values(+ tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,+ sql: &str,+ values: Vec<SqliteValue>,+) -> Result<()> {+ let mut query = sqlx::query(sql);+ for value in values {+ query = match value {+ SqliteValue::Null => query.bind(None::<i64>),+ SqliteValue::Integer(i) => query.bind(i),+ SqliteValue::Real(r) => query.bind(r),+ SqliteValue::Text(t) => query.bind(t),+ SqliteValue::Blob(b) => query.bind(b),+ };+ }+ query.execute(&mut **tx).await.map_err(sqlite_err)?;+ Ok(())+}+// ---------------------------------------------------------------------------// DDL / SQL builders// ---------------------------------------------------------------------------@@ -1066,101 +1184,154 @@ fn create_vec0_sql(spec: &TableSpec, def: &Vec0TableDef) -> String {)}-/// Build the statement(s) that upsert one row. Regular tables get a single-/// `INSERT β¦ ON CONFLICT` statement; vec0 virtual tables (which don't support-/// UPSERT) get two statements β a `DELETE` then an `INSERT` β that the caller-/// must execute separately (a single `sqlx::query` only runs the first).-fn upsert_sql(spec: &TableSpec, fields: &Map<String, JsonValue>) -> Result<Vec<String>> {- let cols: Vec<&String> = spec.table_schema.columns().keys().collect();- let col_sql = cols- .iter()- .map(|name| quote_ident(name))- .collect::<Vec<_>>()- .join(", ");- let values = cols- .iter()- .map(|name| {- let col = spec- .table_schema- .columns()- .get(*name)- .expect("schema column");- let value = fields.get(*name).unwrap_or(&JsonValue::Null);- sql_literal(value, col)- })- .collect::<Result<Vec<_>>>()?- .join(", ");- // vec0 virtual tables do not support UPSERT; delete-then-insert per row, as- // two separate statements (one `sqlx::query` only executes the first).- if spec.virtual_table_def.is_some() {+/// The row statements of one table, built once per row sink. Values are bound+/// as `?` parameters, one per value, so a statement's row count is bounded by+/// [`BIND_LIMIT`].+struct RowStatements {+ table: String,+ /// Whether the table is a `vec0` virtual table (no UPSERT: one `DELETE` ++ /// `INSERT` per row).+ virtual_table: bool,+ /// Every column, in statement order.+ columns: Vec<(String, ColumnDef)>,+ /// The primary-key columns, in key order.+ pk_columns: Vec<(String, ColumnDef)>,+ /// `INSERT INTO <table> (<columns>) VALUES `+ insert_prefix: String,+ /// `(?, ?, β¦)` for one row.+ row_placeholders: String,+ /// `ON CONFLICT (<pk>) DO UPDATE SET β¦` (empty for a `vec0` table).+ conflict_clause: String,+}++impl RowStatements {+ fn new(spec: &TableSpec) -> Self {+ let schema = &spec.table_schema;+ let columns: Vec<(String, ColumnDef)> = schema+ .columns()+ .iter()+ .map(|(name, col)| (name.clone(), col.clone()))+ .collect();+ let pk_columns: Vec<(String, ColumnDef)> = schema+ .primary_key()+ .iter()+ .map(|name| (name.clone(), schema.columns()[name].clone()))+ .collect();let table = quote_ident(&spec.table_name);- let pk_predicate = pk_predicate(spec, fields)?;- return Ok(vec![- format!("DELETE FROM {table} WHERE {pk_predicate}"),- format!("INSERT INTO {table} ({col_sql}) VALUES ({values})"),- ]);+ let col_list = ident_list(&columns);+ let pk_list = ident_list(&pk_columns);+ let virtual_table = spec.virtual_table_def.is_some();+ let conflict_clause = if virtual_table {+ String::new()+ } else {+ let non_pk: Vec<String> = columns+ .iter()+ .filter(|(name, _)| !schema.primary_key().contains(name))+ .map(|(name, _)| format!("{0} = excluded.{0}", quote_ident(name)))+ .collect();+ if non_pk.is_empty() {+ format!(" ON CONFLICT ({pk_list}) DO NOTHING")+ } else {+ format!(+ " ON CONFLICT ({pk_list}) DO UPDATE SET {}",+ non_pk.join(", ")+ )+ }+ };+ Self {+ insert_prefix: format!("INSERT INTO {table} ({col_list}) VALUES "),+ row_placeholders: format!("({})", placeholders(columns.len())),+ conflict_clause,+ table,+ virtual_table,+ columns,+ pk_columns,+ }}- let pk_sql = spec- .table_schema- .primary_key()- .iter()- .map(|name| quote_ident(name))- .collect::<Vec<_>>()- .join(", ");- let non_pk = cols- .iter()- .filter(|name| !spec.table_schema.primary_key().contains(name))- .map(|name| format!("{} = excluded.{}", quote_ident(name), quote_ident(name)))- .collect::<Vec<_>>();- let conflict = if non_pk.is_empty() {- format!("ON CONFLICT ({pk_sql}) DO NOTHING")- } else {- format!("ON CONFLICT ({pk_sql}) DO UPDATE SET {}", non_pk.join(", "))- };- Ok(vec![format!(- "INSERT INTO {} ({col_sql}) VALUES ({values}) {conflict}",- quote_ident(&spec.table_name)- )])-}-fn delete_sql(spec: &TableSpec, pk: &[JsonValue]) -> Result<String> {- if pk.len() != spec.table_schema.primary_key().len() {- return Err(Error::engine(- "SQLite row target primary key length mismatch",- ));+ fn upsert_rows_per_statement(&self) -> usize {+ (BIND_LIMIT / self.columns.len().max(1)).max(1)}- let mut predicates = Vec::with_capacity(pk.len());- for (idx, name) in spec.table_schema.primary_key().iter().enumerate() {- let col = spec.table_schema.columns().get(name).ok_or_else(|| {- Error::engine(format!(- "primary key column {name:?} is not in the table schema"- ))- })?;- predicates.push(format!(- "{} = {}",- quote_ident(name),- sql_literal(&key_part_value(&pk[idx], col), col)?- ));++ fn delete_rows_per_statement(&self) -> usize {+ (BIND_LIMIT / self.pk_columns.len().max(1)).max(1)}- Ok(format!(- "DELETE FROM {} WHERE {}",- quote_ident(&spec.table_name),- predicates.join(" AND ")- ))-}-fn pk_predicate(spec: &TableSpec, fields: &Map<String, JsonValue>) -> Result<String> {- let mut predicates = Vec::new();- for name in spec.table_schema.primary_key() {- let col = spec.table_schema.columns().get(name).expect("pk column");- let value = fields.get(name).unwrap_or(&JsonValue::Null);- predicates.push(format!(- "{} = {}",- quote_ident(name),- sql_literal(value, col)?- ));+ /// `INSERT INTO t (β¦) VALUES (?, β¦), (?, β¦) ON CONFLICT β¦` for `rows` rows.+ fn upsert_sql(&self, rows: usize) -> String {+ let mut sql = self.insert_prefix.clone();+ for i in 0..rows {+ if i > 0 {+ sql.push_str(", ");+ }+ sql.push_str(&self.row_placeholders);+ }+ sql.push_str(&self.conflict_clause);+ sql+ }++ /// `DELETE FROM t WHERE pk IN (?, β¦)` for `keys` keys; a composite key+ /// compares as a row value: `WHERE (a, b) IN (VALUES (?, ?), β¦)`.+ fn delete_sql(&self, keys: usize) -> String {+ let table = &self.table;+ if self.pk_columns.len() == 1 {+ let pk = quote_ident(&self.pk_columns[0].0);+ format!("DELETE FROM {table} WHERE {pk} IN ({})", placeholders(keys))+ } else {+ let pk_list = ident_list(&self.pk_columns);+ let row = format!("({})", placeholders(self.pk_columns.len()));+ let rows = std::iter::repeat_n(row.as_str(), keys)+ .collect::<Vec<_>>()+ .join(", ");+ format!("DELETE FROM {table} WHERE ({pk_list}) IN (VALUES {rows})")+ }+ }++ /// A row's values in column order, for [`Self::upsert_sql`].+ fn row_values(&self, row: &Map<String, JsonValue>) -> Result<Vec<SqliteValue>> {+ self.columns+ .iter()+ .map(|(name, col)| sqlite_value(row.get(name).unwrap_or(&JsonValue::Null), col))+ .collect()+ }++ /// A row's primary-key values in key order, for [`Self::delete_sql`].+ fn row_key(&self, row: &Map<String, JsonValue>) -> Result<Vec<SqliteValue>> {+ self.pk_columns+ .iter()+ .map(|(name, col)| sqlite_value(row.get(name).unwrap_or(&JsonValue::Null), col))+ .collect()}- Ok(predicates.join(" AND "))++ /// A stored key's values in key order, for [`Self::delete_sql`].+ fn key_values(&self, key: &[JsonValue]) -> Result<Vec<SqliteValue>> {+ if key.len() != self.pk_columns.len() {+ return Err(Error::engine(+ "SQLite row target primary key length mismatch",+ ));+ }+ self.pk_columns+ .iter()+ .zip(key)+ .map(|((_, col), part)| sqlite_value(&key_part_value(part, col), col))+ .collect()+ }+}++/// `"a", "b", β¦`+fn ident_list(columns: &[(String, ColumnDef)]) -> String {+ columns+ .iter()+ .map(|(name, _)| quote_ident(name))+ .collect::<Vec<_>>()+ .join(", ")+}++/// `?, ?, β¦`+fn placeholders(count: usize) -> String {+ std::iter::repeat_n("?", count)+ .collect::<Vec<_>>()+ .join(", ")}// ---------------------------------------------------------------------------@@ -1248,10 +1419,21 @@ fn json_scalar_to_stable_key(value: &JsonValue) -> Result<StableKey> {}}-fn sql_literal(value: &JsonValue, col: &ColumnDef) -> Result<String> {+/// A value bound to a statement parameter.+#[derive(Clone, Debug, PartialEq)]+enum SqliteValue {+ Null,+ Integer(i64),+ Real(f64),+ Text(String),+ Blob(Vec<u8>),+}++/// A column value as bound for its declared type.+fn sqlite_value(value: &JsonValue, col: &ColumnDef) -> Result<SqliteValue> {if value.is_null() {return if col.nullable {- Ok("NULL".to_string())+ Ok(SqliteValue::Null)} else {Err(Error::engine(format!("non-nullable SQLite column of type {} got null",@@ -1262,49 +1444,55 @@ fn sql_literal(value: &JsonValue, col: &ColumnDef) -> Result<String> {let t = col.sqlite_type.to_ascii_lowercase();if t.starts_with("float[") {// sqlite-vec accepts a JSON array string for vector columns.- return vector_literal(value);+ return vector_text(value).map(SqliteValue::Text);}if is_integer_type(&t) {- return match value {- JsonValue::Number(n) if n.is_i64() || n.is_u64() => Ok(n.to_string()),- JsonValue::Bool(b) => Ok(if *b { "1" } else { "0" }.to_string()),- // A fractional number (e.g. 1.5) must NOT be silently stored β SQLite- // affinity would keep it as a REAL in an INTEGER column, violating the- // declared schema. Reject it instead.- _ => Err(Error::engine(format!(- "integer column {} requires an integer value",- col.sqlite_type- ))),- };+ if let Some(i) = value.as_i64() {+ return Ok(SqliteValue::Integer(i));+ }+ if let Some(b) = value.as_bool() {+ return Ok(SqliteValue::Integer(i64::from(b)));+ }+ // A fractional number (e.g. 1.5), or one past i64, must NOT be+ // silently stored β SQLite affinity would keep it as a REAL in an+ // INTEGER column, violating the declared schema. Reject it instead.+ return Err(Error::engine(format!(+ "integer column {} requires an integer value",+ col.sqlite_type+ )));}if is_real_type(&t) {if let Some((secs, nanos)) = crate::row_schema::serialized_duration_parts(value) {- return Ok(format!("{secs}.{nanos:09}"));+ return Ok(SqliteValue::Real(secs as f64 + f64::from(nanos) / 1e9));}- return match value {- JsonValue::Number(n) => Ok(n.to_string()),- _ => Err(Error::engine(format!(+ return match value.as_f64() {+ Some(n) => Ok(SqliteValue::Real(n)),+ None => Err(Error::engine(format!("real column {} requires a number",col.sqlite_type))),};}if is_text_type(&t) {- return Ok(quote_string(value_to_string(value)));+ return Ok(SqliteValue::Text(value_to_string(value)));}if is_blob_type(&t) {- return blob_literal(value);- }- // Fallback (BLOB / unknown): store scalars directly, complex as JSON text.- match value {- JsonValue::String(s) => Ok(quote_string(s)),- JsonValue::Number(n) => Ok(n.to_string()),- JsonValue::Bool(b) => Ok(if *b { "1" } else { "0" }.to_string()),- other => Ok(quote_string(other.to_string())),- }+ return blob_value(value);+ }+ // Fallback (unknown affinity): store scalars directly, complex as JSON text.+ Ok(match value {+ JsonValue::String(s) => SqliteValue::Text(s.clone()),+ JsonValue::Number(n) => match (n.as_i64(), n.as_f64()) {+ (Some(i), _) => SqliteValue::Integer(i),+ (None, Some(f)) => SqliteValue::Real(f),+ (None, None) => SqliteValue::Text(n.to_string()),+ },+ JsonValue::Bool(b) => SqliteValue::Integer(i64::from(*b)),+ other => SqliteValue::Text(other.to_string()),+ })}-fn blob_literal(value: &JsonValue) -> Result<String> {+fn blob_value(value: &JsonValue) -> Result<SqliteValue> {let bytes: Vec<u8> = match value {JsonValue::Array(items) => items.iter()@@ -1322,13 +1510,7 @@ fn blob_literal(value: &JsonValue) -> Result<String> {));}};- let mut literal = String::with_capacity(3 + bytes.len() * 2);- literal.push_str("X'");- for byte in bytes {- literal.push_str(&format!("{byte:02x}"));- }- literal.push('\'');- Ok(literal)+ Ok(SqliteValue::Blob(bytes))}fn value_to_string(value: &JsonValue) -> String {@@ -1338,7 +1520,8 @@ fn value_to_string(value: &JsonValue) -> String {}}-fn vector_literal(value: &JsonValue) -> Result<String> {+/// A JSON number array as sqlite-vec text input: `[1,2,3]`.+fn vector_text(value: &JsonValue) -> Result<String> {let arr = value.as_array().ok_or_else(|| Error::engine("vector column requires a JSON array"))?;@@ -1352,12 +1535,7 @@ fn vector_literal(value: &JsonValue) -> Result<String> {}parts.push(n.to_string());}- Ok(quote_string(format!("[{}]", parts.join(","))))-}--fn quote_string(value: impl AsRef<str>) -> String {- let value = value.as_ref().replace('\0', "").replace('\'', "''");- format!("'{value}'")+ Ok(format!("[{}]", parts.join(",")))}fn quote_ident(value: &str) -> String {@@ -1470,41 +1648,45 @@ mod tests {}#[test]- fn upsert_sql_uses_on_conflict_with_typed_literals() {+ fn upsert_statement_binds_rows_as_parameters() {let mut fields = Map::new();fields.insert("id".into(), JsonValue::from(7));fields.insert("name".into(), JsonValue::from("a'b"));fields.insert("score".into(), JsonValue::from(1.5));- let stmts = upsert_sql(&spec(schema()), &fields).unwrap();- // Regular tables: a single ON CONFLICT upsert statement.- assert_eq!(stmts.len(), 1);+ let statements = RowStatements::new(&spec(schema()));+ // Regular tables: one multi-row ON CONFLICT upsert statement.assert_eq!(- stmts[0],- "INSERT INTO \"items\" (\"id\", \"name\", \"score\") VALUES (7, 'a''b', 1.5) \+ statements.upsert_sql(2),+ "INSERT INTO \"items\" (\"id\", \"name\", \"score\") VALUES (?, ?, ?), (?, ?, ?) \ON CONFLICT (\"id\") DO UPDATE SET \"name\" = excluded.\"name\", \"score\" = excluded.\"score\"");+ assert_eq!(+ statements.row_values(&fields).unwrap(),+ vec![+ SqliteValue::Integer(7),+ SqliteValue::Text("a'b".to_string()),+ SqliteValue::Real(1.5),+ ]+ );+ // 3 columns: 10,922 rows fit the bind limit.+ assert_eq!(statements.upsert_rows_per_statement(), BIND_LIMIT / 3);}#[test]- fn vec0_upsert_emits_separate_delete_and_insert() {- // Regression: vec0 has no UPSERT, so it must produce a DELETE then an- // INSERT as two statements (a single `sqlx::query` runs only the first,- // which silently dropped the INSERT β lost rows).+ fn vec0_statements_have_no_upsert_clause() {+ // vec0 has no UPSERT: a row is a DELETE by key then an INSERT.let mut spec = spec(schema());spec.virtual_table_def = Some(Vec0TableDef::default());- let mut fields = Map::new();- fields.insert("id".into(), JsonValue::from(7));- fields.insert("name".into(), JsonValue::from("a"));- fields.insert("score".into(), JsonValue::from(1.5));- let stmts = upsert_sql(&spec, &fields).unwrap();- assert_eq!(stmts.len(), 2, "vec0 upsert must be two statements");- assert!(- stmts[0].starts_with("DELETE FROM \"items\" WHERE"),- "{stmts:?}"+ let statements = RowStatements::new(&spec);+ assert!(statements.virtual_table);+ assert_eq!(+ statements.delete_sql(1),+ "DELETE FROM \"items\" WHERE \"id\" IN (?)"+ );+ assert_eq!(+ statements.upsert_sql(1),+ "INSERT INTO \"items\" (\"id\", \"name\", \"score\") VALUES (?, ?, ?)");- assert!(stmts[1].starts_with("INSERT INTO \"items\""), "{stmts:?}");- // Neither statement contains a `;` separator (so each runs on its own).- assert!(stmts.iter().all(|s| !s.contains(';')), "{stmts:?}");}#[test]@@ -1521,43 +1703,74 @@ mod tests {json_scalar_to_stable_key(&JsonValue::from("true")).unwrap(),json_scalar_to_stable_key(&JsonValue::Bool(true)).unwrap(),]));- let sql = delete_sql(&spec(schema), &stable_key_to_pk(&key).unwrap()).unwrap();+ let statements = RowStatements::new(&spec(schema));+ // A composite key compares as a row value.assert_eq!(- sql,- "DELETE FROM \"items\" WHERE \"tenant\" = 'true' AND \"active\" = 1"+ statements.delete_sql(2),+ "DELETE FROM \"items\" WHERE (\"tenant\", \"active\") IN (VALUES (?, ?), (?, ?))"+ );+ // A text key part spelled "true" stays text; the boolean key part is+ // bound as the integer it is stored as.+ assert_eq!(+ statements+ .key_values(&stable_key_to_pk(&key).unwrap())+ .unwrap(),+ vec![+ SqliteValue::Text("true".to_string()),+ SqliteValue::Integer(1)+ ]);}#[test]- fn delete_sql_uses_primary_key_literal() {- let sql = delete_sql(&spec(schema()), &[JsonValue::from(9)]).unwrap();- assert_eq!(sql, "DELETE FROM \"items\" WHERE \"id\" = 9");+ fn delete_statement_lists_keys() {+ let statements = RowStatements::new(&spec(schema()));+ assert_eq!(+ statements.delete_sql(3),+ "DELETE FROM \"items\" WHERE \"id\" IN (?, ?, ?)"+ );+ assert_eq!(+ statements.key_values(&[JsonValue::from(9)]).unwrap(),+ vec![SqliteValue::Integer(9)]+ );+ assert!(statements.key_values(&[]).is_err());}#[test]fn integer_column_rejects_fractional_number() {let col = ColumnDef::new("INTEGER");// Integer values (and bools) are fine.- assert_eq!(sql_literal(&JsonValue::from(7), &col).unwrap(), "7");- assert_eq!(sql_literal(&JsonValue::from(true), &col).unwrap(), "1");+ assert_eq!(+ sqlite_value(&JsonValue::from(7), &col).unwrap(),+ SqliteValue::Integer(7)+ );+ assert_eq!(+ sqlite_value(&JsonValue::from(true), &col).unwrap(),+ SqliteValue::Integer(1)+ );// A fractional number must be rejected, not stored as REAL in an INTEGER column.- assert!(sql_literal(&JsonValue::from(1.5), &col).is_err());+ assert!(sqlite_value(&JsonValue::from(1.5), &col).is_err());}#[test]- fn blob_literal_rejects_out_of_range_bytes() {+ fn blob_value_rejects_out_of_range_bytes() {let col = ColumnDef::new("BLOB");- assert!(sql_literal(&serde_json::json!([256]), &col).is_err());+ assert!(sqlite_value(&serde_json::json!([256]), &col).is_err());+ assert_eq!(+ sqlite_value(&serde_json::json!([104, 105]), &col).unwrap(),+ SqliteValue::Blob(b"hi".to_vec())+ );}#[test]fn single_column_table_upsert_does_nothing_on_conflict() {let schema = TableSchema::new([("id", ColumnDef::new("INTEGER"))], ["id"]).unwrap();- let mut fields = Map::new();- fields.insert("id".into(), JsonValue::from(1));- let stmts = upsert_sql(&spec(schema), &fields).unwrap();- assert_eq!(stmts.len(), 1);- assert!(stmts[0].ends_with("ON CONFLICT (\"id\") DO NOTHING"));+ let statements = RowStatements::new(&spec(schema));+ assert!(+ statements+ .upsert_sql(1)+ .ends_with("ON CONFLICT (\"id\") DO NOTHING")+ );}#[test]diff --git a/rust/sdk/cocoindex/src/row_schema.rs b/rust/sdk/cocoindex/src/row_schema.rsindex 52d8de71..82011ef6 100644--- a/rust/sdk/cocoindex/src/row_schema.rs+++ b/rust/sdk/cocoindex/src/row_schema.rs@@ -88,7 +88,9 @@feature = "qdrant",feature = "turbopuffer",feature = "neo4j",- feature = "falkordb"+ feature = "falkordb",+ feature = "bigquery",+ feature = "snowflake"))]use crate::error::Error;#[cfg(any(@@ -204,7 +206,9 @@ pub(crate) fn not_vector_field_error(connector: &str, field_name: &str) -> Errorfeature = "doris",feature = "lancedb",feature = "neo4j",- feature = "falkordb"+ feature = "falkordb",+ feature = "bigquery",+ feature = "snowflake"))]pub(crate) fn unknown_column_error(connector: &str, field_name: &str) -> Error {Error::engine(format!(diff --git a/rust/sdk/cocoindex/tests/common/mod.rs b/rust/sdk/cocoindex/tests/common/mod.rsnew file mode 100644index 00000000..5eee1f10--- /dev/null+++ b/rust/sdk/cocoindex/tests/common/mod.rs@@ -0,0 +1,106 @@+//! Shared support for the connector integration tests.+#![allow(dead_code)]++use std::sync::{Mutex, OnceLock};++use tracing::field::{Field, Visit};+use tracing::{Event, Level, Metadata, Subscriber, span};++static STATEMENTS: OnceLock<Mutex<Vec<String>>> = OnceLock::new();++/// Record every SQL statement `sqlx` executes from now on, in this test+/// binary. `sqlx` reports each executed statement as a `tracing` event on the+/// `sqlx::query` target; this installs a global subscriber for that target+/// once per binary, so tests running in parallel share the log and pick their+/// statements by table name ([`sql_statements_containing`]). The subscriber+/// takes the place of the engine's, so it prints the engine's warnings and+/// errors to stderr, which is where a background mount's failure goes.+pub fn record_sql_statements() {+ STATEMENTS.get_or_init(|| {+ // A second `set_global_default` (another test called this first)+ // fails harmlessly: the subscriber is already ours.+ let _ = tracing::subscriber::set_global_default(SqlStatementLog);+ Mutex::new(Vec::new())+ });+}++/// The recorded statements whose text contains `needle`.+pub fn sql_statements_containing(needle: &str) -> Vec<String> {+ STATEMENTS+ .get()+ .expect("record_sql_statements() was not called")+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .iter()+ .filter(|statement| statement.contains(needle))+ .cloned()+ .collect()+}++struct SqlStatementLog;++impl Subscriber for SqlStatementLog {+ fn enabled(&self, metadata: &Metadata<'_>) -> bool {+ metadata.target() == "sqlx::query" || *metadata.level() <= Level::WARN+ }++ fn new_span(&self, _attributes: &span::Attributes<'_>) -> span::Id {+ span::Id::from_u64(1)+ }++ fn record(&self, _span: &span::Id, _values: &span::Record<'_>) {}++ fn record_follows_from(&self, _span: &span::Id, _follows: &span::Id) {}++ fn event(&self, event: &Event<'_>) {+ if event.metadata().target() != "sqlx::query" {+ let mut message = String::new();+ event.record(&mut MessageText(&mut message));+ eprintln!(+ "{} {}: {message}",+ event.metadata().level(),+ event.metadata().target()+ );+ return;+ }+ let mut text = String::new();+ event.record(&mut StatementText(&mut text));+ if let Some(statements) = STATEMENTS.get() {+ statements+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .push(text);+ }+ }++ fn enter(&self, _span: &span::Id) {}++ fn exit(&self, _span: &span::Id) {}+}++/// Collects the statement text of a `sqlx::query` event: its `summary` (the+/// first words) and, for a longer statement, `db.statement` (the whole text).+struct StatementText<'a>(&'a mut String);++impl Visit for StatementText<'_> {+ fn record_debug(&mut self, _field: &Field, _value: &dyn std::fmt::Debug) {}++ fn record_str(&mut self, field: &Field, value: &str) {+ if field.name() == "summary" || field.name() == "db.statement" {+ self.0.push_str(value);+ self.0.push(' ');+ }+ }+}++/// Collects every field of an event as text.+struct MessageText<'a>(&'a mut String);++impl Visit for MessageText<'_> {+ fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {+ if !self.0.is_empty() {+ self.0.push_str("; ");+ }+ self.0.push_str(&format!("{}={value:?}", field.name()));+ }+}diff --git a/rust/sdk/cocoindex/tests/postgres_source.rs b/rust/sdk/cocoindex/tests/postgres_source.rsindex 736c7019..1cca7069 100644--- a/rust/sdk/cocoindex/tests/postgres_source.rs+++ b/rust/sdk/cocoindex/tests/postgres_source.rs@@ -10,6 +10,7 @@ use std::time::{SystemTime, UNIX_EPOCH};use cocoindex::connectors::postgres;use cocoindex::{Ctx, Environment, Result};+use futures::TryStreamExt as _;use serde::{Deserialize, Serialize};cocoindex::context_key!(@@ -104,7 +105,10 @@ async fn postgres_source_reads_processes_and_reconciles_when_available() -> Resu// --- T1: typed read returns correct values + types ---{- let mut rows: Vec<SourceRow> = postgres::read_table(&db, &src_table).await?;+ let mut rows: Vec<SourceRow> = postgres::read_table(&db, &src_table)+ .await?+ .try_collect()+ .await?;rows.sort_by(|a, b| a.name.cmp(&b.name));assert_eq!(rows.len(), 2);assert_eq!(rows[0].name, "Headphones");@@ -117,6 +121,8 @@ async fn postgres_source_reads_processes_and_reconciles_when_available() -> Resu&src_table,postgres::ReadTableOptions::new().columns(["name"]),)+ .await?+ .try_collect().await?;rows.sort_by(|a, b| a.name.cmp(&b.name));assert_eq!(@@ -158,6 +164,8 @@ async fn postgres_source_reads_processes_and_reconciles_when_available() -> Resu"source_names",postgres::ReadTableOptions::new().pg_schema_name(src_schema.clone()),)+ .await?+ .try_collect().await?;assert_eq!(rows,@@ -188,7 +196,11 @@ async fn postgres_source_reads_processes_and_reconciles_when_available() -> Resu.execute(db.pool()).await.map_err(pe)?;+ // The read starts (the table exists); the unsupported column fails+ // the stream at its first row.let err = postgres::read_table::<serde_json::Value>(&db, &unsupported_table)+ .await?+ .try_collect::<Vec<_>>().await.unwrap_err();assert!(@@ -238,7 +250,10 @@ async fn postgres_source_reads_processes_and_reconciles_when_available() -> ResuSome(&out_schema_name),).await?;- let rows: Vec<SourceRow> = postgres::read_table(db, &src_table).await?;+ let rows: Vec<SourceRow> = postgres::read_table(db, &src_table)+ .await?+ .try_collect()+ .await?;let outs = ctx.mount_each(rows,diff --git a/rust/sdk/cocoindex/tests/postgres_target.rs b/rust/sdk/cocoindex/tests/postgres_target.rsindex 4c09292f..9fbdd27d 100644--- a/rust/sdk/cocoindex/tests/postgres_target.rs+++ b/rust/sdk/cocoindex/tests/postgres_target.rs@@ -1,10 +1,12 @@#![cfg(feature = "postgres")]use std::str::FromStr as _;+use std::sync::Arc;use std::time::{Duration, SystemTime, UNIX_EPOCH};use cocoindex::connectors::postgres;-use cocoindex::{Ctx, Environment, PreviewAction, Result, SchemaFields};+use cocoindex::{App, Ctx, Environment, PreviewAction, Result, SchemaFields};+use futures::TryStreamExt as _;use rust_decimal::Decimal;use serde::{Deserialize, Serialize};use sqlx::Row as _;@@ -13,6 +15,23 @@ cocoindex::context_key!(static PG: postgres::Database, key = "postgres_target_test_db");+mod common;++/// Build an app over a fresh state directory. Installs the SQL statement log+/// first: it has to be in place before the engine initializes its own tracing.+async fn build_app(db: &postgres::Database, name: &str) -> Result<(App, tempfile::TempDir)> {+ common::record_sql_statements();+ let tempdir = tempfile::tempdir().unwrap();+ let app = Environment::builder()+ .db_path(tempdir.path().join(".cocoindex_db"))+ .provide_key(&PG, db.clone())+ .build()+ .await?+ .app(name)+ .await?;+ Ok((app, tempdir))+}+#[derive(Clone, Serialize)]struct TestRow {id: i64,@@ -165,14 +184,7 @@ async fn postgres_table_target_reconciles_rows_when_available() -> Result<()> {.await.map_err(|e| cocoindex::Error::engine(format!("postgres cleanup: {e}")))?;- let tempdir = tempfile::tempdir().unwrap();- let app = Environment::builder()- .db_path(tempdir.path().join(".cocoindex_db"))- .provide_key(&PG, db.clone())- .build()- .await?- .app("PostgresTargetE2ETest")- .await?;+ let (app, _tempdir) = build_app(&db, "PostgresTargetE2ETest").await?;app.run({let schema = schema.clone();@@ -303,14 +315,7 @@ async fn postgres_table_target_previews_rows_when_available() -> Result<()> {let schema = format!("cocoindex_rust_preview_test_{nonce}");let db = postgres::Database::connect(&url).await?;- let tempdir = tempfile::tempdir().unwrap();- let app = Environment::builder()- .db_path(tempdir.path().join(".cocoindex_db"))- .provide_key(&PG, db.clone())- .build()- .await?- .app("PostgresTargetPreviewTest")- .await?;+ let (app, _tempdir) = build_app(&db, "PostgresTargetPreviewTest").await?;let rows = |labels: &[(i64, &str)]| {labels.iter()@@ -394,14 +399,7 @@ async fn postgres_sql_command_attachment_runs_setup_and_teardown_when_available(.await.map_err(|e| cocoindex::Error::engine(format!("postgres cleanup: {e}")))?;- let tempdir = tempfile::tempdir().unwrap();- let app = Environment::builder()- .db_path(tempdir.path().join(".cocoindex_db"))- .provide_key(&PG, db.clone())- .build()- .await?- .app("PostgresSqlCommandE2ETest")- .await?;+ let (app, _tempdir) = build_app(&db, "PostgresSqlCommandE2ETest").await?;// Declare the attachment β setup SQL creates the index.app.run({@@ -445,14 +443,7 @@ async fn postgres_undeclared_and_dropped_tables_are_removed_when_available() ->let schema = format!("cocoindex_rust_removal_test_{nonce}");let db = postgres::Database::connect(&url).await?;- let tempdir = tempfile::tempdir().unwrap();- let app = Environment::builder()- .db_path(tempdir.path().join(".cocoindex_db"))- .provide_key(&PG, db.clone())- .build()- .await?- .app("PostgresTableRemovalE2ETest")- .await?;+ let (app, _tempdir) = build_app(&db, "PostgresTableRemovalE2ETest").await?;let row = TestRow {id: 1,label: "one".to_string(),@@ -525,7 +516,10 @@ async fn postgres_read_table_items_keys_rows_when_available() -> Result<()> {}let mut items: Vec<(cocoindex::StableKey, SrcRow)> =- postgres::read_table_items(&db, &table, |row: &SrcRow| row.id).await?;+ postgres::read_table_items(&db, &table, |row: &SrcRow| row.id)+ .await?+ .try_collect()+ .await?;items.sort_by_key(|(_, row)| row.id);assert_eq!(items.len(), 2);assert_eq!(items[0].0, cocoindex::StableKey::Int(1));@@ -564,14 +558,7 @@ async fn postgres_vector_index_target_reconciles_when_available() -> Result<()>.await.map_err(|e| cocoindex::Error::engine(format!("postgres cleanup: {e}")))?;- let tempdir = tempfile::tempdir().unwrap();- let app = Environment::builder()- .db_path(tempdir.path().join(".cocoindex_db"))- .provide_key(&PG, db.clone())- .build()- .await?- .app("PostgresVectorIndexE2ETest")- .await?;+ let (app, _tempdir) = build_app(&db, "PostgresVectorIndexE2ETest").await?;app.run({let schema = schema.clone();@@ -616,14 +603,7 @@ async fn postgres_strips_nul_from_text_when_available() -> Result<()> {.await.map_err(|e| cocoindex::Error::engine(format!("postgres cleanup: {e}")))?;- let tempdir = tempfile::tempdir().unwrap();- let app = Environment::builder()- .db_path(tempdir.path().join(".cocoindex_db"))- .provide_key(&PG, db.clone())- .build()- .await?- .app("PostgresNulE2ETest")- .await?;+ let (app, _tempdir) = build_app(&db, "PostgresNulE2ETest").await?;// A label containing a U+0000 NUL β Postgres `text` cannot store it, so it// must be stripped before insert (otherwise the write errors).@@ -721,14 +701,7 @@ async fn postgres_adds_and_drops_columns_when_available() -> Result<()> {.execute(db.pool()).await.map_err(|e| cocoindex::Error::engine(format!("postgres cleanup: {e}")))?;- let tempdir = tempfile::tempdir().unwrap();- let app = Environment::builder()- .db_path(tempdir.path().join(".cocoindex_db"))- .provide_key(&PG, db.clone())- .build()- .await?- .app("PostgresEvolveE2ETest")- .await?;+ let (app, _tempdir) = build_app(&db, "PostgresEvolveE2ETest").await?;// v1: (id, label)app.run({@@ -805,14 +778,7 @@ async fn postgres_column_drop_retries_after_failed_attempt_when_available() -> R.execute(db.pool()).await.map_err(|e| cocoindex::Error::engine(format!("postgres cleanup: {e}")))?;- let tempdir = tempfile::tempdir().unwrap();- let app = Environment::builder()- .db_path(tempdir.path().join(".cocoindex_db"))- .provide_key(&PG, db.clone())- .build()- .await?- .app("PostgresDropRetryE2ETest")- .await?;+ let (app, _tempdir) = build_app(&db, "PostgresDropRetryE2ETest").await?;// v1: table with (id, label, extra).app.run({@@ -932,14 +898,7 @@ async fn postgres_bytea_round_trips_byte_arrays_when_available() -> Result<()> {.await.map_err(|e| cocoindex::Error::engine(format!("postgres cleanup: {e}")))?;- let tempdir = tempfile::tempdir().unwrap();- let app = Environment::builder()- .db_path(tempdir.path().join(".cocoindex_db"))- .provide_key(&PG, db.clone())- .build()- .await?- .app("PostgresByteaTest")- .await?;+ let (app, _tempdir) = build_app(&db, "PostgresByteaTest").await?;app.run({let schema = schema.clone();@@ -1023,14 +982,7 @@ async fn postgres_decimal_and_duration_round_trip_when_available() -> Result<()>.as_nanos();let schema = format!("cocoindex_rust_decimal_{nonce}");let db = postgres::Database::connect(&url).await?;- let tempdir = tempfile::tempdir().unwrap();- let app = Environment::builder()- .db_path(tempdir.path().join(".cocoindex_db"))- .provide_key(&PG, db.clone())- .build()- .await?- .app("PostgresDecimalTest")- .await?;+ let (app, _tempdir) = build_app(&db, "PostgresDecimalTest").await?;app.run({let schema = schema.clone();@@ -1122,14 +1074,7 @@ async fn postgres_schema_evolution_retype_and_pk_change_when_available() -> Resu.await.map_err(|e| cocoindex::Error::engine(format!("postgres cleanup: {e}")))?;- let tempdir = tempfile::tempdir().unwrap();- let app = Environment::builder()- .db_path(tempdir.path().join(".cocoindex_db"))- .provide_key(&PG, db.clone())- .build()- .await?- .app("PostgresEvoTest")- .await?;+ let (app, _tempdir) = build_app(&db, "PostgresEvoTest").await?;// v1: score is bigint.app.run({@@ -1344,3 +1289,265 @@ async fn postgres_from_row_resolves_vector_from_context_provider_when_available(.map_err(|e| cocoindex::Error::engine(format!("postgres cleanup: {e}")))?;Ok(())}++#[tokio::test]+async fn postgres_applies_a_batch_in_chunked_statements_when_available() -> Result<()> {+ let Ok(url) = std::env::var("POSTGRES_URL") else {+ eprintln!("skipping live Postgres batch test; POSTGRES_URL is not set");+ return Ok(());+ };+ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let schema = format!("cocoindex_rust_batch_test_{nonce}");+ let db = postgres::Database::connect(&url).await?;++ let (app, _tempdir) = build_app(&db, "PostgresBatchE2ETest").await?;++ // 4,500 rows: three upsert statements of at most 2,000 rows, not one+ // statement per row.+ let rows: Vec<TestRow> = (1..=4500)+ .map(|id| TestRow {+ id,+ label: format!("label {id}"),+ })+ .collect();+ app.run({+ let schema = schema.clone();+ move |ctx| declare_rows(ctx, schema, rows)+ })+ .await?;+ let table = format!("\"{schema}\".\"rows\"");+ let inserts = common::sql_statements_containing(&format!("INSERT INTO {table}"));+ assert_eq!(inserts.len(), 3, "{}", inserts.len());+ assert!(+ inserts+ .iter()+ .all(|s| s.contains("unnest($1::text[], $2::text[])")),+ "{}",+ inserts[0]+ );+ let (count, last): (i64, String) =+ sqlx::query_as(&format!("SELECT count(*), max(label) FROM {table}"))+ .fetch_one(db.pool())+ .await+ .map_err(|e| cocoindex::Error::engine(format!("postgres count: {e}")))?;+ assert_eq!((count, last.as_str()), (4500, "label 999"));++ // Keep 100 rows (updated): 4,400 deletes in three statements, 100+ // upserts in one.+ let kept: Vec<TestRow> = (1..=100)+ .map(|id| TestRow {+ id,+ label: format!("kept {id}"),+ })+ .collect();+ app.run({+ let schema = schema.clone();+ move |ctx| declare_rows(ctx, schema, kept)+ })+ .await?;+ let deletes = common::sql_statements_containing(&format!("DELETE FROM {table}"));+ assert_eq!(deletes.len(), 3, "{}", deletes.len());+ let inserts = common::sql_statements_containing(&format!("INSERT INTO {table}"));+ assert_eq!(inserts.len(), 4, "{}", inserts.len());+ let (count, last): (i64, String) =+ sqlx::query_as(&format!("SELECT count(*), max(label) FROM {table}"))+ .fetch_one(db.pool())+ .await+ .map_err(|e| cocoindex::Error::engine(format!("postgres count: {e}")))?;+ assert_eq!((count, last.as_str()), (100, "kept 99"));++ sqlx::query(&format!("DROP SCHEMA IF EXISTS \"{schema}\" CASCADE"))+ .execute(db.pool())+ .await+ .map_err(|e| cocoindex::Error::engine(format!("postgres cleanup: {e}")))?;+ Ok(())+}++#[derive(Clone, Serialize)]+struct AddressRow {+ id: i64,+ host: std::net::IpAddr,+ network: Option<String>,+}++async fn declare_addresses(ctx: Ctx, schema: String, rows: Vec<AddressRow>) -> Result<()> {+ let table = postgres::mount_table_target(+ &ctx,+ &PG,+ "addresses",+ postgres::TableSchema::new(+ [+ ("id", postgres::ColumnDef::new("bigint")),+ ("host", postgres::ColumnDef::new("inet")),+ ("network", postgres::ColumnDef::new("cidr").nullable()),+ ],+ ["id"],+ )?,+ Some(&schema),+ )+ .await?;+ for row in &rows {+ table.declare_row(&ctx, row)?;+ }+ Ok(())+}++#[tokio::test]+async fn postgres_inet_and_cidr_columns_round_trip_when_available() -> Result<()> {+ let Ok(url) = std::env::var("POSTGRES_URL") else {+ eprintln!("skipping live Postgres inet test; POSTGRES_URL is not set");+ return Ok(());+ };+ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let schema = format!("cocoindex_rust_inet_test_{nonce}");+ let db = postgres::Database::connect(&url).await?;++ let (app, _tempdir) = build_app(&db, "PostgresInetE2ETest").await?;+ app.run({+ let schema = schema.clone();+ move |ctx| {+ declare_addresses(+ ctx,+ schema,+ vec![+ AddressRow {+ id: 1,+ host: "10.1.2.3".parse().unwrap(),+ network: Some("10.0.0.0/8".to_string()),+ },+ AddressRow {+ id: 2,+ host: "2001:db8::1".parse().unwrap(),+ network: None,+ },+ ],+ )+ }+ })+ .await?;+ let rows: Vec<(i64, String, Option<String>)> = sqlx::query_as(&format!(+ "SELECT id, host(host), network::text FROM \"{schema}\".\"addresses\" ORDER BY id"+ ))+ .fetch_all(db.pool())+ .await+ .map_err(|e| cocoindex::Error::engine(format!("postgres select: {e}")))?;+ assert_eq!(+ rows,+ vec![+ (1, "10.1.2.3".to_string(), Some("10.0.0.0/8".to_string())),+ (2, "2001:db8::1".to_string(), None),+ ]+ );++ sqlx::query(&format!("DROP SCHEMA IF EXISTS \"{schema}\" CASCADE"))+ .execute(db.pool())+ .await+ .map_err(|e| cocoindex::Error::engine(format!("postgres cleanup: {e}")))?;+ Ok(())+}++async fn declare_rows_user_managed(ctx: Ctx, schema: String, rows: Vec<TestRow>) -> Result<()> {+ // The pending form's row provider resolves when the declaring component+ // commits (Python declares the table through `use_mount`): the table is+ // declared in one child, and the rows in a sibling mounted once that child+ // is ready.+ let declared: Arc<std::sync::Mutex<Option<postgres::TableTarget>>> = Arc::default();+ let handle = ctx+ .mount(&"table", {+ let declared = declared.clone();+ move |child| async move {+ let table = postgres::declare_table_target_with_options(+ &child,+ &PG,+ "user_rows",+ postgres::TableSchema::new(+ [+ ("id", postgres::ColumnDef::new("bigint")),+ ("label", postgres::ColumnDef::new("text")),+ ],+ ["id"],+ )?,+ Some(&schema),+ cocoindex::ManagedTargetOptions {+ managed_by: cocoindex::ManagedBy::User,+ },+ )?;+ *declared.lock().unwrap() = Some(table);+ Ok(())+ }+ })+ .await?;+ handle.ready().await?;+ let table = declared.lock().unwrap().take().expect("table declared");+ ctx.mount(&"rows", move |child| async move {+ for row in &rows {+ table.declare_row(&child, row)?;+ }+ Ok(())+ })+ .await?+ .ready()+ .await+}++#[tokio::test]+async fn postgres_declared_user_managed_table_keeps_table_manages_rows_when_available() -> Result<()>+{+ let Ok(url) = std::env::var("POSTGRES_URL") else {+ eprintln!("skipping live Postgres user-managed test; POSTGRES_URL is not set");+ return Ok(());+ };+ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let schema = format!("cocoindex_rust_user_managed_test_{nonce}");+ let db = postgres::Database::connect(&url).await?;+ let pe = |e: sqlx::Error| cocoindex::Error::engine(format!("postgres: {e}"));+ // The user owns the table: it exists before the first run.+ sqlx::query(&format!("CREATE SCHEMA \"{schema}\""))+ .execute(db.pool())+ .await+ .map_err(pe)?;+ sqlx::query(&format!(+ "CREATE TABLE \"{schema}\".\"user_rows\" (id bigint PRIMARY KEY, label text NOT NULL)"+ ))+ .execute(db.pool())+ .await+ .map_err(pe)?;++ let (app, _tempdir) = build_app(&db, "PostgresUserManagedE2ETest").await?;+ let row = TestRow {+ id: 1,+ label: "one".to_string(),+ };+ app.run({+ let schema = schema.clone();+ let row = row.clone();+ move |ctx| declare_rows_user_managed(ctx, schema, vec![row])+ })+ .await?;+ let labels: Vec<String> =+ sqlx::query_scalar(&format!("SELECT label FROM \"{schema}\".\"user_rows\""))+ .fetch_all(db.pool())+ .await+ .map_err(pe)?;+ assert_eq!(labels, vec!["one".to_string()]);++ // A run that no longer declares the table leaves it in place: the user+ // owns it.+ app.run(|_ctx| async { Ok(()) }).await?;+ assert!(table_exists(&db, &schema, "user_rows").await?);++ sqlx::query(&format!("DROP SCHEMA IF EXISTS \"{schema}\" CASCADE"))+ .execute(db.pool())+ .await+ .map_err(pe)?;+ Ok(())+}diff --git a/rust/sdk/cocoindex/tests/sqlite_target.rs b/rust/sdk/cocoindex/tests/sqlite_target.rsindex fbd2e88f..4c5de3cd 100644--- a/rust/sdk/cocoindex/tests/sqlite_target.rs+++ b/rust/sdk/cocoindex/tests/sqlite_target.rs@@ -16,6 +16,8 @@ cocoindex::context_key!(static DB: sqlite::Database, key = "sqlite_target_test_db");+mod common;+#[derive(Clone, Serialize)]struct Item {id: i64,@@ -49,7 +51,10 @@ async fn temp_db() -> (sqlite::Database, tempfile::TempDir) {(db, dir)}+/// Build an app over a fresh state directory. Installs the SQL statement log+/// first: it has to be in place before the engine initializes its own tracing.async fn build_app(db: &sqlite::Database) -> (App, tempfile::TempDir) {+ common::record_sql_statements();let dir = tempfile::tempdir().unwrap();let app = Environment::builder().db_path(dir.path().join(".cocoindex_db"))@@ -582,6 +587,7 @@ struct DocRow {}async fn build_app_with_embedder(db: &sqlite::Database, name: &str) -> (App, tempfile::TempDir) {+ common::record_sql_statements();let dir = tempfile::tempdir().unwrap();let app = Environment::builder().db_path(dir.path().join(".cocoindex_db"))@@ -709,3 +715,113 @@ async fn sqlite_connect_with_vec_creates_and_searches_a_vec0_table() {.unwrap();assert_eq!(nearest, vec![2]);}++async fn declare_batch(ctx: Ctx, items: Vec<Item>) -> Result<()> {+ let table = sqlite::mount_table_target(&ctx, &DB, "batch_items", item_schema()).await?;+ for it in &items {+ table.declare_row(&ctx, it)?;+ }+ Ok(())+}++#[tokio::test]+async fn sqlite_applies_a_batch_in_chunked_statements() {+ let (db, _dbdir) = temp_db().await;+ let (app, _appdir) = build_app(&db).await;++ // 20,000 rows of 2 columns: two upsert statements (16,383 rows fit the+ // 32,766-parameter bind limit), not one statement per row.+ let items: Vec<Item> = (1..=20_000).map(|id| item(id, &format!("l{id}"))).collect();+ app.run(|ctx| declare_batch(ctx, items)).await.unwrap();+ let inserts = common::sql_statements_containing("INSERT INTO \"batch_items\"");+ assert_eq!(inserts.len(), 2, "{}", inserts.len());+ let count: i64 = sqlx::query_scalar("SELECT count(*) FROM batch_items")+ .fetch_one(db.pool())+ .await+ .unwrap();+ assert_eq!(count, 20_000);++ // Keep 10 rows: 19,990 deletes in one `IN` list, 10 upserts in one statement.+ let kept: Vec<Item> = (1..=10).map(|id| item(id, &format!("k{id}"))).collect();+ app.run(|ctx| declare_batch(ctx, kept)).await.unwrap();+ let deletes = common::sql_statements_containing("DELETE FROM \"batch_items\"");+ assert_eq!(deletes.len(), 1, "{}", deletes.len());+ let inserts = common::sql_statements_containing("INSERT INTO \"batch_items\"");+ assert_eq!(inserts.len(), 3, "{}", inserts.len());+ assert_eq!(+ fetch(&db, "batch_items").await,+ (1..=10)+ .map(|id| (id, format!("k{id}")))+ .collect::<Vec<_>>()+ );+}++#[derive(Clone, Serialize)]+struct Pair {+ left: String,+ right: i64,+ label: String,+}++async fn declare_pairs(ctx: Ctx, pairs: Vec<Pair>) -> Result<()> {+ let schema = sqlite::TableSchema::new(+ [+ ("left", sqlite::ColumnDef::new("TEXT")),+ ("right", sqlite::ColumnDef::new("INTEGER")),+ ("label", sqlite::ColumnDef::new("TEXT")),+ ],+ ["left", "right"],+ )?;+ let table = sqlite::mount_table_target(&ctx, &DB, "pairs", schema).await?;+ for pair in &pairs {+ table.declare_row(&ctx, pair)?;+ }+ Ok(())+}++#[tokio::test]+async fn sqlite_composite_key_rows_are_deleted_by_row_value() {+ let (db, _dbdir) = temp_db().await;+ let (app, _appdir) = build_app(&db).await;+ fn pair(left: &str, right: i64) -> Pair {+ Pair {+ left: left.to_string(),+ right,+ label: format!("{left}{right}"),+ }+ }+ app.run(|ctx| declare_pairs(ctx, vec![pair("a", 1), pair("a", 2), pair("b", 1)]))+ .await+ .unwrap();+ // Dropping (a, 2) and (b, 1) must leave (a, 1): the keys are matched as+ // rows, not column by column.+ app.run(|ctx| declare_pairs(ctx, vec![pair("a", 1)]))+ .await+ .unwrap();+ let rows: Vec<(String, i64)> =+ sqlx::query_as("SELECT left, right FROM pairs ORDER BY left, right")+ .fetch_all(db.pool())+ .await+ .unwrap();+ assert_eq!(rows, vec![("a".to_string(), 1)]);+}++#[tokio::test]+async fn sqlite_connect_with_options_sets_the_busy_timeout() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("options.db");+ let db = sqlite::Database::connect_with_options(+ path.to_str().unwrap(),+ sqlite::ConnectOptions {+ busy_timeout: std::time::Duration::from_millis(1234),+ vec_extension: None,+ },+ )+ .await+ .unwrap();+ let timeout_ms: i64 = sqlx::query_scalar("PRAGMA busy_timeout")+ .fetch_one(db.pool())+ .await+ .unwrap();+ assert_eq!(timeout_ms, 1234);+}