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