1+ using System ;
2+ using System . Diagnostics ;
3+ using postgres_database_restore_tool . ValueObject ;
4+
5+ namespace postgres_database_restore_tool . Helper
6+ {
7+ public static class CommandExecutor
8+ {
9+ public static void Execute ( string commandType , string user , string database )
10+ {
11+ var proc = new Process ( ) ;
12+ proc . StartInfo . FileName = "psql" ;
13+ proc . StartInfo . Arguments = $@ "-U { user } -c ""{ commandType } database """"{ database } """"";
14+ proc.StartInfo.RedirectStandardOutput = true;
15+ proc.StartInfo.RedirectStandardError = true;
16+ proc.StartInfo.UseShellExecute = false;
17+ proc.StartInfo.CreateNoWindow = true;
18+ proc.Start();
19+ var output = proc.StandardOutput.ReadToEnd();
20+ var error = proc.StandardError.ReadToEnd();
21+ proc.WaitForExit();
22+ if (proc.ExitCode != 0)
23+ {
24+ proc . Close ( ) ;
25+ throw new Exception ( "Error restoring database: " + error ) ;
26+ }
27+
28+ proc. Close ( ) ;
29+ }
30+
31+ public static void ExecuteRestore( UserConnectionVo connection )
32+ {
33+ const string pwdKey = "PGPASSWORD";
34+ Environment. SetEnvironmentVariable ( pwdKey , connection . Password ) ;
35+ switch ( connection . ActionTypeValue )
36+ {
37+ case "Drop_and_Restore":
38+ Execute( "drop" , connection . UserName , connection . DatabaseName ) ;
39+ Execute( "create" , connection . UserName , connection . DatabaseName ) ;
40+ break ;
41+ case "Create_and_Restore":
42+ Execute( "create" , connection . UserName , connection . DatabaseName ) ;
43+ break ;
44+ }
45+
46+ var proc = new Process( ) ;
47+ if ( connection . DatabaseBackupType == "pg_dump" )
48+ {
49+ proc. StartInfo . FileName = "psql" ;
50+ proc. StartInfo . Arguments = $@ "-U { connection . UserName } ""{ connection . DatabaseName } "" < ""{ connection . RestoreFileLocation } """;
51+ }
52+ else
53+ {
54+ proc . StartInfo . FileName = connection . DatabaseBackupType;
55+ proc . StartInfo . Arguments = $@ "-U { connection . UserName } -d ""{ connection . DatabaseName } "" ""{ connection . RestoreFileLocation } """;
56+ }
57+
58+ proc.StartInfo.RedirectStandardOutput = true;
59+ proc.StartInfo.RedirectStandardError = true;
60+ proc.StartInfo.UseShellExecute = false;
61+ proc.StartInfo.CreateNoWindow = true;
62+ proc.Start();
63+ var output = proc.StandardOutput.ReadToEnd();
64+ var error = proc.StandardError.ReadToEnd();
65+ proc.WaitForExit();
66+ if (proc.ExitCode != 0)
67+ {
68+ proc . Close ( ) ;
69+ throw new Exception ( "Error restoring database.Details: " + error ) ;
70+ }
71+
72+ proc. Close ( ) ;
73+ }
74+ }
75+ }
0 commit comments