38 lines
1.1 KiB
Rust
Raw Normal View History

2019-08-15 15:02:52 +03:00
use fluence::sdk::*;
2019-08-18 14:10:28 +03:00
pub mod database;
2019-08-15 15:02:52 +03:00
pub mod errors;
2019-08-17 00:58:17 +03:00
2019-08-15 15:02:52 +03:00
fn init() {
logger::WasmLogger::init_with_level(log::Level::Info).unwrap();
}
2019-08-17 00:58:17 +03:00
#[invocation_handler(init_fn = init, side_modules = sqlite)]
2019-08-15 15:02:52 +03:00
fn run(nickname: String) -> String {
// Create table for messages storage
2019-08-18 14:10:28 +03:00
database::query("CREATE TABLE messages(message text, username text)")
2019-08-16 18:33:36 +03:00
.expect("error on CREATE TABLE");
2019-08-15 15:02:52 +03:00
2019-08-15 19:10:13 +03:00
// Insert message 'Hello, username!' using `nickname` as author's username
2019-08-18 14:10:28 +03:00
database::query(
2019-08-17 00:58:17 +03:00
format!(
r#"INSERT INTO messages VALUES("{}","{}")"#,
"Hello, username!", nickname
)
.as_str(),
)
2019-08-16 18:33:36 +03:00
.expect("error on INSERT INTO");
2019-08-15 15:02:52 +03:00
// Get all messages
2019-08-18 14:10:28 +03:00
let messages = database::query("SELECT * FROM messages").expect("error on SELECT *");
2019-08-16 18:33:36 +03:00
log::info!("messages: {:?}", messages);
2019-08-15 15:02:52 +03:00
// Get all messages as JSON via SQLite's JSON extension
2019-08-18 14:10:28 +03:00
database::query(
2019-08-15 15:02:52 +03:00
"SELECT json_group_array(
2019-08-16 19:47:38 +03:00
json_object('message', message, 'username', username)
2019-08-17 00:58:17 +03:00
) AS json_result FROM (SELECT * FROM messages)",
2019-08-15 15:02:52 +03:00
)
2019-08-16 18:33:36 +03:00
.expect("error on SELECT as json")
2019-08-15 15:02:52 +03:00
}