Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sqlite #1

Merged
merged 5 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,26 @@ readme = "README.md"

[features]
default = ["all"]
all = ["timers", "url", "console"]
all = ["timers", "url", "console", "sqlite"]

timers = []
timers = ["tokio/time"]
url = []
console = []
sqlite = ["sqlx"]

[dependencies]
either = "1"
log = { version = "0.4" }
rquickjs = { version = "0.6", features = ["either", "macro", "futures"] }
rquickjs = { version = "0.6", features = [
"array-buffer",
"either",
"macro",
"futures",
] }
sqlx = { version = "0.8", default-features = false, features = [
"sqlite",
"runtime-tokio",
], optional = true }
tokio = { version = "1" }

[dev-dependencies]
Expand Down
56 changes: 56 additions & 0 deletions src/ffi/c_string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use std::mem;
use std::{ffi::c_char, slice, str};

use rquickjs::{qjs, Error, Exception, Result, String, Value};

#[derive(Debug)]
pub struct CString<'js> {
ptr: *const c_char,
len: usize,
value: Value<'js>,
}

#[allow(dead_code)]
impl<'js> CString<'js> {
pub fn from_string(string: String<'js>) -> Result<Self> {
let mut len = mem::MaybeUninit::uninit();
let ptr = unsafe {
qjs::JS_ToCStringLen(
string.ctx().as_raw().as_ptr(),
len.as_mut_ptr(),
string.as_raw(),
)
};
if ptr.is_null() {
// Might not ever happen but I am not 100% sure
// so just incase check it.
return Err(Error::Unknown);
}
let len = unsafe { len.assume_init() };
Ok(Self {
ptr,
len,
value: string.into_value(),
})
}

pub fn as_ptr(&self) -> *const c_char {
self.ptr
}

pub fn len(&self) -> usize {
self.len
}

pub fn as_str(&self) -> Result<&str> {
let bytes = unsafe { slice::from_raw_parts(self.ptr as *const u8, self.len) };
str::from_utf8(bytes)
.map_err(|_| Exception::throw_message(self.value.ctx(), "Invalid UTF-8"))
}
}

impl<'js> Drop for CString<'js> {
fn drop(&mut self) {
unsafe { qjs::JS_FreeCString(self.value.ctx().as_raw().as_ptr(), self.ptr) };
}
}
35 changes: 35 additions & 0 deletions src/ffi/c_vec.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use rquickjs::{Result, TypedArray, Value};

use crate::utils::result::ResultExt;

#[derive(Debug)]
pub struct CVec<'js> {
ptr: *const u8,
len: usize,
#[allow(dead_code)]
value: Value<'js>,
}

#[allow(dead_code)]
impl<'js> CVec<'js> {
pub fn from_array(array: TypedArray<'js, u8>) -> Result<Self> {
let raw = array.as_raw().or_throw(array.ctx())?;
Ok(Self {
ptr: raw.ptr.as_ptr(),
len: raw.len,
value: array.into_value(),
})
}

pub fn as_ptr(&self) -> *const u8 {
self.ptr
}

pub fn len(&self) -> usize {
self.len
}

pub fn as_slice(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
}
}
5 changes: 5 additions & 0 deletions src/ffi/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pub use self::c_string::CString;
pub use self::c_vec::CVec;

mod c_string;
mod c_vec;
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
pub use self::modules::*;

mod ffi;
mod modules;
#[cfg(test)]
mod test;
mod utils;
2 changes: 2 additions & 0 deletions src/modules/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#[cfg(feature = "console")]
pub mod console;
#[cfg(feature = "sqlite")]
pub mod sqlite;
#[cfg(feature = "timers")]
pub mod timers;
#[cfg(feature = "url")]
Expand Down
62 changes: 62 additions & 0 deletions src/modules/sqlite/argument.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
use rquickjs::{Ctx, Exception, FromJs, Result, TypedArray};
use sqlx::query::Query;
use sqlx::sqlite::SqliteArguments;
use sqlx::Sqlite;

use crate::ffi::{CString, CVec};
use crate::utils::result::ResultExt;

#[derive(Debug)]
pub enum Argument<'js> {
Null,
Integer(i64),
Real(f64),
Text(CString<'js>),
Blob(CVec<'js>),
}

impl<'js> FromJs<'js> for Argument<'js> {
fn from_js(ctx: &Ctx<'js>, value: rquickjs::Value<'js>) -> Result<Self> {
if value.is_undefined() || value.is_null() {
return Ok(Argument::Null);
} else if let Some(int) = value.as_int() {
return Ok(Argument::Integer(int as i64));
} else if let Some(big_int) = value.as_big_int() {
return Ok(Argument::Integer(big_int.clone().to_i64()?));
} else if let Some(float) = value.as_float() {
return Ok(Argument::Real(float));
} else if let Some(string) = value.as_string() {
return Ok(Argument::Text(CString::from_string(string.clone())?));
} else if let Some(object) = value.as_object() {
if object.as_typed_array::<u8>().is_some() {
// Lifetime issue: https://github.com/DelSkayn/rquickjs/issues/356
return Ok(Argument::Blob(CVec::from_array(
TypedArray::<u8>::from_value(value.clone()).or_throw(ctx)?,
)?));
}
}
Err(Exception::throw_type(
ctx,
&["Value of type '", value.type_name(), "' is not supported"].concat(),
))
}
}

