567c005170910e76a8efc2160affa95a0dec970a
[dbsrgits/SQL-Translator-2.0-ish.git] / lib / SQL / Translator.pm
1 use MooseX::Declare;
2 class SQL::Translator {
3     use MooseX::Types::Moose qw(Str);
4     use TryCatch;
5     use SQL::Translator::Types qw(DBIHandle Parser Producer);
6     
7     has 'parser' => (
8         isa => Str,
9         is => 'ro',
10         init_arg => 'from',
11         required => 1,
12     );
13     
14     has 'producer' => (
15         isa => Str,
16         is => 'ro',
17         init_arg => 'to',
18         required => 1,
19     );
20     
21     has '_parser' => (
22         isa => Parser,
23         is => 'rw',
24         lazy_build => 1,
25         handles => [ qw(parse) ],
26     );
27     
28     has '_producer' => (
29         isa => Producer,
30         is => 'rw',
31         lazy_build => 1,
32         handles => [ qw(produce) ],
33     );
34     
35     has 'dbh' => (
36         isa => DBIHandle,
37         is => 'ro',
38         predicate => 'has_dbh',
39     );
40     
41     has 'filename' => (
42         isa => Str,
43         is => 'ro',
44         predicate => 'has_ddl',
45     );
46     
47     method _build__parser {
48         my $class = 'SQL::Translator::Parser';
49     
50         Class::MOP::load_class($class);
51     
52         my $parser;
53         if ($self->has_dbh) {
54             $parser = $class->new({ dbh => $self->dbh });
55         } elsif ($self->has_ddl) {
56             $parser = $class->new({ filename => $self->filename, type => $self->parser });
57         } else {
58             die "dbh or filename is required!";
59         }
60     
61         return $parser;
62     }
63     
64     method _build__producer {
65         my $class = 'SQL::Translator::Producer';
66         my $role = $class . '::' . $self->producer;
67     
68         Class::MOP::load_class($class);
69         try { Class::MOP::load_class($role) } catch ($e) { $role = $class . '::SQL::' . $self->producer; Class::MOP::load_class($role) }
70     
71         my $producer = $class->new({ schema => $self->parse });
72         $role->meta->apply($producer);
73     
74         return $producer;
75     }
76