Skip to main content

ArcadeDbClient

Struct ArcadeDbClient 

Source
pub struct ArcadeDbClient { /* private fields */ }
Expand description

A lightweight gRPC client for ArcadeDB.

Wraps both the data and admin service clients with convenience methods for SQL commands and queries. Clone (cheap — shares the underlying tonic Channel) and all methods take &self, so it can be held by a Clone repo and shared across tasks.

Implementations§

Source§

impl ArcadeDbClient

Source

pub fn to_database(&self, database: impl Into<String>) -> DatabaseClient

Bind this client to database, producing a DatabaseClient whose methods omit the database parameter. Cheap: clones the channel handle.

Source§

impl ArcadeDbClient

Source

pub async fn execute_language( &self, database: &str, language: &str, command: &str, ) -> Result<ExecuteCommandResponse>

Execute a command in the given query language (“sql” or “cypher”).

Returns the server response including affected records and write stats.

Source

pub async fn execute( &self, database: &str, command: &str, ) -> Result<ExecuteCommandResponse>

Execute a SQL command (DDL, INSERT, UPDATE, DELETE).

Returns the server response including affected records and write stats.

Source

pub async fn execute_with_values( &self, database: &str, command: &str, parameters: impl Into<Params>, ) -> Result<ExecuteCommandResponse>

execute with bound :name parameters — the command-RPC analogue of query_with_values. Prefer this whenever the command references caller-supplied values (user names, urls, ids): no literal escaping, no injection surface. Build parameter values with Params (e.g. the params! macro) or a RecordEncode DTO’s ToGrpcRecord::to_param_map.

Source

pub async fn cypher_query( &self, database: &str, query: &str, ) -> Result<QueryResult>

Execute a Cypher read query (MATCH + RETURN, etc.).

Uses the streaming query RPC with language=“cypher”.

Source

pub async fn cypher_execute( &self, database: &str, command: &str, ) -> Result<ExecuteCommandResponse>

Execute a Cypher write command (MATCH + SET, etc.).

Uses the execute_command RPC with language set to “opencypher” (the variant that ArcadeDB accepts for write operations).

Source§

impl ArcadeDbClient

Source

pub async fn query(&self, database: &str, query: &str) -> Result<QueryResult>

Execute a SQL query and return the result records with server-side timing.

Source

pub async fn query_with_values( &self, database: &str, query: &str, parameters: impl Into<Params>, ) -> Result<QueryResult>

Execute a SQL query with bound parameters (the :name placeholders in the query are filled from parameters).

Prefer this over query whenever the query references caller-supplied values — bound params avoid SQL-injection concerns and let ArcadeDB cache the parsed query plan. The vector-search operators (vector.sparseNeighbors, vector.fuse, SEARCH_INDEX) in particular expect array-valued params for the query token/weight vectors.

Build parameter values with Params (e.g. the params! macro), or assemble list/map values directly from the proto types re-exported at the crate root.

Source

pub async fn lookup_by_rid( &self, database: &str, rid: &Link, ) -> Result<Option<GrpcRecord>>

Fetch one record by rid — the O(1) path: direct bucket/position dereference, no SQL parsing, no index traversal. The fastest read ArcadeDB offers; prefer it whenever the caller already holds the record’s Link (a prior query’s @rid, an edge’s @in/@out — all record intrinsics).

Durability note: rids are stable for a database’s lifetime but may shift across rebuilds/backup-restores — treat them as within-lifetime handles, never as persisted identifiers. Domain keys (e.g. a UNIQUE index column) remain the durable identity.

Source

pub async fn lookup<T>(&self, database: &str, rid: &Link) -> Result<Option<T>>
where T: for<'a> TryFrom<&'a GrpcRecord, Error = RecordDecodeError>,

lookup_by_rid decoded into an owned DTO (T: TryFrom<&GrpcRecord>, i.e. an owned RecordDecode struct).

Source

pub async fn fetch_optional<T>( &self, database: &str, query: &str, parameters: impl Into<Params>, ) -> Result<Option<T>>
where T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,

