add a ref to the translator object that created the producer and keep the schema...
[dbsrgits/SQL-Translator-2.0-ish.git] / lib / SQL / Translator / Producer.pm
1 use MooseX::Declare;
2 class SQL::Translator::Producer {
3     use SQL::Translator::Constants qw(:sqlt_types);
4     use MooseX::Types::Moose qw(Bool HashRef Str);
5     use SQL::Translator::Types qw(Column Table Translator);
6     
7     has 'no_comments' => (
8         isa => Bool,
9         is => 'rw',
10         lazy => 1, 
11         default => 0
12     );
13     
14     has 'drop_table' => (
15         isa => Bool,
16         is => 'rw',
17         lazy => 1,
18         default => 1
19     );
20
21     has 'data_type_mapping' => (
22         isa => HashRef,
23         is => 'ro',
24         lazy_build => 1
25     );
26
27     has 'translator' => (
28         isa => Translator,
29         is => 'ro',
30         weak_ref => 1,
31         required => 1,
32         handles => [ qw(schema) ],
33     );
34
35     method _build_data_type_mapping {
36         return { 
37             SQL_LONGVARCHAR() => 'text',
38             SQL_TIMESTAMP()   => 'timestamp',
39             SQL_TYPE_TIMESTAMP() => 'timestamp without time zone',
40             SQL_TYPE_TIMESTAMP_WITH_TIMEZONE() => 'timestamp',
41             SQL_INTEGER()     => 'integer',
42             SQL_CHAR()        => 'char',
43             SQL_VARCHAR()     => 'varchar',
44             SQL_BIGINT()      => 'bigint',
45             SQL_FLOAT()       => 'numeric',
46         };
47     }
48
49     method produce {
50         my $schema = $self->schema;
51
52         $self->_create_table($_) for values %{$schema->tables};
53     }
54     
55     method _create_table(Table $table) {
56         my $no_comments    = 0;
57         my $add_drop_table = 1;
58         my $sqlite_version = 0;
59     
60         my $create_table;
61         my (@column_defs, @index_defs, @constraint_defs);
62     
63         $create_table .= 'DROP TABLE '   . $table->name . ";\n" if $add_drop_table;
64         $create_table .= 'CREATE TABLE ' . $table->name . " (\n";
65     
66         push @column_defs, $self->_create_column($_) for values %{$table->columns};
67         $create_table .= join(",\n", map { '  ' . $_ } @column_defs ) . "\n)";
68         print $create_table . "\n";
69     }
70     
71     method _create_column(Column $column) {
72         my $column_def;
73         $column_def  = $column->name . ' ' . $column->data_type;
74         $column_def .= '(' . $column->size . ')' if $column->size;
75         $column_def .= ' NOT NULL' unless $column->is_nullable;
76         $column_def;
77     }
78 }