Problema con procedimiento
Publicado por José Vicente (113 intervenciones) el 15/08/2023 08:12:07
Hola, tengo un procedimiento en el que creo una Bd Postgres y luego intento restaurar en ella el backup de seguridad que tengo hecho con pg_dump. No me hace el backup, si crea la bd pero a la hora de hacer el backup me dice que el archivo no es correcto. He ejecutado paso a paso y el nombre del archivo y su contenido están bien. ¿Podéis ayudarme? Gracias.
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
Private connectionString As String = "Server=localhost;port=5432;UserId=postgres;Password=password;Database=postgres"
Public Sub CrearNuevaBaseDeDatos(nombreBD As String)
Try
' ESTABLECEMOS LA CONEXIÓN AL SERVIDOR
Using connection As New NpgsqlConnection(connectionString)
connection.Open()
' CREAMOS UN CRONÓMETRO Y LO INICIAMOS
Dim cronometro As New Stopwatch()
cronometro.Start()
' CREAMOS LA BD
Dim createDatabaseSql As String = $"CREATE DATABASE {nombreBD}"
Using createDatabaseCommand As New NpgsqlCommand(createDatabaseSql, connection)
createDatabaseCommand.ExecuteNonQuery()
Dim Mensaje As String = "¿QUIERES RESTAURAR LOS VALORES DE LA BD AL ÚLTIMO DÍA GUARDADO? "
Dim Caption As String = "RESTAURACIÓN VALORES."
Dim Botones As MessageBoxButtons = MessageBoxButtons.YesNo
Dim icono As MessageBoxIcon = MessageBoxIcon.Warning
Dim Result As DialogResult
Result = MessageBox.Show(Mensaje, Caption, Botones, icono)
If Result = System.Windows.Forms.DialogResult.Yes Then
' AGREGAMOS LA FECHA DEL ÚLTIMO BACKUP
Dim backupFolderPath As String = "D:\Documentos\Escaneados\Informe_medico_infarto_2019\Tension\Backup_BD"
Dim backupFiles As String() = Directory.GetFiles(backupFolderPath, "prueba1_*.sql")
Dim latestBackupFile As String = ""
If backupFiles.Length > 0 Then
' ORDENAMOS LOS ARCHIVOS POR FECHA DE CREACIÓN DESCENDENTE
Array.Sort(backupFiles, Function(f1, f2) New FileInfo(f2).CreationTime.CompareTo(New FileInfo(f1).CreationTime))
latestBackupFile = backupFiles(0)
Else
MessageBox.Show("NO SE ENCONTRARON ARCHIVOS DE BACKUP EN LA CARPETA.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
Dim fechaCreacion As Date = File.GetCreationTime(latestBackupFile)
Dim fechaFormateada As String = fechaCreacion.ToString("dd-MM-yyyy")
Dim fechaEspecifica As String = date_tb.Text
Dim dateFormat As String = "dd-MM-yyyy"
Dim parsedDate As Date
If Date.TryParseExact(fechaEspecifica, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, parsedDate) Then
Dim backupFileName As String = "prueba1_" & parsedDate.ToString("dd-MM-yyyy") & ".sql"
Dim backupFilePath As String = Path.Combine(backupFolderPath, backupFileName)
If File.Exists(backupFilePath) Then
Dim processInfo As New ProcessStartInfo("D:\BBDD\PostgreSQL\Instalacion\bin\pg_restore.exe") With {
.Arguments = $"-U postgres -h localhost -p 5432 -d prueba1 -v ""{backupFilePath}""",
.WindowStyle = ProcessWindowStyle.Normal,
.RedirectStandardOutput = True,
.RedirectStandardError = True, ' HABILITA LA REDIRECCIÓN DE SALIDA ESTÁNDAR Y DE ERROR.
.UseShellExecute = False}
Dim restoreProcess As Process = New Process With {
.StartInfo = processInfo
}
restoreProcess.Start()
Dim output As String = restoreProcess.StandardOutput.ReadToEnd()
Dim errorOutput As String = restoreProcess.StandardError.ReadToEnd()
restoreProcess.WaitForExit()
If restoreProcess.ExitCode = 0 Then
MessageBox.Show("RESTAURACIÓN EXITOSA.")
Else
MessageBox.Show($"FALLÓ LA RESTAURACIÓN. Detalles:{Environment.NewLine}{errorOutput}")
End If
Else
MessageBox.Show("NO SE ENCONTRÓ EL ARCHIVO DE BACKUP CORRESPONDIENTE A LA FECHA INDICADA.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Else
MessageBox.Show("FECHA INCORRECTA. POR FAVOR, INTRODUCE LA FECHA EN FORMATO dd-MM-yyyy.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End If
End Using
' DETENEMOS EL CRONÓMETRO
cronometro.Stop()
' CERRAMOS LA CONEXIÓN
connection.Close()
' OBTENEMOS EL TIEMPO TRANSCURRIDO EN SEGUNDOS CON PRECISIÓN HASTA LAS CENTÉSIMAS.
Dim tiempoTranscurrido As Double = cronometro.ElapsedMilliseconds / 1000.0
MessageBox.Show($"NUEVA BD CREADA. TIEMPO EMPLEADO: {tiempoTranscurrido:0.00} SEGUNDOS.")
End Using
Catch ex As Exception
MessageBox.Show("ERROR AL CREAR LA BD: " & ex.Message)
End Try
End Sub
Valora esta pregunta


0