lazify things
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Generator / Role / DDL.pm
1 package SQL::Translator::Generator::Role::DDL;
2
3 use Moo::Role;
4 use SQL::Translator::Utils qw(header_comment);
5
6 requires '_build_type_map';
7 requires '_build_numeric_types';
8 requires '_build_unquoted_defaults';
9 requires 'field_type_size';
10 requires 'quote';
11
12 has type_map => (
13    is => 'lazy',
14 );
15
16 has numeric_types => (
17    is => 'lazy',
18 );
19
20 has unquoted_defaults => (
21    is => 'lazy',
22 );
23
24 has add_comments => (
25    is => 'ro',
26 );
27
28 has add_drop_table => (
29    is => 'ro',
30 );
31
32 # would also be handy to have a required size set if there is such a thing
33
34 sub field_name { $_[0]->quote($_[1]->name) }
35
36 sub field_comments {
37    ( $_[1]->comments ? ('-- ' . $_[1]->comments . "\n ") : () )
38 }
39
40 sub table_comments {
41    my ($self, $table) = @_;
42    if ($self->add_comments) {
43       return (
44          "",
45          "--",
46          "-- Table: " . $self->quote($table->name) . "",
47          "--",
48          map "-- $_", $table->comments
49       )
50    } else {
51       return ()
52    }
53 }
54
55 sub field_nullable { ($_[1]->is_nullable ? $_[0]->nullable : 'NOT NULL' ) }
56
57 sub field_default {
58   return () if !defined $_[1]->default_value;
59
60   my $val = $_[1]->default_value;
61   $val = "'$val'" unless $_[0]->numeric_types->{$_[1]->data_type};
62   return ( "DEFAULT $val" )
63 }
64
65 sub field_type {
66    my ($self, $field) = @_;
67
68    my $field_type = $field->data_type;
69    ($self->type_map->{$field_type} || $field_type).$self->field_type_size($field)
70 }
71
72 sub fields {
73   my ($self, $table) = @_;
74   ( map $self->field($_), $table->get_fields )
75 }
76
77 sub indices {
78   my ($self, $table) = @_;
79   (map $self->index($_), $table->get_indices)
80 }
81
82 sub nullable { 'NULL' }
83
84 sub header_comments { header_comment() . "\n" if $_[0]->add_comments }
85
86 1;