fix MSSQL collation detection on freetds tds version 8.0
[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 To manually set or unset case-sensitive mode, put:
41
42     case_sensitive_collation => 1
43
44 in your Loader options.
45
46 =cut
47
48 sub _is_case_sensitive {
49     my $self = shift;
50
51     return $self->case_sensitive_collation ? 1 : 0;
52 }
53
54 sub _setup {
55     my $self = shift;
56
57     $self->next::method;
58
59     return if defined $self->case_sensitive_collation;
60
61     my $dbh = $self->schema->storage->dbh;
62
63     # We use the sys.databases query for the general case, and fallback to
64     # databasepropertyex() if for some reason sys.databases is not available,
65     # which does not work over DBD::ODBC with unixODBC+FreeTDS.
66     #
67     # XXX why does databasepropertyex() not work over DBD::ODBC ?
68     #
69     # more on collations here: http://msdn.microsoft.com/en-us/library/ms143515.aspx
70     my ($collation_name) =
71            eval { $dbh->selectrow_array('SELECT collation_name FROM sys.databases WHERE name = DB_NAME()') }
72         || eval { $dbh->selectrow_array("SELECT CAST(databasepropertyex(DB_NAME(), 'Collation') AS VARCHAR)") };
73
74     if (not $collation_name) {
75         warn <<'EOF';
76
77 WARNING: MSSQL Collation detection failed. Defaulting to case-insensitive mode.
78 Override the 'case_sensitive_collation' attribute in your Loader options if
79 needed.
80 EOF
81         $self->case_sensitive_collation(0);
82         return;
83     }
84
85     my $case_sensitive = $collation_name =~ /_(?:CS|BIN2?)(?:_|\z)/;
86
87     $self->case_sensitive_collation($case_sensitive ? 1 : 0);
88 }
89
90 sub _lc {
91     my ($self, $name) = @_;
92
93     return $self->case_sensitive_collation ? $name : lc($name);
94 }
95
96 sub _tables_list {
97     my ($self, $opts) = @_;
98
99     my $dbh = $self->schema->storage->dbh;
100     my $sth = $dbh->prepare(<<'EOF');
101 SELECT t.table_name
102 FROM INFORMATION_SCHEMA.TABLES t
103 WHERE lower(t.table_schema) = ?
104 EOF
105     $sth->execute(lc $self->db_schema);
106
107     my @tables = map @$_, @{ $sth->fetchall_arrayref };
108
109     return $self->_filter_tables(\@tables, $opts);
110 }
111
112 sub _table_pk_info {
113     my ($self, $table) = @_;
114     my $dbh = $self->schema->storage->dbh;
115     my $sth = $dbh->prepare(qq{sp_pkeys '$table'});
116     $sth->execute;
117
118     my @keydata;
119
120     while (my $row = $sth->fetchrow_hashref) {
121         push @keydata, $self->_lc($row->{COLUMN_NAME});
122     }
123
124     return \@keydata;
125 }
126
127 sub _table_fk_info {
128     my ($self, $table) = @_;
129
130     my ($local_cols, $remote_cols, $remote_table, @rels, $sth);
131     my $dbh = $self->schema->storage->dbh;
132     eval {
133         $sth = $dbh->prepare(qq{sp_fkeys \@fktable_name = '$table'});
134         $sth->execute;
135     };
136
137     while (my $row = eval { $sth->fetchrow_hashref }) {
138         my $fk = $row->{FK_NAME};
139         push @{$local_cols->{$fk}}, $self->_lc($row->{FKCOLUMN_NAME});
140         push @{$remote_cols->{$fk}}, $self->_lc($row->{PKCOLUMN_NAME});
141         $remote_table->{$fk} = $row->{PKTABLE_NAME};
142     }
143
144     foreach my $fk (keys %$remote_table) {
145         push @rels, {
146                       local_columns => \@{$local_cols->{$fk}},
147                       remote_columns => \@{$remote_cols->{$fk}},
148                       remote_table => $remote_table->{$fk},
149                     };
150
151     }
152     return \@rels;
153 }
154
155 sub _table_uniq_info {
156     my ($self, $table) = @_;
157
158     my $dbh = $self->schema->storage->dbh;
159     local $dbh->{FetchHashKeyName} = 'NAME_lc';
160
161     my $sth = $dbh->prepare(qq{
162 SELECT ccu.constraint_name, ccu.column_name
163 FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
164 JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc on (ccu.constraint_name = tc.constraint_name)
165 JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu on (ccu.constraint_name = kcu.constraint_name and ccu.column_name = kcu.column_name)
166 wHERE lower(ccu.table_name) = @{[ $dbh->quote(lc $table) ]} AND constraint_type = 'UNIQUE' ORDER BY kcu.ordinal_position
167     });
168     $sth->execute;
169     my $constraints;
170     while (my $row = $sth->fetchrow_hashref) {
171         my $name = $row->{constraint_name};
172         my $col  = $self->_lc($row->{column_name});
173         push @{$constraints->{$name}}, $col;
174     }
175
176     my @uniqs = map { [ $_ => $constraints->{$_} ] } keys %$constraints;
177     return \@uniqs;
178 }
179
180 sub _columns_info_for {
181     my $self    = shift;
182     my ($table) = @_;
183
184     my $result = $self->next::method(@_);
185
186     while (my ($col, $info) = each %$result) {
187         my $dbh = $self->schema->storage->dbh;
188
189         my $sth = $dbh->prepare(qq{
190 SELECT column_name 
191 FROM INFORMATION_SCHEMA.COLUMNS
192 WHERE columnproperty(object_id(@{[ $dbh->quote(lc $table) ]}, 'U'), @{[ $dbh->quote(lc $col) ]}, 'IsIdentity') = 1
193 AND lower(table_name) = @{[ $dbh->quote(lc $table) ]} AND lower(column_name) = @{[ $dbh->quote(lc $col) ]}
194         });
195         if (eval { $sth->execute; $sth->fetchrow_array }) {
196             $info->{is_auto_increment} = 1;
197             $info->{data_type} =~ s/\s*identity//i;
198             delete $info->{size};
199         }
200
201 # get default
202         $sth = $dbh->prepare(qq{
203 SELECT column_default
204 FROM INFORMATION_SCHEMA.COLUMNS
205 wHERE lower(table_name) = @{[ $dbh->quote(lc $table) ]} AND lower(column_name) = @{[ $dbh->quote(lc $col) ]}
206         });
207         my ($default) = eval { $sth->execute; $sth->fetchrow_array };
208
209         if (defined $default) {
210             # strip parens
211             $default =~ s/^\( (.*) \)\z/$1/x;
212
213             # Literal strings are in ''s, numbers are in ()s (in some versions of
214             # MSSQL, in others they are unquoted) everything else is a function.
215             $info->{default_value} =
216                 $default =~ /^['(] (.*) [)']\z/x ? $1 :
217                     $default =~ /^\d/ ? $default : \$default;
218         }
219     }
220
221     return $result;
222 }
223
224 =head1 SEE ALSO
225
226 L<DBIx::Class::Schema::Loader::DBI::Sybase::Microsoft_SQL_Server>,
227 L<DBIx::Class::Schema::Loader::DBI::ODBC::Microsoft_SQL_Server>,
228 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
229 L<DBIx::Class::Schema::Loader::DBI>
230
231 =head1 AUTHOR
232
233 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
234
235 =head1 LICENSE
236
237 This library is free software; you can redistribute it and/or modify it under
238 the same terms as Perl itself.
239
240 =cut
241
242 1;
243 # vim:et sts=4 sw=4 tw=0: