Initial revision
[freeside.git] / bin / dbdef-create
1 #!/usr/bin/perl -Tw
2 #
3 # create dbdef file for existing mySQL database (needs SHOW|DESCRIBE command
4 # not in Pg) based on fs-setup
5 #
6 # ivan@sisd.com 98-jun-2
7
8 use strict;
9 use DBI;
10 use FS::dbdef;
11 use FS::UID qw(adminsuidsetup datasrc);
12
13 #needs to match FS::Record
14 my($dbdef_file) = "/var/spool/freeside/dbdef.". datasrc;
15
16 my($dbh)=adminsuidsetup;
17
18 my($tables_sth)=$dbh->prepare("SHOW TABLES");
19 my($tables_rv)=$tables_sth->execute;
20
21 my(@tables);
22 foreach ( @{$tables_sth->fetchall_arrayref} ) {
23   my($table)=${$_}[0]; 
24   #print "TABLE\t$table\n";
25
26   my($index_sth)=$dbh->prepare("SHOW INDEX FROM $table");
27   my($primary_key)='';
28   my(%index,%unique);
29   for ( 1 .. $index_sth->execute ) {
30     my($row)=$index_sth->fetchrow_hashref;
31     if ( ${$row}{'Key_name'} eq "PRIMARY" ) {
32       $primary_key=${$row}{'Column_name'};
33       next;
34     }
35     if ( ${$row}{'Non_unique'} ) { #index
36       push @{$index{${$row}{'Key_name'}}}, ${$row}{'Column_name'};
37     } else { #unique
38       push @{$unique{${$row}{'Key_name'}}}, ${$row}{'Column_name'};
39     }
40   }
41
42   my(@index)=values %index;
43   my(@unique)=values %unique;
44   #print "\tPRIMARY KEY $primary_key\n";
45   foreach (@index) {
46     #print "\tINDEX\t", join(', ', @{$_}), "\n";
47   }
48   foreach (@unique) {
49     #print "\tUNIQUE\t", join(', ', @{$_}), "\n";
50   }
51
52   my($columns_sth)=$dbh->prepare("SHOW COLUMNS FROM $table");
53   my(@columns);
54   for ( 1 .. $columns_sth->execute ) {
55     my($row)=$columns_sth->fetchrow_hashref;
56     #print "\t", ${$row}{'Field'}, "\n";
57     ${$row}{'Type'} =~ /^(\w+)\(?([\d\,]+)?\)?( unsigned)?$/
58       or die "Illegal type ${$row}{'Type'}\n";
59     my($type,$length)=($1,$2);
60     my($null)=${$row}{'Null'};
61     $null =~ s/YES/NULL/;
62     push @columns, new FS::dbdef_column (
63       ${$row}{'Field'},
64       $type,
65       $null,
66       $length,
67     );
68   }
69
70   #print "\n";
71   push @tables, new FS::dbdef_table (
72     $table,
73     $primary_key,
74     new FS::dbdef_unique (\@unique),
75     new FS::dbdef_index (\@index),
76     @columns,
77   );
78
79 }
80
81 my($dbdef) = new FS::dbdef ( @tables );
82
83 #important
84 $dbdef->save($dbdef_file);
85