impl<'js> Argument<'js> {
pub fn try_bind<'q>(
&'q self,
ctx: &Ctx<'js>,
query: &mut Query<'q, Sqlite, SqliteArguments<'q>>,
) -> Result<()>
where
'js: 'q,
{
match self {
Argument::Null => query.try_bind::<Option<i32>>(None).or_throw(ctx),
Argument::Integer(int) => query.try_bind(*int).or_throw(ctx),
Argument::Real(float) => query.try_bind(*float).or_throw(ctx),
Argument::Text(string) => query.try_bind(string.as_str()?).or_throw(ctx),
Argument::Blob(blob) => query.try_bind(blob.as_slice()).or_throw(ctx),
}
}
}
113 changes: 113 additions & 0 deletions src/modules/sqlite/database.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
use rquickjs::{Ctx, Result};
use sqlx::{Executor, SqlitePool};

use super::Statement;
use crate::utils::result::ResultExt;

#[rquickjs::class]
#[derive(rquickjs::class::Trace)]
pub struct Database {
#[qjs(skip_trace)]
pool: SqlitePool,
}

impl Database {
pub fn new(pool: SqlitePool) -> Self {
Self { pool }
}
}

#[rquickjs::methods(rename_all = "camelCase")]
impl Database {
async fn exec(&self, ctx: Ctx<'_>, sql: String) -> Result<()> {
sqlx::raw_sql(&sql)
.execute(&self.pool)
.await
.or_throw(&ctx)?;
Ok(())
}

async fn prepare(&self, ctx: Ctx<'_>, sql: String) -> Result<Statement> {
let stmt = sqlx::Statement::to_owned(&self.pool.prepare(&sql).await.or_throw(&ctx)?);
Ok(Statement::new(stmt, self.pool.clone()))
}

async fn close(&mut self) -> Result<()> {
self.pool.close().await;
Ok(())
}
}

#[cfg(test)]
mod tests {
use rquickjs::CatchResultExt;

use crate::sqlite::SqliteModule;
use crate::test::{call_test, test_async_with, ModuleEvaluator};

#[tokio::test]
async fn test_database_exec() {
test_async_with(|ctx| {
Box::pin(async move {
ModuleEvaluator::eval_rust::<SqliteModule>(ctx.clone(), "sqlite")
.await
.unwrap();

let module = ModuleEvaluator::eval_js(
ctx.clone(),
"test",
r#"
import { open } from "sqlite";

export async function test() {
const db = await open({ inMemory: true });
await db.exec("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, name TEXT);");
await db.exec("INSERT INTO test (name) VALUES ('test');");
return "ok";
}
"#,
)
.await
.catch(&ctx)
.unwrap();

let result = call_test::<String, _>(&ctx, &module, ()).await;
assert_eq!(result, "ok");
})
})
.await;
}

#[tokio::test]
async fn test_database_close() {
test_async_with(|ctx| {
Box::pin(async move {
ModuleEvaluator::eval_rust::<SqliteModule>(ctx.clone(), "sqlite")
.await
.unwrap();

let module = ModuleEvaluator::eval_js(
ctx.clone(),
"test",
r#"
import { open } from "sqlite";

export async function test() {
const db = await open({ inMemory: true });
await db.exec("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, name TEXT);");
await db.close();
return "ok";
}
"#,
)
.await
.catch(&ctx)
.unwrap();

let result = call_test::<String, _>(&ctx, &module, ()).await;
assert_eq!(result, "ok");
})
})
.await;
}
}
Empty file added src/modules/sqlite/error.rs
Empty file.
41 changes: 41 additions & 0 deletions src/modules/sqlite/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use rquickjs::{
function::{Async, Func},
module::{Declarations, Exports, ModuleDef},
Class, Ctx, Result,
};

use self::argument::Argument;
use self::database::Database;
use self::statement::Statement;
use self::value::Value;
use crate::utils::module::export_default;

mod argument;
mod database;
mod error;
mod open;
mod statement;
mod value;

pub struct SqliteModule;

impl ModuleDef for SqliteModule {
fn declare(declare: &Declarations) -> Result<()> {
declare.declare(stringify!(Database))?;
declare.declare("open")?;
declare.declare("default")?;

Ok(())
}

fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
export_default(ctx, exports, |default| {
Class::<Database>::define(default)?;

default.set("open", Func::from(Async(open::open)))?;

Ok(())
})?;
Ok(())
}
}
Loading
Loading