jdbc/wrapper/sql/
datasource.rs

1use super::connection::Connection;
2use crate::errors::Error;
3use jni::{
4    objects::{AutoLocal, JMethodID, JObject, JValueGen},
5    signature::ReturnType,
6    AttachGuard, JNIEnv,
7};
8pub struct DataSource<'local, 'obj> {
9    inner: &'obj JObject<'local>,
10    env: JNIEnv<'local>,
11    get_conn: JMethodID,
12}
13
14impl<'local, 'obj_ref> DataSource<'local, 'obj_ref> {
15    pub fn from_ref(
16        env: &mut JNIEnv<'local>,
17        datasource: &'obj_ref JObject<'local>,
18    ) -> Result<Self, Error> {
19        let class = AutoLocal::new(env.find_class("javax/sql/DataSource")?, env);
20        let get_conn: jni::objects::JMethodID =
21            env.get_method_id(&class, "getConnection", "()Ljava/sql/Connection;")?;
22        let env = unsafe { env.unsafe_clone() };
23        Ok(DataSource {
24            inner: datasource,
25            env,
26            get_conn,
27        })
28    }
29
30    pub fn get_connection(
31        &mut self,
32        guard: AttachGuard<'local>,
33    ) -> Result<Connection<'local>, Error> {
34        let conn = unsafe {
35            self.env
36                .call_method_unchecked(&self.inner, self.get_conn, ReturnType::Object, &[])
37        }?;
38
39        if let JValueGen::Object(obj) = conn {
40            return Ok(Connection::from_ref(guard, obj)?);
41        }
42        return Err(Error::JniError(jni::errors::Error::WrongJValueType(
43            "unknown",
44            "java.sql.Connection",
45        )));
46    }
47}