libsql_orm/
database.rs

1//! Database connection and query execution
2//!
3//! This module handles the connection to libsql databases and provides
4//! query execution capabilities for Cloudflare Workers.
5
6#[cfg(target_arch = "wasm32")]
7use libsql::wasm::{CloudflareSender, Connection, Rows};
8#[cfg(not(target_arch = "wasm32"))]
9use libsql::{Builder, Connection, Rows};
10
11/// Database connection wrapper for libsql in Cloudflare Workers
12///
13/// Provides a high-level interface for connecting to and interacting with
14/// libsql databases in WebAssembly environments, specifically optimized
15/// for Cloudflare Workers.
16///
17/// # Examples
18///
19/// ```no_run
20/// use libsql_orm::Database;
21///
22/// async fn connect_example() -> Result<(), Box<dyn std::error::Error>> {
23///     let db = Database::new_connect(
24///         "libsql://your-db.turso.io",
25///         "your-auth-token"
26///     ).await?;
27///     Ok(())
28/// }
29/// ```
30pub struct Database {
31    #[cfg(target_arch = "wasm32")]
32    pub inner: Connection<CloudflareSender>,
33    #[cfg(not(target_arch = "wasm32"))]
34    pub inner: Connection,
35}
36
37#[cfg(target_arch = "wasm32")]
38impl From<Connection<CloudflareSender>> for Database {
39    fn from(inner: Connection<CloudflareSender>) -> Self {
40        Self { inner }
41    }
42}
43
44#[cfg(not(target_arch = "wasm32"))]
45impl From<Connection> for Database {
46    fn from(inner: Connection) -> Self {
47        Self { inner }
48    }
49}
50
51impl Database {
52    /// Creates a new database connection to a libsql database
53    ///
54    /// # Arguments
55    ///
56    /// * `url` - The database URL (e.g., "libsql://your-db.turso.io")
57    /// * `token` - The authentication token for the database
58    ///
59    /// # Returns
60    ///
61    /// Returns a `Result` containing the `Database` instance or a `libsql::Error`
62    ///
63    /// # Examples
64    ///
65    /// ```no_run
66    /// use libsql_orm::Database;
67    ///
68    /// async fn example() -> Result<(), Box<dyn std::error::Error>> {
69    ///     let db = Database::new_connect(
70    ///         "libsql://your-db.turso.io",
71    ///         "your-auth-token"
72    ///     ).await?;
73    ///     println!("Connected to database successfully!");
74    ///     Ok(())
75    /// }
76    /// ```
77    pub async fn new_connect(url: &str, token: &str) -> std::result::Result<Self, libsql::Error> {
78        #[cfg(target_arch = "wasm32")]
79        let conn = Connection::open_cloudflare_worker(url.to_string(), token.to_string());
80        #[cfg(not(target_arch = "wasm32"))]
81        let conn = Builder::new_remote(url.to_string(), token.to_string())
82            .build()
83            .await?
84            .connect()?;
85        conn.execute("SELECT 1", ()).await.map(|_| Self::from(conn))
86    }
87
88    /// Executes a SQL query with parameters
89    ///
90    /// # Arguments
91    ///
92    /// * `sql` - The SQL query string
93    /// * `params` - Vector of parameters to bind to the query
94    ///
95    /// # Returns
96    ///
97    /// Returns a `Result` containing `Rows` iterator or a `libsql::Error`
98    ///
99    /// # Examples
100    ///
101    /// ```no_run
102    /// use libsql_orm::Database;
103    ///
104    /// async fn query_example(db: &Database) -> Result<(), Box<dyn std::error::Error>> {
105    ///     let rows = db.query(
106    ///         "SELECT * FROM users WHERE age > ?",
107    ///         vec![libsql::Value::Integer(18)]
108    ///     ).await?;
109    ///     Ok(())
110    /// }
111    /// ```
112    pub async fn query(
113        &self,
114        sql: &str,
115        params: Vec<libsql::Value>,
116    ) -> Result<Rows, libsql::Error> {
117        self.inner.query(sql, params).await
118    }
119}