Skip to main content

an5_adapters/
lib.rs

1//! AN5 adapters runtime for Rust.
2//!
3//! Provides [`An5Adapter`] (connection + dialect) and [`TableClient`] (ORM CRUD)
4//! on top of `sqlx`, plus a `base` module with dialect-aware SQL building blocks.
5//! Mirrors the Go / TypeScript / Python adapter packages.
6//!
7//! ```no_run
8//! use an5_adapters::{An5Adapter, FindManyArgs};
9//! use serde_json::json;
10//!
11//! # async fn run() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
12//! // Register the drivers this binary needs (swap in `sqlx::postgres::any::DRIVER`
13//! // or `sqlx::mysql::any::DRIVER` and enable the matching cargo feature), then
14//! // hand the connection string to the adapter.
15//! sqlx::any::install_drivers(&[sqlx::sqlite::any::DRIVER])?;
16//! let db = An5Adapter::connect("sqlite:file:app.sqlite?mode=rwc").await?;
17//!
18//! // Dynamic access, the Rust equivalent of `db.user` in TypeScript.
19//! let users = db
20//!     .table("User")
21//!     .find_many(&FindManyArgs {
22//!         r#where: Some(json!({ "email": { "contains": "@example.com" } })),
23//!         take: 10,
24//!         ..Default::default()
25//!     })
26//!     .await?;
27//! # Ok(()) }
28//! ```
29
30pub mod adapter;
31pub mod base;
32
33pub use adapter::{
34    AggregateArgs, An5Adapter, CountArgs, CreateArgs, CreateManyArgs, DeleteManyArgs, FindManyArgs,
35    GroupByArgs, Result, RowMap, TableClient, UpdateArgs, UpdateManyArgs, UpsertArgs,
36    VectorSearchArgs, ViewClient,
37};
38pub use base::{
39    add_table_override, build_order_by, build_where, cosine_similarity, dot_product,
40    euclidean_distance, get_fields_for_model, get_model_to_table, get_relations_for_model,
41    resolve_table, set_adapter_metadata, vector_distance, AdapterMetadata, Dialect, RelationDef,
42    Where,
43};
44
45/// Default connection string: `DATABASE_URL` or a local MSSQL fallback.
46pub fn get_default_connection_string() -> String {
47    std::env::var("DATABASE_URL").unwrap_or_else(|_| {
48        "Server=localhost;Database=master;Trusted_Connection=True;TrustServerCertificate=True;"
49            .to_string()
50    })
51}
52
53/// Build an adapter using [`get_default_connection_string`].
54pub async fn create_an5_adapter(connection_string: Option<&str>) -> Result<An5Adapter> {
55    An5Adapter::connect(connection_string.unwrap_or(&get_default_connection_string())).await
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn default_connection_string_falls_back_to_mssql() {
64        // DATABASE_URL may be set in CI; only assert the shape when it is not.
65        if std::env::var("DATABASE_URL").is_err() {
66            assert!(get_default_connection_string().starts_with("Server=localhost"));
67        }
68    }
69
70    #[test]
71    fn exports_are_reachable() {
72        assert_eq!(Dialect::detect("sqlite::memory:"), Dialect::Sqlite);
73        assert!(!resolve_table("Whatever").is_empty());
74    }
75}