/
person.rs
76 lines (69 loc) · 2.21 KB
/
person.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use sqlx::{ FromRow, SqlitePool };
use serde::{ Serialize };
#[path = "../util/mod.rs"]
mod util;
#[derive(Serialize, Clone, FromRow, Debug)]
pub struct Person {
id: i64,
name: String,
}
#[tauri::command]
pub async fn person_insert(name: &str) -> Result<i64, String> {
let db_url = util::db::get_database();
let db = SqlitePool::connect(&db_url).await.unwrap();
let query_result = sqlx
::query("INSERT INTO person (name) VALUES (?)")
.bind(name)
.execute(&db).await;
if query_result.is_err() {
db.close().await;
return Err(format!("{:?}", query_result.err()));
}
let id = query_result.unwrap().last_insert_rowid();
db.close().await;
Ok(id)
}
#[tauri::command]
pub async fn person_update(id: i64, name: &str) -> Result<i64, String> {
let db_url = util::db::get_database();
let db = SqlitePool::connect(&db_url).await.unwrap();
let query_result = sqlx
::query("UPDATE person SET name=? WHERE id=?")
.bind(name)
.bind(id)
.execute(&db).await;
if query_result.is_err() {
db.close().await;
return Err(format!("{:?}", query_result.err()));
}
db.close().await;
Ok(id)
}
#[tauri::command]
pub async fn person_delete(id: i64) -> Result<i64, String> {
let db_url = util::db::get_database();
let db = SqlitePool::connect(&db_url).await.unwrap();
let query_result = sqlx::query("DELETE FROM person WHERE id=?").bind(id).execute(&db).await;
if query_result.is_err() {
db.close().await;
return Err(format!("{:?}", query_result.err()));
}
db.close().await;
Ok(id)
}
#[tauri::command]
pub async fn person_select() -> Result<String, String> {
let db_url = util::db::get_database();
let db = SqlitePool::connect(&db_url).await.unwrap();
let query_result = sqlx
::query_as::<_, Person>("SELECT id, name FROM person ORDER BY id DESC")
.fetch_all(&db).await;
if query_result.is_err() {
db.close().await;
return Err(format!("{:?}", query_result.err()));
}
let results = query_result.unwrap();
let encoded_message = serde_json::to_string(&results).unwrap();
db.close().await;
Ok(format!("{:?}", encoded_message))
}