Skip to content

Commit

Permalink
fix: Now we can transfer wasm's query to outside.
Browse files Browse the repository at this point in the history
  • Loading branch information
langyo committed Oct 23, 2023
1 parent cda01be commit 6b762f3
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 30 deletions.
2 changes: 1 addition & 1 deletion examples/proxy_wasmtime_example/module/src/entity/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
#[sea_orm(table_name = "posts")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: String,
pub id: i64,

pub title: String,
pub text: String,
Expand Down
33 changes: 32 additions & 1 deletion examples/proxy_wasmtime_example/module/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,39 @@ struct ProxyDb {}
impl ProxyDatabaseTrait for ProxyDb {
fn query(&self, statement: Statement) -> Result<Vec<ProxyRow>, DbErr> {
let sql = statement.sql.clone();
println!(
"{}",
serde_json::to_string(&RequestMsg::Query(sql)).unwrap()
);

Ok(vec![])
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
let ret: ResponseMsg = serde_json::from_str(&input).unwrap();
let ret = match ret {
ResponseMsg::Query(v) => v,
_ => unreachable!("Not a query result"),
};

let mut rows: Vec<ProxyRow> = vec![];
for row in ret {
let mut map: BTreeMap<String, sea_orm::Value> = BTreeMap::new();
for (k, v) in row.as_object().unwrap().iter() {
map.insert(k.to_owned(), {
if v.is_string() {
sea_orm::Value::String(Some(Box::new(v.as_str().unwrap().to_string())))
} else if v.is_number() {
sea_orm::Value::BigInt(Some(v.as_i64().unwrap()))
} else if v.is_boolean() {
sea_orm::Value::Bool(Some(v.as_bool().unwrap()))
} else {
unreachable!("Unknown json type")
}
});
}
rows.push(ProxyRow { values: map });
}

Ok(rows)
}

fn execute(&self, statement: Statement) -> Result<ProxyExecResult, DbErr> {
Expand Down
16 changes: 9 additions & 7 deletions examples/proxy_wasmtime_example/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use anyhow::Result;
use bytes::Bytes;

use sea_orm::{ConnectionTrait, Database, DatabaseBackend, ProxyExecResult, ProxyRow, Statement};
use sea_orm::{ConnectionTrait, Database, DatabaseBackend, ProxyExecResult, Statement};
use wasmtime::{Config, Engine};
use wit_component::ComponentEncoder;

Expand Down Expand Up @@ -60,9 +60,7 @@ async fn main() -> Result<()> {
runner.run().unwrap();
});

loop {
let msg = rx.recv()?;

while let Ok(msg) = rx.recv() {
match msg {
RequestMsg::Execute(sql) => {
let ret: ProxyExecResult = db
Expand All @@ -74,14 +72,16 @@ async fn main() -> Result<()> {
tx.send(ret)?;
}
RequestMsg::Query(sql) => {
let ret: Vec<ProxyRow> = db
use sea_orm::FromQueryResult;

let ret: Vec<serde_json::Value> = db
.query_all(Statement::from_string(DatabaseBackend::Sqlite, sql))
.await?
.iter()
.map(|r| r.into())
.map(|r| sea_orm::query::JsonValue::from_query_result(&r, "").unwrap())
.collect();
let ret: Vec<serde_json::Value> = ret.iter().map(|r| r.into()).collect();
println!("Query result: {:?}", ret);

let ret = ResponseMsg::Query(ret);
tx.send(ret)?;
}
Expand All @@ -90,4 +90,6 @@ async fn main() -> Result<()> {
}
}
}

Ok(())
}
27 changes: 6 additions & 21 deletions src/database/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use crate::{error::*, ExecResult, ExecResultHolder, QueryResult, QueryResultRow,
use sea_query::{Value, ValueType};
use std::{collections::BTreeMap, fmt::Debug};

#[cfg(feature = "proxy")]
/// Defines the [ProxyDatabaseTrait] to save the functions
pub trait ProxyDatabaseTrait: Send + Sync + std::fmt::Debug {
/// Execute a query in the [ProxyDatabase], and return the query results
Expand All @@ -28,7 +27,6 @@ pub trait ProxyDatabaseTrait: Send + Sync + std::fmt::Debug {
}

/// Defines the results obtained from a [ProxyDatabase]
#[cfg(feature = "proxy")]
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct ProxyExecResult {
/// The last inserted id on auto-increment
Expand All @@ -37,7 +35,6 @@ pub struct ProxyExecResult {
pub rows_affected: u64,
}

#[cfg(feature = "proxy")]
impl ProxyExecResult {
/// Create a new [ProxyExecResult] from the last inserted id and the number of rows affected
pub fn new(last_insert_id: u64, rows_affected: u64) -> Self {
Expand All @@ -48,14 +45,12 @@ impl ProxyExecResult {
}
}

#[cfg(feature = "proxy")]
impl Default for ExecResultHolder {
fn default() -> Self {
Self::Proxy(ProxyExecResult::default())
}
}

#[cfg(feature = "proxy")]
impl From<ProxyExecResult> for ExecResult {
fn from(result: ProxyExecResult) -> Self {
Self {
Expand All @@ -64,7 +59,6 @@ impl From<ProxyExecResult> for ExecResult {
}
}

#[cfg(feature = "proxy")]
impl From<ExecResult> for ProxyExecResult {
fn from(result: ExecResult) -> Self {
match result.result {
Expand Down Expand Up @@ -95,22 +89,19 @@ impl From<ExecResult> for ProxyExecResult {

/// Defines the structure of a Row for the [ProxyDatabase]
/// which is just a [BTreeMap]<[String], [Value]>
#[cfg(feature = "proxy")]
#[derive(Clone, Debug)]
pub struct ProxyRow {
/// The values of the single row
pub values: BTreeMap<String, Value>,
}

#[cfg(feature = "proxy")]
impl ProxyRow {
/// Create a new [ProxyRow] from a [BTreeMap]<[String], [Value]>
pub fn new(values: BTreeMap<String, Value>) -> Self {
Self { values }
}
}

#[cfg(feature = "proxy")]
impl Default for ProxyRow {
fn default() -> Self {
Self {
Expand All @@ -119,28 +110,24 @@ impl Default for ProxyRow {
}
}

#[cfg(feature = "proxy")]
impl From<BTreeMap<String, Value>> for ProxyRow {
fn from(values: BTreeMap<String, Value>) -> Self {
Self { values }
}
}

#[cfg(feature = "proxy")]
impl From<ProxyRow> for BTreeMap<String, Value> {
fn from(row: ProxyRow) -> Self {
row.values
}
}

#[cfg(feature = "proxy")]
impl From<ProxyRow> for Vec<(String, Value)> {
fn from(row: ProxyRow) -> Self {
row.values.into_iter().collect()
}
}

#[cfg(feature = "proxy")]
impl From<ProxyRow> for QueryResult {
fn from(row: ProxyRow) -> Self {
QueryResult {
Expand All @@ -149,7 +136,7 @@ impl From<ProxyRow> for QueryResult {
}
}

#[cfg(all(feature = "proxy", feature = "with-json"))]
#[cfg(feature = "with-json")]
impl Into<serde_json::Value> for ProxyRow {
fn into(self) -> serde_json::Value {
self.values
Expand All @@ -159,7 +146,6 @@ impl Into<serde_json::Value> for ProxyRow {
}
}

#[cfg(feature = "proxy")]
impl From<QueryResult> for ProxyRow {
fn from(result: QueryResult) -> Self {
match result.row {
Expand All @@ -176,7 +162,7 @@ impl From<QueryResult> for ProxyRow {
}
}

#[cfg(all(feature = "proxy", feature = "sqlx-mysql"))]
#[cfg(feature = "sqlx-mysql")]
impl From<sqlx::mysql::MySqlRow> for ProxyRow {
fn from(row: sqlx::mysql::MySqlRow) -> Self {
// https://docs.rs/sqlx-mysql/0.7.2/src/sqlx_mysql/protocol/text/column.rs.html
Expand Down Expand Up @@ -316,7 +302,7 @@ impl From<sqlx::mysql::MySqlRow> for ProxyRow {
}
}

#[cfg(all(feature = "proxy", feature = "sqlx-postgres"))]
#[cfg(feature = "sqlx-postgres")]
impl From<sqlx::postgres::PgRow> for ProxyRow {
fn from(row: sqlx::postgres::PgRow) -> Self {
// https://docs.rs/sqlx-postgres/0.7.2/src/sqlx_postgres/type_info.rs.html
Expand Down Expand Up @@ -780,7 +766,7 @@ impl From<sqlx::postgres::PgRow> for ProxyRow {
}
}

#[cfg(all(feature = "proxy", feature = "sqlx-sqlite"))]
#[cfg(feature = "sqlx-sqlite")]
impl From<sqlx::sqlite::SqliteRow> for ProxyRow {
fn from(row: sqlx::sqlite::SqliteRow) -> Self {
// https://docs.rs/sqlx-sqlite/0.7.2/src/sqlx_sqlite/type_info.rs.html
Expand Down Expand Up @@ -854,7 +840,7 @@ impl From<sqlx::sqlite::SqliteRow> for ProxyRow {
}
}

#[cfg(all(feature = "proxy", feature = "mock"))]
#[cfg(feature = "mock")]
impl From<crate::MockRow> for ProxyRow {
fn from(row: crate::MockRow) -> Self {
Self {
Expand Down Expand Up @@ -896,7 +882,6 @@ impl ProxyRow {
}

#[cfg(test)]
#[cfg(feature = "proxy")]
mod tests {
use crate::{
entity::*, tests_cfg::*, Database, DbBackend, DbErr, ProxyDatabaseTrait, ProxyExecResult,
Expand Down Expand Up @@ -924,7 +909,7 @@ mod tests {

#[smol_potat::test]
async fn create_proxy_conn() {
let db =
let _db =
Database::connect_proxy(DbBackend::MySql, Arc::new(Mutex::new(Box::new(ProxyDb {}))))
.await
.unwrap();
Expand Down

0 comments on commit 6b762f3

Please sign in to comment.