automatically turn on quoting for MySQL (RT#60469)
[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 List::Util 'first';
8 use namespace::clean;
9
10 our $VERSION = '0.07010';
11
12 =head1 NAME
13
14 DBIx::Class::Schema::Loader::DBI::mysql - DBIx::Class::Schema::Loader::DBI mysql Implementation.
15
16 =head1 DESCRIPTION
17
18 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
19
20 =cut
21
22 sub _setup {
23     my $self = shift;
24
25     $self->schema->storage->sql_maker->quote_char("`");
26     $self->schema->storage->sql_maker->name_sep(".");
27
28     $self->next::method(@_);
29
30     if (not defined $self->preserve_case) {
31         $self->preserve_case(0);
32     }
33 }
34
35 sub _tables_list { 
36     my ($self, $opts) = @_;
37
38     return $self->next::method($opts, undef, undef);
39 }
40
41 sub _table_fk_info {
42     my ($self, $table) = @_;
43
44     my $dbh = $self->schema->storage->dbh;
45
46     my $table_def_ref = eval { $dbh->selectrow_arrayref("SHOW CREATE TABLE `$table`") };
47     my $table_def = $table_def_ref->[1];
48
49     return [] if not $table_def;
50
51     my $qt = qr/["`]/;
52
53     my (@reldata) = ($table_def =~
54         /CONSTRAINT $qt.*$qt FOREIGN KEY \($qt(.*)$qt\) REFERENCES $qt(.*)$qt \($qt(.*)$qt\)/ig
55     );
56
57     my @rels;
58     while (scalar @reldata > 0) {
59         my $cols = shift @reldata;
60         my $f_table = shift @reldata;
61         my $f_cols = shift @reldata;
62
63         my @cols   = map { s/(?: \Q$self->{_quoter}\E | $qt )//x; $self->_lc($_) }
64             split(/$qt?\s*$qt?,$qt?\s*$qt?/, $cols);
65
66         my @f_cols = map { s/(?: \Q$self->{_quoter}\E | $qt )//x; $self->_lc($_) }
67             split(/$qt?\s*$qt?,$qt?\s*$qt?/, $f_cols);
68
69         my $remote_table = first { $_ =~ /^${f_table}\z/i } $self->_tables_list;
70
71         push(@rels, {
72             local_columns => \@cols,
73             remote_columns => \@f_cols,
74             remote_table => $remote_table,
75         });
76     }
77
78     return \@rels;
79 }
80
81 # primary and unique info comes from the same sql statement,
82 #   so cache it here for both routines to use
83 sub _mysql_table_get_keys {
84     my ($self, $table) = @_;
85
86     if(!exists($self->{_cache}->{_mysql_keys}->{$table})) {
87         my %keydata;
88         my $dbh = $self->schema->storage->dbh;
89         my $sth = $dbh->prepare('SHOW INDEX FROM '.$self->_table_as_sql($table));
90         $sth->execute;
91         while(my $row = $sth->fetchrow_hashref) {
92             next if $row->{Non_unique};
93             push(@{$keydata{$row->{Key_name}}},
94                 [ $row->{Seq_in_index}, $self->_lc($row->{Column_name}) ]
95             );
96         }
97         foreach my $keyname (keys %keydata) {
98             my @ordered_cols = map { $_->[1] } sort { $a->[0] <=> $b->[0] }
99                 @{$keydata{$keyname}};
100             $keydata{$keyname} = \@ordered_cols;
101         }
102         $self->{_cache}->{_mysql_keys}->{$table} = \%keydata;
103     }
104
105     return $self->{_cache}->{_mysql_keys}->{$table};
106 }
107
108 sub _table_pk_info {
109     my ( $self, $table ) = @_;
110
111     return $self->_mysql_table_get_keys($table)->{PRIMARY};
112 }
113
114 sub _table_uniq_info {
115     my ( $self, $table ) = @_;
116
117     my @uniqs;
118     my $keydata = $self->_mysql_table_get_keys($table);
119     foreach my $keyname (keys %$keydata) {
120         next if $keyname eq 'PRIMARY';
121         push(@uniqs, [ $keyname => $keydata->{$keyname} ]);
122     }
123
124     return \@uniqs;
125 }
126
127 sub _columns_info_for {
128     my $self = shift;
129     my ($table) = @_;
130
131     my $result = $self->next::method(@_);
132
133     my $dbh = $self->schema->storage->dbh;
134
135     while (my ($col, $info) = each %$result) {
136         delete $info->{size} if $info->{data_type} !~ /^(?: (?:var)?(?:char(?:acter)?|binary) | bit | year)\z/ix;
137
138         if ($info->{data_type} eq 'int') {
139             $info->{data_type} = 'integer';
140         }
141         elsif ($info->{data_type} eq 'double') {
142             $info->{data_type} = 'double precision';
143         }
144
145         # information_schema is available in 5.0+
146         my ($precision, $scale, $column_type, $default) = eval { $dbh->selectrow_array(<<'EOF', {}, $table, $col) };
147 SELECT numeric_precision, numeric_scale, column_type, column_default
148 FROM information_schema.columns
149 WHERE table_name = ? AND column_name = ?
150 EOF
151         my $has_information_schema = not defined $@;
152
153         $column_type = '' if not defined $column_type;
154
155         if ($info->{data_type} eq 'bit' && (not exists $info->{size})) {
156             $info->{size} = $precision if defined $precision;
157         }
158         elsif ($info->{data_type} =~ /^(?:float|double precision|decimal)\z/i) {
159             if (defined $precision && defined $scale) {
160                 if ($precision == 10 && $scale == 0) {
161                     delete $info->{size};
162                 }
163                 else {
164                     $info->{size} = [$precision,$scale];
165                 }
166             }
167         }
168         elsif ($info->{data_type} eq 'year') {
169             if ($column_type =~ /\(2\)/) {
170                 $info->{size} = 2;
171             }
172             elsif ($column_type =~ /\(4\)/ || $info->{size} == 4) {
173                 delete $info->{size};
174             }
175         }
176         elsif ($info->{data_type} =~ /^(?:date(?:time)?|timestamp)\z/) {
177             if (not (defined $self->datetime_undef_if_invalid && $self->datetime_undef_if_invalid == 0)) {
178                 $info->{datetime_undef_if_invalid} = 1;
179             }
180         }
181
182         # Sometimes apparently there's a bug where default_value gets set to ''
183         # for things that don't actually have or support that default (like ints.)
184         if (exists $info->{default_value} && $info->{default_value} eq '') {
185             if ($has_information_schema) {
186                 if (not defined $default) {
187                     delete $info->{default_value};
188                 }
189             }
190             else { # just check if it's a char/text type, otherwise remove
191                 delete $info->{default_value} unless $info->{data_type} =~ /char|text/i;
192             }
193         }
194     }
195
196     return $result;
197 }
198
199 sub _extra_column_info {
200     no warnings 'uninitialized';
201     my ($self, $table, $col, $info, $dbi_info) = @_;
202     my %extra_info;
203
204     if ($dbi_info->{mysql_is_auto_increment}) {
205         $extra_info{is_auto_increment} = 1
206     }
207     if ($dbi_info->{mysql_type_name} =~ /\bunsigned\b/i) {
208         $extra_info{extra}{unsigned} = 1;
209     }
210     if ($dbi_info->{mysql_values}) {
211         $extra_info{extra}{list} = $dbi_info->{mysql_values};
212     }
213     if (   lc($dbi_info->{COLUMN_DEF})      eq 'current_timestamp'
214         && lc($dbi_info->{mysql_type_name}) eq 'timestamp') {
215
216         my $current_timestamp = 'current_timestamp';
217         $extra_info{default_value} = \$current_timestamp;
218     }
219
220     return \%extra_info;
221 }
222
223 sub _dbh_column_info {
224     my $self = shift;
225
226     local $SIG{__WARN__} = sub { warn @_
227         unless $_[0] =~ /^column_info: unrecognized column type/ };
228
229     $self->next::method(@_);
230 }
231
232 =head1 SEE ALSO
233
234 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
235 L<DBIx::Class::Schema::Loader::DBI>
236
237 =head1 AUTHOR
238
239 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
240
241 =head1 LICENSE
242
243 This library is free software; you can redistribute it and/or modify it under
244 the same terms as Perl itself.
245
246 =cut
247
248 1;
249 # vim:et sw=4 sts=4 tw=0: