8131ee26521f3e9a4344f7af5dafbc01a63bf64a
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / DBI / mysql.pm
1 package DBIx::Class::Schema::Loader::DBI::mysql;
2
3 use strict;
4 use warnings;
5 use base 'DBIx::Class::Schema::Loader::DBI';
6 use mro 'c3';
7 use Carp::Clan qw/^DBIx::Class/;
8 use List::Util 'first';
9 use List::MoreUtils 'any';
10 use Try::Tiny;
11 use namespace::clean;
12
13 our $VERSION = '0.07010';
14
15 =head1 NAME
16
17 DBIx::Class::Schema::Loader::DBI::mysql - DBIx::Class::Schema::Loader::DBI mysql Implementation.
18
19 =head1 DESCRIPTION
20
21 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
22
23 =cut
24
25 sub _setup {
26     my $self = shift;
27
28     $self->schema->storage->sql_maker->quote_char("`");
29     $self->schema->storage->sql_maker->name_sep(".");
30
31     $self->next::method(@_);
32
33     if (not defined $self->preserve_case) {
34         $self->preserve_case(0);
35     }
36
37     if ($self->db_schema && $self->db_schema->[0] eq '%') {
38         my @schemas = try {
39             map $_->[0], @{ $self->dbh->selectall_arrayref('SHOW DATABASES') };
40         }
41         catch {
42             croak "no SHOW DATABASES privileges: $_";
43         };
44
45         @schemas = grep {
46             my $schema = $_;
47             not any { $schema eq $_ } $self->_system_schemas
48         } @schemas;
49
50         $self->db_schema(\@schemas);
51     }
52 }
53
54 sub _system_schemas {
55     my $self = shift;
56
57     return ($self->next::method(@_), 'mysql');
58 }
59
60 sub _tables_list { 
61     my ($self, $opts) = @_;
62
63     return $self->next::method($opts, undef, undef);
64 }
65
66 sub _table_fk_info {
67     my ($self, $table) = @_;
68
69     my $table_def_ref = eval { $self->dbh->selectrow_arrayref("SHOW CREATE TABLE ".$table->sql_name) };
70     my $table_def = $table_def_ref->[1];
71
72     return [] if not $table_def;
73
74     my $qt  = qr/["`]/;
75     my $nqt = qr/[^"`]/;
76
77     my (@reldata) = ($table_def =~
78         /CONSTRAINT ${qt}${nqt}+${qt} FOREIGN KEY \($qt(.*)$qt\) REFERENCES (?:$qt($nqt+)$qt\.)?$qt($nqt+)$qt \($qt(.+)$qt\)/ig
79     );
80
81     my @rels;
82     while (scalar @reldata > 0) {
83         my ($cols, $f_schema, $f_table, $f_cols) = splice @reldata, 0, 4;
84
85         my @cols   = map { s/$qt//g; $self->_lc($_) }
86             split(/$qt?\s*$qt?,$qt?\s*$qt?/, $cols);
87
88         my @f_cols = map { s/$qt//g; $self->_lc($_) }
89             split(/$qt?\s*$qt?,$qt?\s*$qt?/, $f_cols);
90
91         my $remote_table = first {
92                lc($_->name) eq lc($f_table)
93             && ((not $f_schema) || lc($_->schema) eq lc($f_schema))
94         } $self->_tables_list;
95
96         push(@rels, {
97             local_columns => \@cols,
98             remote_columns => \@f_cols,
99             remote_table => $remote_table,
100         });
101     }
102
103     return \@rels;
104 }
105
106 # primary and unique info comes from the same sql statement,
107 #   so cache it here for both routines to use
108 sub _mysql_table_get_keys {
109     my ($self, $table) = @_;
110
111     if(!exists($self->{_cache}->{_mysql_keys}->{$table})) {
112         my %keydata;
113         my $sth = $self->dbh->prepare('SHOW INDEX FROM '.$table->sql_name);
114         $sth->execute;
115         while(my $row = $sth->fetchrow_hashref) {
116             next if $row->{Non_unique};
117             push(@{$keydata{$row->{Key_name}}},
118                 [ $row->{Seq_in_index}, $self->_lc($row->{Column_name}) ]
119             );
120         }
121         foreach my $keyname (keys %keydata) {
122             my @ordered_cols = map { $_->[1] } sort { $a->[0] <=> $b->[0] }
123                 @{$keydata{$keyname}};
124             $keydata{$keyname} = \@ordered_cols;
125         }
126         $self->{_cache}->{_mysql_keys}->{$table} = \%keydata;
127     }
128
129     return $self->{_cache}->{_mysql_keys}->{$table};
130 }
131
132 sub _table_pk_info {
133     my ( $self, $table ) = @_;
134
135     return $self->_mysql_table_get_keys($table)->{PRIMARY};
136 }
137
138 sub _table_uniq_info {
139     my ( $self, $table ) = @_;
140
141     my @uniqs;
142     my $keydata = $self->_mysql_table_get_keys($table);
143     foreach my $keyname (keys %$keydata) {
144         next if $keyname eq 'PRIMARY';
145         push(@uniqs, [ $keyname => $keydata->{$keyname} ]);
146     }
147
148     return \@uniqs;
149 }
150
151 sub _columns_info_for {
152     my $self = shift;
153     my ($table) = @_;
154
155     my $result = $self->next::method(@_);
156
157     while (my ($col, $info) = each %$result) {
158         if ($info->{data_type} eq 'int') {
159             $info->{data_type} = 'integer';
160         }
161         elsif ($info->{data_type} eq 'double') {
162             $info->{data_type} = 'double precision';
163         }
164         my $data_type = $info->{data_type};
165
166         delete $info->{size} if $data_type !~ /^(?: (?:var)?(?:char(?:acter)?|binary) | bit | year)\z/ix;
167
168         # information_schema is available in 5.0+
169         my ($precision, $scale, $column_type, $default) = eval { $self->dbh->selectrow_array(<<'EOF', {}, $table, $col) };
170 SELECT numeric_precision, numeric_scale, column_type, column_default
171 FROM information_schema.columns
172 WHERE table_name = ? AND column_name = ?
173 EOF
174         my $has_information_schema = not $@;
175
176         $column_type = '' if not defined $column_type;
177
178         if ($data_type eq 'bit' && (not exists $info->{size})) {
179             $info->{size} = $precision if defined $precision;
180         }
181         elsif ($data_type =~ /^(?:float|double precision|decimal)\z/i) {
182             if (defined $precision && defined $scale) {
183                 if ($precision == 10 && $scale == 0) {
184                     delete $info->{size};
185                 }
186                 else {
187                     $info->{size} = [$precision,$scale];
188                 }
189             }
190         }
191         elsif ($data_type eq 'year') {
192             if ($column_type =~ /\(2\)/) {
193                 $info->{size} = 2;
194             }
195             elsif ($column_type =~ /\(4\)/ || $info->{size} == 4) {
196                 delete $info->{size};
197             }
198         }
199         elsif ($data_type =~ /^(?:date(?:time)?|timestamp)\z/) {
200             if (not (defined $self->datetime_undef_if_invalid && $self->datetime_undef_if_invalid == 0)) {
201                 $info->{datetime_undef_if_invalid} = 1;
202             }
203         }
204         elsif ($data_type =~ /^(?:enum|set)\z/ && $has_information_schema
205                && $column_type =~ /^(?:enum|set)\(/) {
206
207             delete $info->{extra}{list};
208
209             while ($column_type =~ /'((?:[^']* (?:''|\\')* [^']*)* [^\\'])',?/xg) {
210                 my $el = $1;
211                 $el =~ s/''/'/g;
212                 push @{ $info->{extra}{list} }, $el;
213             }
214         }
215
216         # Sometimes apparently there's a bug where default_value gets set to ''
217         # for things that don't actually have or support that default (like ints.)
218         if (exists $info->{default_value} && $info->{default_value} eq '') {
219             if ($has_information_schema) {
220                 if (not defined $default) {
221                     delete $info->{default_value};
222                 }
223             }
224             else { # just check if it's a char/text type, otherwise remove
225                 delete $info->{default_value} unless $data_type =~ /char|text/i;
226             }
227         }
228     }
229
230     return $result;
231 }
232
233 sub _extra_column_info {
234     no warnings 'uninitialized';
235     my ($self, $table, $col, $info, $dbi_info) = @_;
236     my %extra_info;
237
238     if ($dbi_info->{mysql_is_auto_increment}) {
239         $extra_info{is_auto_increment} = 1
240     }
241     if ($dbi_info->{mysql_type_name} =~ /\bunsigned\b/i) {
242         $extra_info{extra}{unsigned} = 1;
243     }
244     if ($dbi_info->{mysql_values}) {
245         $extra_info{extra}{list} = $dbi_info->{mysql_values};
246     }
247     if (   lc($dbi_info->{COLUMN_DEF})      eq 'current_timestamp'
248         && lc($dbi_info->{mysql_type_name}) eq 'timestamp') {
249
250         my $current_timestamp = 'current_timestamp';
251         $extra_info{default_value} = \$current_timestamp;
252     }
253
254     return \%extra_info;
255 }
256
257 sub _dbh_column_info {
258     my $self = shift;
259
260     local $SIG{__WARN__} = sub { warn @_
261         unless $_[0] =~ /^column_info: unrecognized column type/ };
262
263     $self->next::method(@_);
264 }
265
266 sub _table_comment {
267     my ( $self, $table ) = @_;
268     my $comment = $self->next::method($table);
269     if (not $comment) {
270         ($comment) = try { $self->schema->storage->dbh->selectrow_array(
271             qq{SELECT table_comment
272                 FROM information_schema.tables
273                 WHERE table_schema = schema()
274                   AND table_name = ?
275             }, undef, $table);
276         };
277         # InnoDB likes to auto-append crap.
278         if (not $comment) {
279             # Do nothing.
280         }
281         elsif ($comment =~ /^InnoDB free:/) {
282             $comment = undef;
283         }
284         else {
285             $comment =~ s/; InnoDB.*//;
286         }
287     }
288     return $comment;
289 }
290
291 sub _column_comment {
292     my ( $self, $table, $column_number, $column_name ) = @_;
293     my $comment = $self->next::method($table, $column_number, $column_name);
294     if (not $comment) {
295         ($comment) = try { $self->schema->storage->dbh->selectrow_array(
296             qq{SELECT column_comment
297                 FROM information_schema.columns
298                 WHERE table_schema = schema()
299                   AND table_name = ?
300                   AND column_name = ?
301             }, undef, $table, $column_name);
302         };
303     }
304     return $comment;
305 }
306
307 =head1 SEE ALSO
308
309 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
310 L<DBIx::Class::Schema::Loader::DBI>
311
312 =head1 AUTHOR
313
314 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
315
316 =head1 LICENSE
317
318 This library is free software; you can redistribute it and/or modify it under
319 the same terms as Perl itself.
320
321 =cut
322
323 1;
324 # vim:et sw=4 sts=4 tw=0: