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