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