Typed fetch of at most one row: Ok(None) on an empty result, a decode error only when a row exists but does not match T.

Pair point-lookups with LIMIT 1 — the call decodes the first row but the RPC still materializes the whole result set.

Source

pub async fn fetch_one<T>( &self, database: &str, query: &str, parameters: impl Into<Params>, ) -> Result<T>
where T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,

fetch_optional with a one-row contract: an empty result is ArcadeDbError::NotFound, not Ok(None).

Same wire-cost note: keep the query itself to one row (LIMIT 1) so the RPC materializes only what is decoded.

Source

pub async fn query_scalar<T>( &self, database: &str, query: &str, parameters: impl Into<Params>, ) -> Result<Option<T>>
where T: for<'de> FromGrpcValue<'de>,

Decode the single column of a single-row query (SELECT count(*), SELECT max(x), …). Ok(None) when the query returned no row.

The column is identified by position: the row must carry exactly one property (a defensive guard — the proto row is a map, so “first column” is only well-defined for one-column rows), decoded via FromGrpcValue. Aggregate queries return a single row anyway (SELECT count(*)); anything wide belongs in fetch_optional.

Source

pub async fn write_returning_optional<T>( &self, database: &str, command: &str, parameters: impl Into<Params>, ) -> Result<Option<T>>
where T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,

Run a write command that returns the stored row and decode it. The command must be a form whose response carries records:

  • INSERT INTO t SET … — returns the stored record as-is (the RPC runs with return_rows = true; no RETURN clause exists for INSERT — trailing … RETURN AFTER is a syntax error).
  • UPDATE t SET … RETURN AFTER WHERE … — RETURN BEFORE|AFTER sits between the SET/UPSERT part and WHERE, not at statement end. The UPSERT variant additionally requires the WHERE column to carry an index.

Ok(None) when the statement matched nothing (RETURN AFTER on a zero-row UPDATE); use upsert_returning for the strict one-row contract.

Replaces the execute→extract→decode template at every returning-write call site.

Source

pub async fn upsert_returning<T>( &self, database: &str, command: &str, parameters: impl Into<Params>, ) -> Result<T>
where T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,

write_returning_optional with a one-row contract (empty result → ArcadeDbError::NotFound).

Source

pub async fn lookup_by_key<T>( &self, database: &str, type_name: &str, key: &[(&str, GrpcValue)], ) -> Result<Option<T>>
where T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>,

Typed lookup by a (single or composite) key on type_name: builds SELECT FROM {type} WHERE k1 = :k0 AND k2 = :k1 LIMIT 1 with bound parameters — no identity concept imported, just the Java API’s lookupByKey semantics over plain equality.

Property/type names are validated identifiers (ASCII alphanumerics and _); values are bound, never interpolated.

Source

pub async fn count_type(&self, database: &str, type_name: &str) -> Result<i64>

Count all records of a type (polymorphic — ArcadeDB SELECT FROM type includes subtypes), the Java API’s countType. One query_scalar roundtrip.

Source§

impl ArcadeDbClient

Source

pub async fn create_record( &self, database: &str, class_name: &str, props: Vec<(&str, GrpcValue)>, ) -> Result<CreateRecordResponse>

Create a record of class_name from (property, value) pairs — the typed single-record counterpart of INSERT-INTO SQL. Returns the server-assigned rid.

Source

pub async fn update_record_partial( &self, database: &str, rid: &Link, props: impl Into<Params>, ) -> Result<bool>

Partially update a record by rid: only the given properties change, everything else is left untouched (UpdateRecord’s partial payload). The typed alternative to escaped-literal SET SQL; pair with changed_param_map for diff-based writes from DTOs.

Returns whether a record was actually updated (unknown rid → false).

Source

pub async fn delete_record(&self, database: &str, rid: &Link) -> Result<bool>

Delete a record by rid. Returns whether a record was actually removed (already-absent rid → false).

Source

pub async fn bulk_insert( &self, database: &str, target_class: &str, key_columns: &[&str], rows: Vec<GrpcRecord>, ) -> Result<InsertSummary>

