Last active
November 19, 2022 21:26
-
-
Save barrybtw/39f69d2e7b89ea8d4af3031828feabb7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #![cfg_attr( | |
| all(not(debug_assertions), target_os = "windows"), | |
| windows_subsystem = "windows" | |
| )] | |
| use sqlx::sqlite::SqlitePoolOptions; | |
| // add variant for sqlx::Error | |
| #[derive(Debug, thiserror::Error)] | |
| enum Error { | |
| #[error(transparent)] | |
| Io(#[from] std::io::Error), | |
| Sqlx(#[from] sqlx::Error), | |
| } | |
| // implement fmt::Display for Error | |
| impl std::fmt::Display for Error { | |
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| match self { | |
| Error::Io(err) => write!(f, "I/O error: {}", err), | |
| Error::Sqlx(err) => write!(f, "Sqlx error: {}", err), | |
| } | |
| } | |
| } | |
| impl serde::Serialize for Error { | |
| fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> | |
| where | |
| S: serde::ser::Serializer, | |
| { | |
| serializer.serialize_str(self.to_string().as_ref()) | |
| } | |
| } | |
| #[tauri::command] | |
| fn greet(name: &str) -> String { | |
| format!("Hello, {}! You've been greeted from Rust!", name) | |
| } | |
| #[derive(sqlx::FromRow)] | |
| struct Food { | |
| id: i32, | |
| name: String, | |
| calories: f32, | |
| } | |
| #[tauri::command] | |
| async fn get_foods() -> Result<Vec<Food>, Error> { | |
| let con = SqlitePoolOptions::new() | |
| .max_connections(5) | |
| .connect("sqlite://./foods.db") | |
| .await?; | |
| let food = sqlx::query!("SELECT * FROM foods").fetch_all(&con).await?; | |
| Ok(food) | |
| } | |
| fn main() { | |
| tauri::Builder::default() | |
| .invoke_handler(tauri::generate_handler![greet]) | |
| .invoke_handler(tauri::generate_handler![get_foods]) | |
| .run(tauri::generate_context!()) | |
| .expect("error while running tauri application"); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment