Archivos: genFileDBO.pl

File genFileDBO.pl, 5.8 KB (added by era, 18 months ago)

Es un programa que escribí en PERL para poder administrar los fuentes de la base de datos PostgreSQL, es sencillo y se encarga de generar una estructura de directorios los archivos fuentes para poder hacer diff y facilitar el uso de SVN, si lo tengo que explicar sencillo, entonces es un parceador de dumps, espero a alguien le sea de utilidad como a mi.

Line 
1#!/usr/bin/perl
2
3use strict;
4use Getopt::Long qw(HelpMessage);
5use Pod::Usage;
6
7my $options = {
8        execute         => 1 ,
9        path            => '',
10        dumpf           => '',
11        userdb          => '',
12};
13
14my $dummy  =0;
15my $result = GetOptions(
16        "x|execute=s"           => \$$options{'execute'},
17        "p|path=s"              => \$$options{'path'},
18        "d|dumpf=s"             => \$$options{'dumpf'},
19        "u|userdb=s"            => \$$options{'userdb'},
20) or pod2usage(-verbose=>2);
21
22sub new {
23        my ($type) = $_[0];
24        my ($self) = {};
25        $self->{'options'}      = $options;
26        bless($self, $type);
27        return($self);
28}
29
30sub main (){
31        my ($self) = @_;
32
33        print "
34        MANUAL DE PARAMETROS OPCIONALES:
35        USAR \"-u\" para especificar un usuario con privilegios para pg_dump / pg_dumpall, toma por defecto que existe el usuario llamado root en PostgreSQL
36        USAR \"-d\" para especificar un archivo dump PostgreSQL
37        USAR \"-p\" para especificar un path, ej -p /tmp, toma por defecto el path \".\"
38        USAR \"-x 0\" para especificar la NO ejecucion del pg_dumpall, toma por defecto -x 1\n\n";
39
40        my $db;
41        my $file;
42        my $dirname="DB";
43        my $user;
44
45        if ($self->{'options'}->{'userdb'} ne ''){
46                $user=$self->{'options'}->{'userdb'};
47        } else {
48                $user='root';
49        }
50
51        if ($self->{'options'}->{'execute'} == 1){
52                if (($db=$self->listado($user))==-1){
53                        return -1;
54                }
55
56                print "De acuerdo a la configuracion puede solicitarse la clave del usuario $user en PostgreSQL\n";
57                my $command;
58                if ($db eq 'ALLDBS'){
59                        $dirname='pg_dumpall';
60                        $file="schema.sql";
61                        $command="pg_dumpall --schema-only --file=$file -U $user ";
62                } else {
63                        $file="schema_$db.sql";
64                        $dirname=$db;
65                        $command="pg_dump --schema-only --file=$file  -U $user $db";
66                }
67
68                print "\n\nEjecutando Comando: \n";
69                print "$command\n";
70                system $command;
71
72                if ($? == -1) {
73                        print "failed to execute: $!\n";
74                        return -1;
75                }
76        } elsif ($self->{'options'}->{'dumpf'} ne ''){
77                # verificar que exista el archivo y volcar el parametro a $file
78                print "Tomando el parametro \"".$self->{'options'}->{'dumpf'}."\" como archivo a trabajar\n";
79                $file=$self->{'options'}->{'dumpf'};
80        } else {
81                # error
82                print "Falta parametro para encontrar el Archivo dump de PostgreSQL \"-d\" \n";
83                return -1;
84        }
85
86
87        open(CURSOR,$file) or die "No se encuentra el archivo \"$file\" \nERROR: $!\n";
88
89        my $name='';
90        my $type='';
91        my $schema='';
92        my $owner='';
93        my $none='';
94        my $fOpen=0;
95        my $relPath;
96
97        if ($self->{'options'}->{'path'} ne ''){
98                $relPath=$self->{'options'}->{'path'}."/$dirname/";
99        } else {
100                $relPath="./$dirname/";
101        }
102        print "PATH de trabajo: ".$relPath."\n\n";
103
104        my @registros=<CURSOR>;
105
106        foreach my $reg (@registros){
107
108                if ($reg =~ m/^-- Name/){
109
110                        my ($a,$b,$c,$d) = split ('; ',$reg);
111                        ($none,$name) = split (': ',$a);
112                        ($none,$type) = split (': ',$b);
113                        ($none,$schema)= split (': ',$c);
114                        ($none,$owner)= split (': ',$d);
115
116                        if ($name && $type && $schema){
117                                if ($schema eq '-'){
118                                        $self->fs(\$fOpen,$relPath."GLOBAL/$type/",$name);
119                                } else {
120                                        $self->fs(\$fOpen,$relPath."$schema/$type/",$name);
121                                        print OBJ "SET search_path=$schema,pg_catalog;\n";
122                                }
123                                $fOpen=1;
124                        } else {
125                                # No se reconoce el objeto!!!
126                                # Sirve para debug, detectar y incluir estructuras
127                                print "No reconosco: ".$reg."\n";
128                                $name='';
129                                $type='';
130                                $schema='';
131                                $owner='';
132                                $fOpen=0;
133                        }
134                } elsif ($reg =~ m/^-- PostgreSQL database/){
135                        # inicio o reconeccion.
136                        $fOpen=0;
137                        next;
138                } elsif ($reg =~ m/^\\connect/){
139                        next;
140                } elsif ($reg =~ m/^--\n/){
141                        next;
142                } elsif ($reg =~ m/^SET search_path/){
143                        next;
144                } elsif ($reg =~ m/^-- Role memberships/){
145                        $self->fs(\$fOpen,$relPath,"Role memberships");
146                        $fOpen=1;
147                } elsif ($reg =~ m/^-- Roles/){
148                        $self->fs(\$fOpen,$relPath,"Roles");
149                        $fOpen=1;
150                } elsif ($reg =~ m/^-- Database creation/){
151                        $self->fs(\$fOpen,$relPath,"Database creation");
152                        $fOpen=1;
153                } elsif ($fOpen==1) {
154                        # escribo el archivo.
155                        print OBJ $reg; 
156                } else {
157                        # Sirve para debug, detectar y incluir estructuras, esto sale por Std Output   
158                        # print "Paso por alto a: ".$reg."\n";
159                }
160        }
161
162        if ($fOpen==1){
163                close (OBJ);
164        }
165        close (CURSOR);
166
167        if ($self->{'options'}->{'execute'} == 1){
168                print "Borrando el archivo $file\n";
169                system "rm $file";
170        }
171
172        return 0;
173}
174
175sub fs{
176        my ($self,$fOpen,$path,$name) = @_;
177
178        if ($$fOpen==1){
179                close (OBJ);
180                $$fOpen=0;
181        }
182        # Creo la estructura de directorio a mi gusto.
183        system "mkdir -p \"$path\"";
184
185        # creo archivo!!
186        open (OBJ,">",$path.$name.".sql");
187
188        return 0;
189}
190
191sub listado{
192        my ($self,$user) = @_;
193
194        my $command="psql -l -U $user";
195        print "\n\nEjecutando Comando: $command\n";
196        my @resultados = `$command`;
197
198        if (@resultados==0){
199                print "Error en la ejecucion: $command\n";
200                return -1;
201        }
202       
203        my $i=1;
204        my $list=0;
205        print "\n\n";
206        my @array;
207
208        foreach my $reg (@resultados){
209
210                if ($reg =~ m/\s*\(*\)/){
211                        $list=0;
212                }
213
214                if ($list==1){
215                        if ($i<10){
216                                if ($i==1){
217                                        print "00 -  *** TODAS LAS BASES ***\n";
218                                }
219                                print "0$i";
220                        } else {
221                                print $i;
222                        }
223                        print " - $reg";
224                        $i++;
225                        my ($none,$name) = split(/\s+/,$reg);
226                        push(@array,$name);
227                } else {
228                        print "     $reg";
229                }
230
231                if ($reg =~ m/\s*------/){ 
232                        # titulo
233                        $list=1;
234                }
235        }
236
237
238        print "Ingrese una Opcion: ";
239        my $opc=<STDIN>;
240        while ($opc !~ /\d/) {
241                print "Ingrese una Opcion: ";
242                $opc=<STDIN>;
243        }
244        chop($opc);
245
246        if ($opc<0 || $opc>=$i){
247                print "Opcion: $opc INVALIDA\n";
248                return -1;
249        }
250        print "Opcion: $opc, Cargando ";
251        my $db;
252        if ($opc==0){
253                print "TODAS LAS BASES\n";
254                $db='ALLDBS';
255        } elsif($opc>0) {
256                $db=$array[($opc-1)];
257                print "Base: ".$db."\n";
258        } else{
259                return -1;
260        }
261
262        return $db;
263}
264
265my $pp = new();
266if ($pp->main()==-1){
267        print "\nSALIO CON ERROR!\n";
268} else {
269        print "\nEJECUCION EXITOSA\n";
270}