-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexecute.rs
More file actions
70 lines (60 loc) · 2.26 KB
/
execute.rs
File metadata and controls
70 lines (60 loc) · 2.26 KB
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
use sqlparser::ast::Statement;
use std::env;
use tokio_postgres::{Client, Error, NoTls};
pub struct PostgresExecutor {
client: Client,
}
impl PostgresExecutor {
pub async fn new() -> Result<PostgresExecutor, String> {
// TODO, simplify, use TLS
let hostname = env::var("PG_HOSTNAME").map_err(|_x| "PG_HOSTNAME not provided")?;
let username = env::var("PG_USERNAME").map_err(|_x| "PG_USERNAME not provided")?;
let port = env::var("PG_PORT").map_err(|_x| "PG_PORT not provided")?;
let database = env::var("PG_DATABASE").map_err(|_x| "PG_DATABASE not provided")?;
let password = env::var("PG_PASSWORD").map_err(|_x| "PG_PASSWORD not provided")?;
let url = format!(
"postgresql://{username}:{password}@{hostname}:{port}/{database}",
port = port,
username = username,
password = password,
hostname = hostname,
database = database,
);
let (client, connection) = tokio_postgres::connect(&url, NoTls)
.await
.map_err(|_x| "Failed to connect")?;
tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("Connection error: {}", e);
}
});
Ok(PostgresExecutor { client })
}
pub async fn execute(&mut self, name: &str, stmt: &Statement) -> Result<(), Error> {
let is_table = self
.client
.execute(
"SELECT count(*) FROM pg_tables where tablename='model'",
&[],
)
.await?;
let view_or_table = if is_table == 1 { "TABLE" } else { "VIEW" };
let with_local = if is_table == 1 { "" } else { "WITH LOCAL" };
let transaction = self.client.transaction().await?;
transaction
.batch_execute(
format!(
"DROP {view_or_table} IF EXISTS \"{name}\" CASCADE {with_local};
{stmt}",
view_or_table = view_or_table,
with_local = with_local,
name = name,
stmt = stmt
)
.as_str(),
)
.await?;
transaction.commit().await?;
Ok(())
}
}