doc MSSQL case issues
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / DBI / MSSQL.pm
1 package DBIx::Class::Schema::Loader::DBI::MSSQL;
2
3 use strict;
4 use warnings;
5 use base 'DBIx::Class::Schema::Loader::DBI::Sybase::Common';
6 use Carp::Clan qw/^DBIx::Class/;
7 use Class::C3;
8
9 __PACKAGE__->mk_group_accessors('simple', qw/
10     case_sensitive_collation
11 /);
12
13 our $VERSION = '0.06000';
14
15 =head1 NAME
16
17 DBIx::Class::Schema::Loader::DBI::MSSQL - DBIx::Class::Schema::Loader::DBI MSSQL Implementation.
18
19 =head1 DESCRIPTION
20
21 Base driver for Microsoft SQL Server, used by
22 L<DBIx::Class::Schema::Loader::DBI::Sybase::Microsoft_SQL_Server> for support
23 via L<DBD::Sybase> and
24 L<DBIx::Class::Schema::Loader::DBI::ODBC::Microsoft_SQL_Server> for support via
25 L<DBD::ODBC>.
26
27 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base> for
28 usage information.
29
30 =head1 CASE SENSITIVITY
31
32 Most MSSQL databases use C<CI> (case-insensitive) collation, for this reason
33 generated column names are lower-cased as this makes them easier to work with
34 in L<DBIx::Class>.
35
36 We attempt to detect the database collation at startup, and set the column
37 lowercasing behavior accordingly, as lower-cased column names do not work on
38 case-sensitive databases.
39
40 If you are using FreeTDS with C<tds version> set to C<8.0> the collation
41 detection may fail, and Loader will default to case-insensitive mode. C<tds
42 version> C<7.0> will work fine.
43
44 If this happens set:
45
46     case_sensitive_collation => 1
47
48 in your Loader options to override it.
49
50 =cut
51
52 sub _is_case_sensitive {
53     my $self = shift;
54
55     return $self->case_sensitive_collation ? 1 : 0;
56 }
57
58 sub _setup {
59     my $self = shift;
60
61     $self->next::method;
62
63     return if defined $self->case_sensitive_collation;
64
65     my $dbh = $self->schema->storage->dbh;
66
67     # We use the sys.databases query for the general case, and fallback to
68     # databasepropertyex() if for some reason sys.databases is not available,
69     # which does not work over DBD::ODBC with unixODBC+FreeTDS.
70     #
71     # XXX why does databasepropertyex() not work over DBD::ODBC ?
72     #
73     # more on collations here: http://msdn.microsoft.com/en-us/library/ms143515.aspx
74     my ($collation_name) =
75            eval { $dbh->selectrow_array('SELECT collation_name FROM sys.databases WHERE name = DB_NAME()') }
76         || eval { $dbh->selectrow_array("SELECT databasepropertyex(DB_NAME(), 'Collation')") };
77
78     if (not $collation_name) {
79         warn <<'EOF';
80
81 WARNING: MSSQL Collation detection failed. Defaulting to case-insensitive mode.
82 Override the 'case_sensitive_collation' attribute in your Loader options if
83 needed.
84 EOF
85         $self->case_sensitive_collation(0);
86         return;
87     }
88
89     my $case_sensitive = $collation_name =~ /_(?:CS|BIN2?)(?:_|\z)/;
90
91     $self->case_sensitive_collation($case_sensitive ? 1 : 0);
92 }
93
94 sub _lc {
95     my ($self, $name) = @_;
96
97     return $self->case_sensitive_collation ? $name : lc($name);
98 }
99
100 sub _tables_list {
101     my ($self, $opts) = @_;
102
103     my $dbh = $self->schema->storage->dbh;
104     my $sth = $dbh->prepare(<<'EOF');
105 SELECT t.table_name
106 FROM INFORMATION_SCHEMA.TABLES t
107 WHERE lower(t.table_schema) = ?
108 EOF
109     $sth->execute(lc $self->db_schema);
110
111     my @tables = map @$_, @{ $sth->fetchall_arrayref };
112
113     return $self->_filter_tables(\@tables, $opts);
114 }
115
116 sub _table_pk_info {
117     my ($self, $table) = @_;
118     my $dbh = $self->schema->storage->dbh;
119     my $sth = $dbh->prepare(qq{sp_pkeys '$table'});
120     $sth->execute;
121
122     my @keydata;
123
124     while (my $row = $sth->fetchrow_hashref) {
125         push @keydata, $self->_lc($row->{COLUMN_NAME});
126     }
127
128     return \@keydata;
129 }
130
131 sub _table_fk_info {
132     my ($self, $table) = @_;
133
134     my ($local_cols, $remote_cols, $remote_table, @rels, $sth);
135     my $dbh = $self->schema->storage->dbh;
136     eval {
137         $sth = $dbh->prepare(qq{sp_fkeys \@fktable_name = '$table'});
138         $sth->execute;
139     };
140
141     while (my $row = eval { $sth->fetchrow_hashref }) {
142         my $fk = $row->{FK_NAME};
143         push @{$local_cols->{$fk}}, $self->_lc($row->{FKCOLUMN_NAME});
144         push @{$remote_cols->{$fk}}, $self->_lc($row->{PKCOLUMN_NAME});
145         $remote_table->{$fk} = $row->{PKTABLE_NAME};
146     }
147
148     foreach my $fk (keys %$remote_table) {
149         push @rels, {
150                       local_columns => \@{$local_cols->{$fk}},
151                       remote_columns => \@{$remote_cols->{$fk}},
152                       remote_table => $remote_table->{$fk},
153                     };
154
155     }
156     return \@rels;
157 }
158
159 sub _table_uniq_info {
160     my ($self, $table) = @_;
161
162     my $dbh = $self->schema->storage->dbh;
163     local $dbh->{FetchHashKeyName} = 'NAME_lc';
164
165     my $sth = $dbh->prepare(qq{
166 SELECT ccu.constraint_name, ccu.column_name
167 FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
168 JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc on (ccu.constraint_name = tc.constraint_name)
169 JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu on (ccu.constraint_name = kcu.constraint_name and ccu.column_name = kcu.column_name)
170 wHERE lower(ccu.table_name) = @{[ $dbh->quote(lc $table) ]} AND constraint_type = 'UNIQUE' ORDER BY kcu.ordinal_position
171     });
172     $sth->execute;
173     my $constraints;
174     while (my $row = $sth->fetchrow_hashref) {
175         my $name = $row->{constraint_name};
176         my $col  = $self->_lc($row->{column_name});
177         push @{$constraints->{$name}}, $col;
178     }
179
180     my @uniqs = map { [ $_ => $constraints->{$_} ] } keys %$constraints;
181     return \@uniqs;
182 }
183
184 sub _columns_info_for {
185     my $self    = shift;
186     my ($table) = @_;
187
188     my $result = $self->next::method(@_);
189
190     while (my ($col, $info) = each %$result) {
191         my $dbh = $self->schema->storage->dbh;
192
193         my $sth = $dbh->prepare(qq{
194 SELECT column_name 
195 FROM INFORMATION_SCHEMA.COLUMNS
196 WHERE columnproperty(object_id(@{[ $dbh->quote(lc $table) ]}, 'U'), @{[ $dbh->quote(lc $col) ]}, 'IsIdentity') = 1
197 AND lower(table_name) = @{[ $dbh->quote(lc $table) ]} AND lower(column_name) = @{[ $dbh->quote(lc $col) ]}
198         });
199         if (eval { $sth->execute; $sth->fetchrow_array }) {
200             $info->{is_auto_increment} = 1;
201             $info->{data_type} =~ s/\s*identity//i;
202             delete $info->{size};
203         }
204
205 # get default
206         $sth = $dbh->prepare(qq{
207 SELECT column_default
208 FROM INFORMATION_SCHEMA.COLUMNS
209 wHERE lower(table_name) = @{[ $dbh->quote(lc $table) ]} AND lower(column_name) = @{[ $dbh->quote(lc $col) ]}
210         });
211         my ($default) = eval { $sth->execute; $sth->fetchrow_array };
212
213         if (defined $default) {
214             # strip parens
215             $default =~ s/^\( (.*) \)\z/$1/x;
216
217             # Literal strings are in ''s, numbers are in ()s (in some versions of
218             # MSSQL, in others they are unquoted) everything else is a function.
219             $info->{default_value} =
220                 $default =~ /^['(] (.*) [)']\z/x ? $1 :
221                     $default =~ /^\d/ ? $default : \$default;
222         }
223     }
224
225     return $result;
226 }
227
228 =head1 SEE ALSO
229
230 L<DBIx::Class::Schema::Loader::DBI::Sybase::Microsoft_SQL_Server>,
231 L<DBIx::Class::Schema::Loader::DBI::ODBC::Microsoft_SQL_Server>,
232 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
233 L<DBIx::Class::Schema::Loader::DBI>
234
235 =head1 AUTHOR
236
237 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
238
239 =head1 LICENSE
240
241 This library is free software; you can redistribute it and/or modify it under
242 the same terms as Perl itself.
243
244 =cut
245
246 1;
247 # vim:et sts=4 sw=4 tw=0: