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