Added Storage::DBI subclass for MSSQL auto PK over ODBC.
[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 insert {
18     my ($self, $source, $to_insert) = @_;
19
20     my $bind_attributes = $self->source_bind_attributes($source);
21     my (undef, $sth) = $self->_execute( 'insert' => [], $source, $bind_attributes, $to_insert);
22     $self->{_scope_identity} = $sth->fetchrow_array;
23
24     return $to_insert;
25 }
26
27 sub last_insert_id { shift->{_scope_identity} }
28
29 sub sqlt_type { 'SQLServer' }
30
31 sub _sql_maker_opts {
32     my ( $self, $opts ) = @_;
33
34     if ( $opts ) {
35         $self->{_sql_maker_opts} = { %$opts };
36     }
37
38     return { limit_dialect => 'Top', %{$self->{_sql_maker_opts}||{}} };
39 }
40
41 1;
42
43 __END__
44
45 =head1 NAME
46
47 DBIx::Class::Storage::ODBC::Microsoft_SQL_Server - Support specific to
48 Microsoft SQL Server over ODBC
49
50 =head1 DESCRIPTION
51
52 This class implements support specific to Microsoft SQL Server over ODBC,
53 including auto-increment primary keys and SQL::Abstract::Limit dialect.  It
54 is loaded automatically by by DBIx::Class::Storage::DBI::ODBC when it
55 detects a MSSQL back-end.
56
57 =head1 IMPLEMENTATION NOTES
58
59 Microsoft SQL Server supports three methods of retrieving the IDENTITY
60 value for inserted row: IDENT_CURRENT, @@IDENTITY, and SCOPE_IDENTITY().
61 SCOPE_IDENTITY is used here because it is the safest.  However, it must
62 be called is the same execute statement, not just the same connection.
63
64 So, this implementation appends a SELECT SCOPE_IDENTITY() statement
65 onto each INSERT to accommodate that requirement.
66
67
68 =head1 AUTHORS
69
70 Marc Mims C<< <marc@questright.com> >>
71
72 =head1 LICENSE
73
74 You may distribute this code under the same terms as Perl itself.
75
76 =cut