wasm_sql/core/bindings/
pool.rs1use std::sync::Arc;
2
3use tokio::sync::RwLock;
4
5use crate::core::bindings::{
6 SqlHostState,
7 connection::ConnectionImpl,
8 transaction::TransactionImpl,
9 generated::wasm_sql::core::{pool::{Connection, PoolState}, transaction::Transaction, util_types::Error},
10};
11
12impl crate::core::bindings::generated::wasm_sql::core::pool::Host for SqlHostState {
13 async fn get_pool_state(&mut self) -> PoolState {
14 let pool = &self.sql_db.pool;
15 PoolState {
16 size: pool.size() as u64,
17 idle: pool.num_idle() as u64,
18 }
19 }
20}
21
22impl crate::core::bindings::generated::wasm_sql::core::pool::HostWithStore for SqlHostState {
23 async fn begin_transaction<T>(
24 accessor: &wasmtime::component::Accessor<T, Self>,
25 ) -> Result<wasmtime::component::Resource<Transaction>, Error> {
26 let pool = accessor.with(|mut access| access.get().sql_db.pool.clone());
27 let tx = pool.begin().await?;
28 let tx_impl = TransactionImpl::Tx(Arc::new(RwLock::new(Some(tx))));
29
30 let tx_resource = accessor.with(|mut access| {
31 let state = access.get();
32
33 state.table.push(tx_impl)
34 })?;
35
36 Ok(tx_resource)
37 }
38
39 async fn acquire_connection<T>(
40 accessor: &wasmtime::component::Accessor<T, Self>,
41 ) -> Result<wasmtime::component::Resource<Connection>, Error> {
42 let pool = accessor.with(|mut access| access.get().sql_db.pool.clone());
43 let conn = pool.acquire().await?;
44
45 let conn_impl = ConnectionImpl {
46 connection: Arc::new(RwLock::new(conn)),
47 };
48
49 let resource = accessor.with(|mut access| {
50 let state = access.get();
51 state.table.push(conn_impl)
52 })?;
53
54 Ok(resource)
55 }
56}