Bulk-insert rows into target_class via the gRPC BulkInsert RPC — a single round trip for many records. key_columns + ignore-conflict make it idempotent (safe to re-run on a non-empty table). Used by the test fixture generators to seed data efficiently.

Returns the server’s InsertSummary (inserted/updated/ignored counts).

Source

pub async fn bulk_upsert( &self, database: &str, target_class: &str, key_columns: &[&str], update_columns_on_conflict: &[&str], rows: Vec<GrpcRecord>, ) -> Result<InsertSummary>

Bulk upsert rows into target_class via the gRPC BulkInsert RPC with CONFLICT_UPDATE (mode 1): key columns are matched against existing records and the non-key columns are overwritten. One round trip for many records — the batch analogue of UPDATE ... UPSERT, which the SQL path only accepts when the WHERE columns carry an index.

key_columns must be covered by an index for conflict detection to be reliable (a UNIQUE index on the match key is the sanctioned shape). update_columns_on_conflict limits which columns are overwritten on a match; empty = merge all non-key columns present on the incoming record.

Returns the server’s InsertSummary (inserted/updated/ignored counts).

Source

pub async fn bulk_upsert_dtos<T>( &self, database: &str, target_class: &str, rows: Vec<T>, ) -> Result<InsertSummary>
where T: ToGrpcRecord + Send,

The typed bulk_upsert: rows are RecordEncode DTOs, the conflict key comes from the DTO’s #[record(key)] fields (ToGrpcRecord::KEY_COLUMNS) — the call site cannot disagree with the DTO about the identity — and every present column is merged on conflict (absent Options keep their stored values).

Errors up front when the DTO declares no key columns.

Source§

impl ArcadeDbClient

Source

pub async fn stream_query<F>( &self, database: &str, query: &str, on_batch: F, ) -> Result<StreamSummary>

Execute a SQL query on the server-streaming RPC (StreamQuery), feeding each result batch to on_batch as it arrives — ranking, filtering, and discarding happen per batch while the server produces the next one, instead of materializing the entire result set client-side first.

The callback contract is consume_stream’s: borrowed views are consumed inside the call, and ControlFlow::Break cancels the stream early (the summary reports truncated). Prefer this over query for large candidate sets; keep query for small reads.

Source

pub async fn stream_query_with_values<F>( &self, database: &str, query: &str, parameters: impl Into<Params>, on_batch: F, ) -> Result<StreamSummary>

stream_query with bound :name parameters — same parameter-safety and plan-caching notes as query_with_values.

Source

pub async fn stream_query_with_options<F>( &self, database: &str, query: &str, parameters: impl Into<Params>, options: StreamOptions, on_batch: F, ) -> Result<StreamSummary>

stream_query_with_values with explicit execution knobs — the StreamOptions knobs (batch_size, retrieval_mode, projections) the plain methods leave at server defaults.

Source

pub async fn stream_query_rows<T, F>( &self, database: &str, query: &str, parameters: impl Into<Params>, on_row: F, ) -> Result<StreamSummary>
where T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>, F: FnMut(T) -> ControlFlow<()>,

Typed row streaming: each record is decoded into T (the RecordDecode bound) and passed to on_row as it arrives — the rows contract without buffering the result set.

ControlFlow::Break stops the stream early (summary reports truncated). A row that does not decode fails the whole call with ArcadeDbError::Decode — fail-fast, matching the buffered path’s whole-query error semantics.

Source

pub async fn stream_query_rows_with_options<T, F>( &self, database: &str, query: &str, parameters: impl Into<Params>, options: StreamOptions, on_row: F, ) -> Result<StreamSummary>
where T: for<'r> TryFrom<&'r GrpcRecord, Error = RecordDecodeError>, F: FnMut(T) -> ControlFlow<()>,

Source§

impl ArcadeDbClient

Source

pub async fn begin_transaction( &self, database: &str, isolation: TransactionIsolation, ) -> Result<String>

Begin an explicit server-side transaction.

