MSSQL through ODBC does not like unfinished statements - make sure we finish the...
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / ODBC / Microsoft_SQL_Server.pm
1 package DBIx::Class::Storage::DBI::ODBC::Microsoft_SQL_Server;
2 use strict;
3 use warnings;
4
5 use base qw/DBIx::Class::Storage::DBI/;
6
7 sub _prep_for_execute {
8     my $self = shift;
9     my ($op, $extra_bind, $ident, $args) = @_;
10
11     my ($sql, $bind) = $self->SUPER::_prep_for_execute(@_);
12     $sql .= ';SELECT SCOPE_IDENTITY()' if $op eq 'insert';
13
14     return ($sql, $bind);
15 }
16
17 sub _execute {
18     my $self = shift;
19     my ($op) = @_;
20
21     my ($rv, $sth, @bind) = $self->dbh_do($self->can('_dbh_execute'), @_);
22     if ($op eq 'insert') {
23       $self->{_scope_identity} = $sth->fetchrow_array;
24       $sth->finish;
25     }
26
27     return wantarray ? ($rv, $sth, @bind) : $rv;
28 }
29
30 sub last_insert_id { shift->{_scope_identity} }
31
32 sub sqlt_type { 'SQLServer' }
33
34 sub _sql_maker_opts {
35     my ( $self, $opts ) = @_;
36
37     if ( $opts ) {
38         $self->{_sql_maker_opts} = { %$opts };
39     }
40
41     return { limit_dialect => 'Top', %{$self->{_sql_maker_opts}||{}} };
42 }
43
44 sub build_datetime_parser {
45   my $self = shift;
46   my $type = "DateTime::Format::Strptime";
47   eval "use ${type}";
48   $self->throw_exception("Couldn't load ${type}: $@") if $@;
49   return $type->new( pattern => '%F %T' );
50 }
51
52 1;
53
54 __END__
55
56 =head1 NAME
57
58 DBIx::Class::Storage::DBI::ODBC::Microsoft_SQL_Server - Support specific
59 to Microsoft SQL Server over ODBC
60
61 =head1 DESCRIPTION
62
63 This class implements support specific to Microsoft SQL Server over ODBC,
64 including auto-increment primary keys and SQL::Abstract::Limit dialect.  It
65 is loaded automatically by by DBIx::Class::Storage::DBI::ODBC when it
66 detects a MSSQL back-end.
67
68 =head1 IMPLEMENTATION NOTES
69
70 Microsoft SQL Server supports three methods of retrieving the IDENTITY
71 value for inserted row: IDENT_CURRENT, @@IDENTITY, and SCOPE_IDENTITY().
72 SCOPE_IDENTITY is used here because it is the safest.  However, it must
73 be called is the same execute statement, not just the same connection.
74
75 So, this implementation appends a SELECT SCOPE_IDENTITY() statement
76 onto each INSERT to accommodate that requirement.
77
78 =head1 METHODS
79
80 =head2 last_insert_id
81
82 =head2 sqlt_type
83
84 =head2 build_datetime_parser
85
86 The resulting parser handles the MSSQL C<DATETIME> type, but is almost
87 certainly not sufficient for the other MSSQL 2008 date/time types.
88
89 =head1 AUTHORS
90
91 Marc Mims C<< <marc@questright.com> >>
92
93 =head1 LICENSE
94
95 You may distribute this code under the same terms as Perl itself.
96
97 =cut