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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use crate::auth::{Auth, Role};
use crate::Database;
use diesel::{query_dsl::RunQueryDsl, sql_query, sql_types::Text};
use diesel_migrations::{FileBasedMigrations, MigrationHarness};
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, QueryableByName)]
pub struct MyQueryResult {
#[diesel(sql_type=Text)]
pub json: String,
}
#[derive(Serialize, Deserialize)]
pub struct MySqlQuery {
pub query: String,
}
#[derive(Serialize, Deserialize)]
pub struct HealthCheckResponse {
pub message: String,
}
pub fn query_db(db: &Database, body: &MySqlQuery) -> Result<String, ()> {
let q = format!("SELECT json_agg(q) as json FROM ({}) q;", body.query);
let mut db = db.pool.get().unwrap();
let rows = sql_query(q.as_str()).get_result::<MyQueryResult>(&mut db);
if rows.is_err() {
return Err(());
}
let result = rows.unwrap().json;
Ok(result)
}
pub fn check_system_role(auth: &Auth) -> bool {
auth.has_permission("system".to_string())
}
pub fn add_system_role(db: &Database, auth: &Auth) -> bool {
let mut db = db.pool.clone().get().unwrap();
Role::assign(&mut db, auth.user_id, "system").unwrap()
}
pub fn is_connected(db: &Database) -> bool {
let mut db = db.pool.clone().get().unwrap();
let is_connected = sql_query("SELECT 1;").execute(&mut db);
is_connected.is_err()
}
pub fn needs_migration(db: &Database) -> bool {
let mut db = db.pool.clone().get().unwrap();
let source = FileBasedMigrations::find_migrations_directory().unwrap();
MigrationHarness::has_pending_migration(&mut db, source).unwrap()
}
pub fn migrate_db(db: &Database) -> bool {
let mut db = db.pool.clone().get().unwrap();
let source = FileBasedMigrations::find_migrations_directory().unwrap();
let has_pending_migrations =
MigrationHarness::has_pending_migration(&mut db, source.clone()).unwrap();
if !has_pending_migrations {
return true;
}
let op = MigrationHarness::run_pending_migrations(&mut db, source);
if op.is_err() {
println!("{:#?}", op.err());
return false;
}
true
}
pub fn health() -> () {
()
}