Returns a transaction id; pass it to execute_in_transaction and query_in_transaction, then finish with commit_transaction or rollback_transaction.

NOTE: ArcadeDB keeps schema changes (DDL) outside transaction scope — they commit immediately in their own sub-transaction. Use the explicit transaction for record operations (the copy phase of an override rebuild) and verify the copy before committing; do not rely on it to make batch DDL atomic.

Source

pub async fn execute_in_transaction( &self, database: &str, language: &str, command: &str, transaction_id: &str, ) -> Result<ExecuteCommandResponse>

Execute a command inside an explicitly-begun transaction.

The command runs with the transaction attached; it is only durable when the transaction is later committed. (Schema statements still commit immediately — see begin_transaction.)

Source

pub async fn query_in_transaction( &self, database: &str, query: &str, transaction_id: &str, ) -> Result<QueryResult>

Run a read query inside an explicitly-begun transaction, so the caller can verify what the transaction has written before committing.

Source

pub async fn commit_transaction( &self, database: &str, transaction_id: &str, ) -> Result<()>

Commit an explicitly-begun transaction, making its record operations durable.

Source

pub async fn rollback_transaction( &self, database: &str, transaction_id: &str, ) -> Result<()>

Roll back an explicitly-begun transaction, discarding its record operations.

Source

pub async fn transaction( &self, database: &str, isolation: TransactionIsolation, ) -> Result<Transaction<'_>>

Begin an explicit server-side transaction as a guard (Transaction).

The guard owns the transaction lifecycle: run commands with Transaction::execute / Transaction::query, then finish with Transaction::commit or Transaction::rollback. Dropping the guard without finishing fires a best-effort background rollback (the server’s idle-reaper is the backstop), so forgotten transactions cannot leak.

Source

pub async fn run_transaction<T, F, Fut>( &self, database: &str, isolation: TransactionIsolation, retries: u32, body: F, ) -> Result<T>
where F: Fn(TxCommands) -> Fut, Fut: Future<Output = Result<T>>,

Run body inside an explicit transaction, retrying the whole block up to retries extra times when the server reports an MVCC conflict (concurrent modification) — the Java API’s transaction(txBlock, retries). A fresh transaction is begun per attempt; every failed attempt is rolled back before retrying.

Conflict detection is best-effort message matching (the gRPC surface exposes no structured conflict code yet): concurrent, mvcc, or needretry in the server message. Non-conflict errors and exhausted retries return the last error, transaction rolled back.

DDL is outside transaction scope (see begin_transaction) — record operations only. Pairs with the Transaction drop-guard: the guard makes multi-statement units atomic, this makes them self-healing under concurrent writers.

Source§

impl ArcadeDbClient

Source

pub async fn connect( addr: &str, user: &str, pass: &str, database: &str, ) -> Result<Self>

Connect to an ArcadeDB server over gRPC.

addr should be host:port (e.g. 127.0.0.1:50051). Uses an insecure (plaintext) channel — the standard for dev setups. For TLS, deadlines, or a configurable connect/retry policy, build a ClientOptions and call connect_with.

The database parameter is used for the x-arcade-database metadata header, which the server-side GrpcAuthInterceptor checks to determine which database’s user list to validate against.

Source

pub async fn connect_with(options: ClientOptions) -> Result<Self>

connect with explicit ClientOptions: TLS, connect timeout/attempts/backoff, and the default per-request gRPC deadline.

Credential validation is up front and typed: metadata-invalid credentials (e.g. non-ASCII) are an ArcadeDbError::InvalidInput, never a panic.

Source

pub fn database(&self) -> &str

The database name this client is authenticated against.

Source

pub fn admin(&self) -> Admin

Domain facades (admin / scan / batch / cache) — capability groups off the root client. Cheap: each wraps a clone of this client’s shared channel.

Source

pub fn scan(&self) -> Scan

scan facade — full-type/bucket iteration.

Source

pub fn batch(&self) -> Batch

batch facade — sqlscript batches, edge upserts, idempotent DDL apply.

Trait Implementations§

Source§

impl Clone for ArcadeDbClient

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more