summaryrefslogtreecommitdiff
path: root/bin/generate-table-module
blob: 76359623f690407575f7a62c39d6dcd939864963 (plain)
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
#!/usr/bin/perl

use FS::Schema qw( dbdef_dist );

my $table = shift;

###
# add a new FS/FS/table.pm
###

my %ut = ( #just guesses
  'int'     => 'number',
  'number'  => 'float',
  'varchar' => 'text',
  'text'    => 'text',
  'serial'  => 'number',
);

my $dbdef_table = dbdef_dist->table($table)
  or die "define table in Schema.pm first";
my $primary_key = $dbdef_table->primary_key;

open(SRC,"<eg/table_template.pm") or die $!;
-e "FS/FS/$table.pm" and die "FS/FS/$table.pm already exists!";
open(DEST,">FS/FS/$table.pm") or die $!;

while (my $line = <SRC>) {

  $line =~ s/table_name/$table/g;

  if ( $line =~ /^=item\s+field\s+-\s+description\s*$/ ) {

    foreach my $column ( $dbdef_table->columns ) {
      print DEST "=item $column\n\n";
      if ( $column eq $primary_key ) {
        print DEST "primary key\n\n";
      } else {
        print DEST "$column\n\n";
      }
    }
    next;

  } elsif ( $line=~ /^(\s*)\$self->ut_numbern\('primary_key'\)\s*/ ) {

    print DEST "$1\$self->ut_numbern('$primary_key')\n"
      if $primary_key;
    next;

  } elsif (
    $line =~ /^(\s*)\|\|\s+\$self->ut_number\('validate_other_fields'\)\s*/
  ) {

    foreach my $column ( grep { $_ ne $primary_key } $dbdef_table->columns ) {
      my $ut = $ut{$dbdef_table->column($column)->type};
      $ut .= 'n' if $dbdef_table->column($column)->null;
      print DEST "$1|| \$self->ut_$ut('$column')\n";
    }
    next;

  }

  print DEST $line;
}

close SRC;
close DEST;

###
# add to FS/FS/Mason.pm
###

my $magic = '# Sammath Naur';
system("perl -pi -e 's/$magic/use FS::$table;\n  $magic/' FS/FS/Mason.pm");

###
# add FS/t/table.t
###

open(TEST,">FS/t/$table.t") or die $!;
print TEST <<ENDTEST;
BEGIN { \$| = 1; print "1..1\\n" }
END {print "not ok 1\\n" unless \$loaded;}
use FS::$table;
\$loaded=1;
print "ok 1\\n";
ENDTEST
close TEST;

###
# add them to MANIFEST
###

system('cvs edit FS/MANIFEST');

open(MANIFEST,">>FS/MANIFEST") or die $!;
print MANIFEST "FS/$table.pm\n",
               "t/$table.t\n";
close MANIFEST;