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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/*! transfer table through databases using rust to call ubuntu shell command
 * export table from postgresql (remote server) to local file
 * import table into postgresql (remote server) from local file
 * export table from greenplum (remote server under docker) to local file
 * import table into greenplum (remote server under docker) from local file
 */
// use url_encode
use crate::file_status::FileStatus;
/** struct with database information */
pub struct DBinfo {
    host: String,
    port: String,
    database: String,
    username: String,
    password: String,
}
impl DBinfo{
    /** initialization */
    #[allow(dead_code)]
    pub fn init(host: String,
                port: String,
                database: String,
                username: String,
                password: String,
    ) -> Result<Self, &'static str> {
        Ok(
            DBinfo {
                host: host,
                port: port,
                database: database,
                username: username,
                password: password,
            }
        )
    }
    /** check local file: delete if exist */
    #[allow(dead_code)]
    pub fn local_clean(&mut self, pathstr: &str) -> Result<(), &'static str>{
        let path=std::path::PathBuf::from(pathstr);
        let md = match std::fs::metadata(&path){
            Ok(res) => res,
            Err(err) => {
                debug!("temporary file {} does not exist: {}", pathstr, err);
                return Ok(())
            }
        };
        if md.is_file(){
            match FileStatus::delete_file(pathstr){
                Ok(_) => return Ok(()),
                Err(err) => {
                    error!("delete {} fail: {}!", pathstr, err);
                    return Err("log file is not one file!");
                }
            };
        }
        Ok(())
    }
    /** export table from database to local file
     *  Greenplum on remote server in docker
     * Postgresql in remote server
     */
    #[allow(dead_code)]
    pub fn export(&mut self,
                  skm: &str,
                  tbl: &str,
                  pathstr: &str,
    ) -> Result<(), &'static str>{
        match self.local_clean(pathstr){
            Ok(_) => (),
            Err(err) => {
                error!("Failed to clean {}: {}", pathstr, err);
                return Err("Export failed!");
            }
        };
        info!("Start exporting {}.{} to {}...", skm, tbl, pathstr);
        // let pw_phase=format!("PGPASSWORD={}", self.password);
        // let qry=r##;
        let qry=format!("\\copy {}.{} to '{}' delimiter ',' csv header;", skm, tbl, pathstr);
        // info!("DEBUG: qry is {}: {}", &self.password, qry);
        let output = std::process::Command::new("psql")
                         .env("PGPASSWORD", &self.password)
                         .arg("-h")
                         .arg(&self.host)
                         .arg("-p")
                         .arg(&self.port)
                         .arg("-d")
                         .arg(&self.database)
                         .arg("-U")
                         .arg(&self.username)
                         .arg("-c")
                         .arg(&qry)
                         .output()
                         .expect("failed to execute process");
        // info!("DEBUG stdout:\n{}", String::from_utf8_lossy(&output.stdout));
        if String::from_utf8_lossy(&output.stderr).len() > 0 {
            error!("Failed export: {}", String::from_utf8_lossy(&output.stderr));
            return Err("export failed.");
        }
        info!("Finish exporting {}.{} to {}.", skm, tbl, pathstr);
        Ok(())
    }
    /** import table from local file
     *  Greenplum on remote server in docker
     * Postgresql in remote server
     */
    #[allow(dead_code)]
    pub fn import(&mut self,
                  skm: &str,
                  tbl: &str,
                  pathstr: &str,
    ) -> Result<(), &'static str>{
        let path=std::path::PathBuf::from(pathstr);
        match std::fs::metadata(&path){
            Ok(res) => res,
            Err(err) => {
                error!("temporary file {} does not exist: {}", pathstr, err);
                return Err("Local data file DOES NOT exist!!!")
            }
        };
        info!("Start importing {}.{} from {}...", skm, tbl, pathstr);
        // let pw_phase=format!("PGPASSWORD={}", self.password);
        // let qry=r##;
        let qry=format!("\\copy {}.{} from '{}' delimiter ',' csv header;", skm, tbl, pathstr);
        // info!("DEBUG: qry is {}: {}", &self.password, qry);
        let output = std::process::Command::new("psql")
                         .env("PGPASSWORD", &self.password)
                         .arg("-h")
                         .arg(&self.host)
                         .arg("-p")
                         .arg(&self.port)
                         .arg("-d")
                         .arg(&self.database)
                         .arg("-U")
                         .arg(&self.username)
                         .arg("-c")
                         .arg(&qry)
                         .output()
                         .expect("failed to execute process");
        // info!("DEBUG stdout:\n{}", String::from_utf8_lossy(&output.stdout));
        if String::from_utf8_lossy(&output.stderr).len() > 0 {
            error!("Failed export: {}", String::from_utf8_lossy(&output.stderr));
            return Err("export failed.");
        }
        info!("Finish importing {}.{} from {}.", skm, tbl, pathstr);
        Ok(())
    }
    /** check table exsitence using psql
     * Greenplum on remote server in docker
     * Postgresql in remote server
     */
    #[allow(dead_code)]
    pub fn psql_chk_tbl_exist(&mut self,
                  skm: &str,
                  tbl: &str,
    ) -> Result<bool, &'static str>{
        let qry=format!("SELECT count(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='{}' AND TABLE_NAME='{}'",
            skm, tbl,
        );
        // info!("DEBUG: qry is {}: {}", &self.password, qry);
        let output = std::process::Command::new("psql")
                         .env("PGPASSWORD", &self.password)
                         .arg("-h")
                         .arg(&self.host)
                         .arg("-p")
                         .arg(&self.port)
                         .arg("-d")
                         .arg(&self.database)
                         .arg("-U")
                         .arg(&self.username)
                         .arg("-c")
                         .arg(&qry)
                         .output()
                         .expect("failed to execute process");
        // info!("DEBUG stdout:\n{}", String::from_utf8_lossy(&output.stdout));
        if String::from_utf8_lossy(&output.stderr).len() > 0 {
            error!("Failed export: {}", String::from_utf8_lossy(&output.stderr));
            return Err("export failed.");
        }
        let out=String::from_utf8_lossy(&output.stdout);
        let lines = out.lines();
        let vec: Vec<&str> = lines.collect();
        let res = vec[2].trim();
        // info!("Result: '{}'", res);
        if res == "0" {return Ok(false)}
        Ok(true)
    }
    /** create table ddl using psql
     * Greenplum on remote server in docker
     * Postgresql in remote server
     */
    #[allow(dead_code)]
    pub fn psql_tbl_ddl_gen(&mut self,
                  port: &str,
                  skm: &str,
                  tbl: &str,
                  dllfile: &str,
    ) -> Result<(), &'static str>{
        let cmd=format!("pg_dump -p {} --schema-only -t {}.{} -x dbhuge | grep -v '^SET' > {}", port, skm, tbl, dllfile);
        let output = std::process::Command::new("ssh")
                         .arg("-i")
                         .arg("/home/user/.ssh/ubuntu_sinnud.pem")
                         .arg("sinnud@192.168.1.213")
                         .arg(&cmd)
                         .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(())
    }
    /** scp table ddl from remote to local
     */
    #[allow(dead_code)]
    pub fn tbl_ddl_scp(&mut self,
                  ddlfile: &str,
    ) -> Result<(), &'static str>{
        //scp -i .ssh/ubuntu_user.pem user@192.168.1.213:/tmp/data243.sql /tmp
        let remote_ddl_file=format!("sinnud@192.168.1.213:{}", ddlfile);
        let output = std::process::Command::new("scp")
                         .arg("-i")
                         .arg("/home/user/.ssh/ubuntu_sinnud.pem")
                         .arg(&remote_ddl_file)
                         .arg(ddlfile)
                         .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.");
        }
        Ok(())
    }
    /** create table using local ddl
     */
    #[allow(dead_code)]
    pub fn create_tbl_use_ddl(&mut self,
                  ddlfile: &str,
    ) -> Result<(), &'static str> {
        let output = std::process::Command::new("psql")
                         .env("PGPASSWORD", &self.password)
                         .arg("-h")
                         .arg(&self.host)
                         .arg("-p")
                         .arg(&self.port)
                         .arg("-d")
                         .arg(&self.database)
                         .arg("-U")
                         .arg(&self.username)
                         .arg("-f")
                         .arg(ddlfile)
                         .output()
                         .expect("failed to execute process");
        // info!("DEBUG stdout:\n{}", String::from_utf8_lossy(&output.stdout));
        if String::from_utf8_lossy(&output.stderr).len() > 0 {
            error!("Failed create table using ddl: {}", String::from_utf8_lossy(&output.stderr));
            // return Err("create table failed.");
            return Ok(()) // allow DISTRIBUTED BY error.
        }
        Ok(())
    }
    /** truncate table using psql
     * Greenplum on remote server in docker
     * Postgresql in remote server
     */
    #[allow(dead_code)]
    pub fn psql_truncate_tbl(&mut self,
                  skm: &str,
                  tbl: &str,
    ) -> Result<(), &'static str>{
        let qry=format!("truncate TABLE {}.{}",
            skm, tbl,
        );
        let output = std::process::Command::new("psql")
                         .env("PGPASSWORD", &self.password)
                         .arg("-h")
                         .arg(&self.host)
                         .arg("-p")
                         .arg(&self.port)
                         .arg("-d")
                         .arg(&self.database)
                         .arg("-U")
                         .arg(&self.username)
                         .arg("-c")
                         .arg(&qry)
                         .output()
                         .expect("failed to execute process");
        // info!("DEBUG stdout:\n{}", String::from_utf8_lossy(&output.stdout));
        if String::from_utf8_lossy(&output.stderr).len() > 0 {
            error!("Failed truncate table using psql: {}", String::from_utf8_lossy(&output.stderr));
            return Err("truncate table failed.");
        }
        Ok(())
    }
    /** table ddl clean from both remote and local
     */
    #[allow(dead_code)]
    pub fn tbl_ddl_clean(&mut self,
                  ddlfile: &str,
    ) -> Result<(), &'static str>{
        let path=std::path::PathBuf::from(ddlfile);
        let md = match std::fs::metadata(&path){
            Ok(res) => res,
            Err(err) => {
                info!("temporary file {} does not exist: {}", ddlfile, err);
                return Ok(())
            }
        };
        if md.is_file(){
            match FileStatus::delete_file(ddlfile){
                Ok(_) => (),
                Err(err) => {
                    error!("delete {} fail: {}!", ddlfile, err);
                    return Err("failed to delete local ddl 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("-f")
                         .arg(ddlfile)
                         .output()
                         .expect("failed to execute process");
        if String::from_utf8_lossy(&output.stderr).len() > 0 {
            error!("Failed delete remote ddl file: {}", String::from_utf8_lossy(&output.stderr));
            return Err("delete remove ddl file failed.");
        }
        info!("DEBUG stdout:\n{}", String::from_utf8_lossy(&output.stdout));
        Ok(())
    }
}