fix excepted and scalarref quoting for DEFAULTS in SQLite (and SQL Server)
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Generator / Role / DDL.pm
CommitLineData
1ea76bff 1package SQL::Translator::Generator::Role::DDL;
2
d22073f1 3# AUTHOR: Arthur Axel fREW Schmidt
4# Copyright: Same as Perl 5
5
1ea76bff 6use Moo::Role;
507693db 7use SQL::Translator::Utils qw(header_comment);
ff6dc6d4 8use Scalar::Util;
1ea76bff 9
1ea76bff 10requires '_build_type_map';
f699ffaa 11requires '_build_numeric_types';
12requires '_build_unquoted_defaults';
4b10273f 13requires '_build_sizeless_types';
39bfaa8b 14requires 'quote';
1ea76bff 15
16has type_map => (
28f1fad7 17 is => 'lazy',
1ea76bff 18);
19
f699ffaa 20has numeric_types => (
28f1fad7 21 is => 'lazy',
f699ffaa 22);
23
4b10273f 24has sizeless_types => (
25 is => 'lazy',
26);
27
f699ffaa 28has unquoted_defaults => (
28f1fad7 29 is => 'lazy',
f699ffaa 30);
31
f9356e0d 32has add_comments => (
33 is => 'ro',
34);
35
36has add_drop_table => (
37 is => 'ro',
38);
39
1ea76bff 40# would also be handy to have a required size set if there is such a thing
41
38d0ddf0 42sub field_name { $_[0]->quote($_[1]->name) }
1ea76bff 43
f699ffaa 44sub field_comments {
45 ( $_[1]->comments ? ('-- ' . $_[1]->comments . "\n ") : () )
46}
47
f511a415 48sub table_comments {
49 my ($self, $table) = @_;
50 if ($self->add_comments) {
51 return (
9a6c1bf9 52 "",
53 "--",
54 "-- Table: " . $self->quote($table->name) . "",
55 "--",
56 map "-- $_", $table->comments
f511a415 57 )
58 } else {
59 return ()
60 }
61}
62
f699ffaa 63sub field_nullable { ($_[1]->is_nullable ? $_[0]->nullable : 'NOT NULL' ) }
1ea76bff 64
65sub field_default {
ff6dc6d4 66 my ($self, $field, $exceptions) = @_;
67
68 my $default = $field->default_value;
69 return () if !defined $default;
70
71 $default = \"$default"
72 if $exceptions and !ref $default and $exceptions->{$default};
73 if (ref $default) {
74 $default = $$default;
75 } elsif (!($self->numeric_types->{lc($field->data_type)} && Scalar::Util::looks_like_number ($default))) {
76 $default = "'$default'";
77 }
78 return ( "DEFAULT $default" )
1ea76bff 79}
80
81sub field_type {
82 my ($self, $field) = @_;
83
84 my $field_type = $field->data_type;
85 ($self->type_map->{$field_type} || $field_type).$self->field_type_size($field)
86}
87
4b10273f 88sub field_type_size {
89 my ($self, $field) = @_;
90
91 ($field->size && !$self->sizeless_types->{$field->data_type}
92 ? '(' . $field->size . ')'
93 : ''
94 )
95}
96
2ce8cf9b 97sub fields {
98 my ($self, $table) = @_;
99 ( map $self->field($_), $table->get_fields )
100}
101
3f9e80bf 102sub indices {
103 my ($self, $table) = @_;
104 (map $self->index($_), $table->get_indices)
105}
106
f699ffaa 107sub nullable { 'NULL' }
108
507693db 109sub header_comments { header_comment() . "\n" if $_[0]->add_comments }
110
1ea76bff 1111;