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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
use mysql::prelude::Queryable;
#[allow(unused_imports)]
use chrono::offset::{Utc, Local};
use chrono::DateTime;
use std::time::SystemTime;
use std::io::Write;
use crate::sqltrait::url_encode;
use crate::sqltrait::SQL;
use crate::pem;
pub struct LibMySQL{
pub conn: mysql::PooledConn,
}
impl Default for LibMySQL {
#[allow(dead_code)]
fn default() -> Self {
let filename="/mnt/public/data/other/pem/config_ms_sinnud";
let pem = pem::db_pem(filename).unwrap();
let ip = &pem[0];
let database = &pem[2];
let username = &pem[3];
let password = &pem[4];
let pw_url=url_encode(password);
let constr=format!("mysql://{}:{}@{}/{}", username, pw_url, ip, database);
let pool = match mysql::Pool::new(&constr){
Ok(res) => res,
Err(err) => {
error!("in default() for LibMySQL: {:?}", err);
println!("Pool::new failed: {:?}", err);
println!("Failed to connect database using default() function!");
std::process::exit(1);
}
};
LibMySQL{
conn: match pool.get_conn(){
Ok(res) => res,
Err(err) =>{
error!("in default() for LibMyQL: {:?}", err);
println!("get_conn failed: {:?}", err);
println!("Failed to connect database using default() function!");
std::process::exit(1);
}
},
}
}
}
impl LibMySQL{
#[allow(dead_code)]
pub fn new(host: String, username: String, password: String, database: String) -> Result<Self, &'static str> {
let constr=format!("mysql://{}:{}@{}/{}", username, url_encode(&password), host, database);
let pool = match mysql::Pool::new(&constr){
Ok(res) => res,
Err(err) => {
error!("in new() for LibMySQL: {:?}", err);
return Err("Failed to connect database using new() function!");
}
};
Ok( LibMySQL{
conn: match pool.get_conn(){
Ok(res) => res,
Err(err) => {
error!("in LibMySQL::new(): {:?}", err);
info!("Failed to connect database using new({}:{}@{}/{}) function!",
username, &password, host, database
);
return Err("Failed to connect database using new() function!");
}
},
}
)
}
}
impl SQL for LibMySQL {
fn execute_queries_no_return(&mut self, qry: &str) -> Result<(), &'static str>{
match self.conn.query_drop(qry){
Ok(res) => res,
Err(err) => {
error!("in LibMySQL::execute(): {:?}", err);
return Err("Failed to run execute_query_no_return!");
}
};
Ok(())
}
fn check_table_exists(&mut self, skm: &str, tbl: &str) -> Result<bool, &'static str>{
let qry=format!("SELECT cast(count(*) as nchar) as cnt FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='{}' AND TABLE_NAME='{}'",
skm, tbl);
let rows = match self.execute_query_with_return(&qry){
Ok(res) => res,
Err(err) => {
error!("in LibMySQL::table_exist(): {:?}", err);
return Err("Failed to run LibMySQL::table_exist!");
}
};
for row in &rows {
if row.len() == 0 {return Ok(false)}
let i: i64 = row.split("\t").nth(0).unwrap().parse::<i64>().unwrap();
if i>0 {return Ok(true)}
}
Ok(false)
}
fn drop_table(&mut self, skm: &str, tbl: &str) -> Result<(), &'static str>{
let qry=format!("DROP TABLE {}.{}", skm, tbl);
info!("in LibMySQL::drop_table() query is\n{}", qry);
match self.execute_queries_no_return(&qry){
Ok(_) => Ok(()),
Err(err) => {
error!("in LibMySQL::drop_table: {:?}", err);
return Err("Failed to run LibMySQL::drop_table!");
}
}
}
fn truncate_table(&mut self, skm: &str, tbl: &str) -> Result<(), &'static str>{
let qry=format!("TRUNCATE TABLE {}.{}", skm, tbl);
debug!("in LibMySQL::truncate_table() query is\n{}", qry);
match self.execute_queries_no_return(&qry){
Ok(_) => Ok(()),
Err(err) => {
error!("in LibMySQL::truncate_table: {:?}", err);
return Err("Failed to run LibMySQL::truncate_table!");
}
}
}
fn create_table(&mut self, skm: &str, tbl: &str, tbl_str: &str) -> Result<(), &'static str>{
let mut qry=format!("CREATE TABLE {}.{} (", skm, tbl);
qry.push_str(tbl_str);
qry.push_str(")");
match self.execute_queries_no_return(&qry){
Ok(_) => Ok(()),
Err(err) => {
error!("in LibMySQL::create_table: {:?}", err);
return Err("Failed to run LibMySQL::create_table!");
}
}
}
fn import_data(&mut self, skm: &str, tbl: &str, datastring: String) -> Result<(), &'static str>{
info!("Store datastring to /tmp/random_file...");
let x = md5::compute(&datastring);
let s = format!("{:x}", x);
let s8 = &s[0..8];
let system_time = SystemTime::now();
let datetime: DateTime<Local> = system_time.into();
let post_ts=datetime.format("%Y%m%d_%H%M%S");
let tmp_file=format!("/tmp/{}_{}", s8, post_ts);
let mut ofile = std::fs::File::create(&tmp_file)
.expect("unable to create file");
ofile.write_all(datastring.as_bytes()).expect("unable to write");
info!("ftp to mysql workstation...");
let output = std::process::Command::new("scp")
.arg("-i")
.arg("/home/user/.ssh/ubuntu_sinnud.pem")
.arg(&tmp_file)
.arg("sinnud@192.168.1.213:/tmp")
.output()
.expect("failed to execute process");
if String::from_utf8_lossy(&output.stderr).len() > 0 {
error!("Failed scp: {}", String::from_utf8_lossy(&output.stderr));
return Err("scp failed.");
}
info!("change owner to mysql.mysql...");
let output = std::process::Command::new("ssh")
.arg("-i")
.arg("/home/user/.ssh/ubuntu_sinnud.pem")
.arg("sinnud@192.168.1.213")
.arg("sudo")
.arg("chown")
.arg("mysql.mysql")
.arg(&tmp_file)
.output()
.expect("failed to execute process");
if String::from_utf8_lossy(&output.stderr).len() > 0 {
error!("Failed ssh: {}", String::from_utf8_lossy(&output.stderr));
return Err("ssh failed.");
}
info!("load into MySQL table...");
let qry=format!("load data infile '{}' into table {}.{}", &tmp_file, skm, tbl);
match self.execute_queries_no_return(&qry){
Ok(_) => (),
Err(err) => {
error!("Failed to load data: {}", err);
return Err("load data infile failed");
}
};
info!("Delete local data file...");
match std::fs::remove_file(&tmp_file){
Ok(_) => (),
Err(err) => {
error!("Failed to delete local data file {}: {}", tmp_file, err);
return Err("Delete local data file failed!");
}
}
info!("Delete mysql data file...");
let output = std::process::Command::new("ssh")
.arg("-i")
.arg("/home/user/.ssh/ubuntu_sinnud.pem")
.arg("sinnud@192.168.1.213")
.arg("sudo")
.arg("rm")
.arg(&tmp_file)
.output()
.expect("failed to execute process");
if String::from_utf8_lossy(&output.stderr).len() > 0 {
error!("Failed ssh: {}", String::from_utf8_lossy(&output.stderr));
return Err("ssh failed.");
}
Ok(())
}
fn execute_query_with_return(&mut self, qry: &str) -> Result<Vec<String>, &'static str>{
let vr: Vec<mysql::Row> = match self.conn.query(qry){
Ok(res) => res,
Err(err) => {
error!("in MySQL::query(): {:?}", err);
return Err("Failed to run query!");
}
};
let mut vs: Vec<String> = Vec::with_capacity(vr.len());
for row in &vr {
let mut line = String::new();
let clms=row.len();
for i in 0..clms {
let cstr: String = row.get(i).unwrap();
line.push_str(&cstr);
if i+1 < clms {
line.push_str("\t");
}
}
vs.push(line);
}
Ok(vs)
}
}