match case of FK remote database in MySQL
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / DBI / mysql.pm
CommitLineData
996be9ee 1package DBIx::Class::Schema::Loader::DBI::mysql;
2
3use strict;
4use warnings;
5use base 'DBIx::Class::Schema::Loader::DBI';
942bd5e0 6use mro 'c3';
c4a69b87 7use Carp::Clan qw/^DBIx::Class/;
c0767caf 8use List::Util 'first';
c4a69b87 9use List::MoreUtils 'any';
ea998e8e 10use Try::Tiny;
c0767caf 11use namespace::clean;
2fa86d8b 12use DBIx::Class::Schema::Loader::Table ();
996be9ee 13
4295c4b4 14our $VERSION = '0.07010';
32f784fc 15
996be9ee 16=head1 NAME
17
18DBIx::Class::Schema::Loader::DBI::mysql - DBIx::Class::Schema::Loader::DBI mysql Implementation.
19
996be9ee 20=head1 DESCRIPTION
21
c0767caf 22See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
996be9ee 23
24=cut
25
bc1cb85e 26sub _setup {
27 my $self = shift;
28
6ebd0f33 29 $self->schema->storage->sql_maker->quote_char("`");
30 $self->schema->storage->sql_maker->name_sep(".");
31
bc1cb85e 32 $self->next::method(@_);
33
34 if (not defined $self->preserve_case) {
35 $self->preserve_case(0);
36 }
c4a69b87 37
38 if ($self->db_schema && $self->db_schema->[0] eq '%') {
39 my @schemas = try {
ba3e8f02 40 $self->_show_databases;
c4a69b87 41 }
42 catch {
43 croak "no SHOW DATABASES privileges: $_";
44 };
45
46 @schemas = grep {
47 my $schema = $_;
ba3e8f02 48 not any { lc($schema) eq lc($_) } $self->_system_schemas
c4a69b87 49 } @schemas;
50
51 $self->db_schema(\@schemas);
52 }
53}
54
ba3e8f02 55sub _show_databases {
56 my $self = shift;
57
58 return map $_->[0], @{ $self->dbh->selectall_arrayref('SHOW DATABASES') };
59}
60
c4a69b87 61sub _system_schemas {
62 my $self = shift;
63
64 return ($self->next::method(@_), 'mysql');
bc1cb85e 65}
66
518472fa 67sub _tables_list {
bfb43060 68 my ($self, $opts) = @_;
518472fa 69
bfb43060 70 return $self->next::method($opts, undef, undef);
518472fa 71}
72
996be9ee 73sub _table_fk_info {
74 my ($self, $table) = @_;
75
c4a69b87 76 my $table_def_ref = eval { $self->dbh->selectrow_arrayref("SHOW CREATE TABLE ".$table->sql_name) };
3de915bc 77 my $table_def = $table_def_ref->[1];
78
79 return [] if not $table_def;
309e2aa1 80
c4a69b87 81 my $qt = qr/["`]/;
82 my $nqt = qr/[^"`]/;
309e2aa1 83
84 my (@reldata) = ($table_def =~
c4a69b87 85 /CONSTRAINT ${qt}${nqt}+${qt} FOREIGN KEY \($qt(.*)$qt\) REFERENCES (?:$qt($nqt+)$qt\.)?$qt($nqt+)$qt \($qt(.+)$qt\)/ig
309e2aa1 86 );
996be9ee 87
88 my @rels;
89 while (scalar @reldata > 0) {
c4a69b87 90 my ($cols, $f_schema, $f_table, $f_cols) = splice @reldata, 0, 4;
996be9ee 91
c4a69b87 92 my @cols = map { s/$qt//g; $self->_lc($_) }
be72dba7 93 split(/$qt?\s*$qt?,$qt?\s*$qt?/, $cols);
5223f24a 94
c4a69b87 95 my @f_cols = map { s/$qt//g; $self->_lc($_) }
be72dba7 96 split(/$qt?\s*$qt?,$qt?\s*$qt?/, $f_cols);
996be9ee 97
ba3e8f02 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
2fa86d8b 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 }
c0767caf 130
996be9ee 131 push(@rels, {
132 local_columns => \@cols,
133 remote_columns => \@f_cols,
c0767caf 134 remote_table => $remote_table,
996be9ee 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
143sub _mysql_table_get_keys {
144 my ($self, $table) = @_;
145
5223f24a 146 if(!exists($self->{_cache}->{_mysql_keys}->{$table})) {
996be9ee 147 my %keydata;
c4a69b87 148 my $sth = $self->dbh->prepare('SHOW INDEX FROM '.$table->sql_name);
996be9ee 149 $sth->execute;
150 while(my $row = $sth->fetchrow_hashref) {
151 next if $row->{Non_unique};
152 push(@{$keydata{$row->{Key_name}}},
bc1cb85e 153 [ $row->{Seq_in_index}, $self->_lc($row->{Column_name}) ]
996be9ee 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 }
5223f24a 161 $self->{_cache}->{_mysql_keys}->{$table} = \%keydata;
996be9ee 162 }
163
5223f24a 164 return $self->{_cache}->{_mysql_keys}->{$table};
996be9ee 165}
166
167sub _table_pk_info {
168 my ( $self, $table ) = @_;
169
170 return $self->_mysql_table_get_keys($table)->{PRIMARY};
171}
172
173sub _table_uniq_info {
174 my ( $self, $table ) = @_;
175
176 my @uniqs;
177 my $keydata = $self->_mysql_table_get_keys($table);
8ac8926d 178 foreach my $keyname (keys %$keydata) {
996be9ee 179 next if $keyname eq 'PRIMARY';
180 push(@uniqs, [ $keyname => $keydata->{$keyname} ]);
181 }
182
183 return \@uniqs;
184}
185
26334ec1 186sub _columns_info_for {
187 my $self = shift;
188 my ($table) = @_;
189
190 my $result = $self->next::method(@_);
191
26334ec1 192 while (my ($col, $info) = each %$result) {
26334ec1 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 }
698c11d8 199 my $data_type = $info->{data_type};
200
201 delete $info->{size} if $data_type !~ /^(?: (?:var)?(?:char(?:acter)?|binary) | bit | year)\z/ix;
26334ec1 202
f80b0ea7 203 # information_schema is available in 5.0+
c4a69b87 204 my ($precision, $scale, $column_type, $default) = eval { $self->dbh->selectrow_array(<<'EOF', {}, $table, $col) };
33aa3462 205SELECT numeric_precision, numeric_scale, column_type, column_default
26334ec1 206FROM information_schema.columns
33aa3462 207WHERE table_name = ? AND column_name = ?
26334ec1 208EOF
698c11d8 209 my $has_information_schema = not $@;
33aa3462 210
26334ec1 211 $column_type = '' if not defined $column_type;
212
698c11d8 213 if ($data_type eq 'bit' && (not exists $info->{size})) {
26334ec1 214 $info->{size} = $precision if defined $precision;
215 }
698c11d8 216 elsif ($data_type =~ /^(?:float|double precision|decimal)\z/i) {
26334ec1 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 }
698c11d8 226 elsif ($data_type eq 'year') {
26334ec1 227 if ($column_type =~ /\(2\)/) {
228 $info->{size} = 2;
229 }
230 elsif ($column_type =~ /\(4\)/ || $info->{size} == 4) {
231 delete $info->{size};
232 }
233 }
698c11d8 234 elsif ($data_type =~ /^(?:date(?:time)?|timestamp)\z/) {
57a9fc92 235 if (not (defined $self->datetime_undef_if_invalid && $self->datetime_undef_if_invalid == 0)) {
236 $info->{datetime_undef_if_invalid} = 1;
237 }
58333f16 238 }
698c11d8 239 elsif ($data_type =~ /^(?:enum|set)\z/ && $has_information_schema
240 && $column_type =~ /^(?:enum|set)\(/) {
241
242 delete $info->{extra}{list};
243
e00d61ac 244 while ($column_type =~ /'((?:[^']* (?:''|\\')* [^']*)* [^\\'])',?/xg) {
245 my $el = $1;
246 $el =~ s/''/'/g;
247 push @{ $info->{extra}{list} }, $el;
698c11d8 248 }
249 }
33aa3462 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
698c11d8 260 delete $info->{default_value} unless $data_type =~ /char|text/i;
33aa3462 261 }
262 }
26334ec1 263 }
264
265 return $result;
266}
267
a8df0345 268sub _extra_column_info {
f430297e 269 no warnings 'uninitialized';
45be2ce7 270 my ($self, $table, $col, $info, $dbi_info) = @_;
a8df0345 271 my %extra_info;
78b7ccaa 272
45be2ce7 273 if ($dbi_info->{mysql_is_auto_increment}) {
a8df0345 274 $extra_info{is_auto_increment} = 1
275 }
45be2ce7 276 if ($dbi_info->{mysql_type_name} =~ /\bunsigned\b/i) {
46bef65f 277 $extra_info{extra}{unsigned} = 1;
278 }
45be2ce7 279 if ($dbi_info->{mysql_values}) {
280 $extra_info{extra}{list} = $dbi_info->{mysql_values};
8fdd52a2 281 }
3372cb43 282 if ( lc($dbi_info->{COLUMN_DEF}) eq 'current_timestamp'
283 && lc($dbi_info->{mysql_type_name}) eq 'timestamp') {
3facc532 284
6e566cc4 285 my $current_timestamp = 'current_timestamp';
286 $extra_info{default_value} = \$current_timestamp;
f430297e 287 }
8fdd52a2 288
a8df0345 289 return \%extra_info;
8fdd52a2 290}
291
db9c411a 292sub _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
5c06aa08 301sub _table_comment {
302 my ( $self, $table ) = @_;
303 my $comment = $self->next::method($table);
304 if (not $comment) {
ea998e8e 305 ($comment) = try { $self->schema->storage->dbh->selectrow_array(
5c06aa08 306 qq{SELECT table_comment
307 FROM information_schema.tables
308 WHERE table_schema = schema()
309 AND table_name = ?
310 }, undef, $table);
ea998e8e 311 };
5c06aa08 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 }
ea998e8e 323 return $comment;
5c06aa08 324}
325
326sub _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) {
ea998e8e 330 ($comment) = try { $self->schema->storage->dbh->selectrow_array(
5c06aa08 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);
ea998e8e 337 };
5c06aa08 338 }
339 return $comment;
340}
341
996be9ee 342=head1 SEE ALSO
343
344L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
345L<DBIx::Class::Schema::Loader::DBI>
346
be80bba7 347=head1 AUTHOR
348
9cc8e7e1 349See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
be80bba7 350
351=head1 LICENSE
352
353This library is free software; you can redistribute it and/or modify it under
354the same terms as Perl itself.
355
996be9ee 356=cut
357
3581;
26334ec1 359# vim:et sw=4 sts=4 tw=0: