MSSQL/Storage.pm

filter: Statementstmt 90.4% 19 / 21 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.8% 26 / 28 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« MSSQL.pm ↑ Summary Shortcut/ms.pm »
1 package DBIO::MSSQL::Storage;
2 # ABSTRACT: Base Class for Microsoft SQL Server support in DBIO
3  
4 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 2 ▶use base qw/
Subroutine BEGIN: called CC=1 SCAR=0.0
8 DBIO::Storage::DBI::UniqueIdentifier
9 DBIO::Storage::DBI::IdentityInsert
10 2 /;
11 2 ▶use mro 'c3';
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 2 ▶use Context::Preserve 'preserve_context';
Subroutine BEGIN: called CC=1 SCAR=0.0
14 2 ▶use Scope::Guard ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 2 ▶use SQL::Abstract::Util 'is_literal_value';
Subroutine BEGIN: called CC=1 SCAR=2.6
16 use Try::Tiny;
17 use namespace::clean;
18  
19 __PACKAGE__->mk_group_accessors(simple => qw/
20 _identity _identity_method _no_scope_identity_query
21 /);
22  
23 __PACKAGE__->sql_maker_class('DBIO::MSSQL::SQLMaker');
24  
25 __PACKAGE__->register_driver('MSSQL' => __PACKAGE__);
26  
27 __PACKAGE__->sql_quote_char([qw/[ ]/]);
28  
29 __PACKAGE__->datetime_parser_type (
30 'DBIO::MSSQL::Storage::DateTime::Format'
31 );
32  
33 __PACKAGE__->new_guid('NEWID()');
34  
35 sub dbio_deploy_class { 'DBIO::MSSQL::Deploy' }
36  
37 sub deploy_setup { }
38  
39  
40 sub _prep_for_execute {
41 my $self = shift;
42 my ($op, $ident, $args) = @_;
43  
44 # cast MONEY values properly
45 if ($op eq 'insert' || $op eq 'update') {
46 my $fields = $args->[0];
47  
48 my $colinfo = $ident->columns_info([keys %$fields]);
49  
50 for my $col (keys %$fields) {
51 # $ident is a result source object with INSERT/UPDATE ops
52 if (
53 $colinfo->{$col}{data_type}
54 &&
55 $colinfo->{$col}{data_type} =~ /^money\z/i
56 ) {
57 if(
58 length ref $fields->{$col}
59 and
60 my $lit = is_literal_value( $fields->{$col} )
61 ) {
62 # We are being fed a literal value
63 # Generally there is not much we can do about it, *except*
64 # in the unambiguous case of a lone bind parameter
65 $fields->{$col} = \[ 'CAST(? AS MONEY)', @{$lit}[ 1 .. $#$lit ] ]
66 if $lit->[0] eq '?';
67 }
68 # nonliteral - wrap away
69 else {
70 $fields->{$col} = \['CAST(? AS MONEY)', [ $col => $fields->{$col} ]];
71 }
72 }
73 }
74 }
75  
76 # UNIQUEIDENTIFIER columns that look like is_auto_increment are
77 # actually populated by NEWID() (see DBIO::Storage::DBI::UniqueIdentifier
78 # _prefetch_autovalues) - they are NOT real IDENTITY columns. Suppress
79 # the SET IDENTITY_INSERT wrapper the parent IdentityInsert would emit
80 # for any autoinc column with a value, otherwise MSSQL complains that
81 # the table has no IDENTITY property.
82 my $suppress_identity_insert = 0;
83 if ($op eq 'insert' and $self->_autoinc_supplied_for_op) {
84 my $colinfo = $ident->columns_info;
85 my $is_guid_autoinc = 0;
86 for my $col (keys %$colinfo) {
87 next unless $colinfo->{$col}{is_auto_increment};
88 my $dt = $colinfo->{$col}{data_type} || '';
89 if ($dt =~ /^(?:uniqueidentifier(?:str)?|guid)\z/i) {
90 $is_guid_autoinc = 1;
91 last;
92 }
93 }
94 $suppress_identity_insert = 1 if $is_guid_autoinc;
95 }
96  
97 my ($sql, $bind);
98 if ($suppress_identity_insert) {
99 local $self->{_autoinc_supplied_for_op} = 0;
100 ($sql, $bind) = $self->next::method(@_);
101 }
102 else {
103 ($sql, $bind) = $self->next::method(@_);
104 }
105  
106 # SELECT SCOPE_IDENTITY only works within a statement scope. We
107 # must try to always use this particular idiom first, as it is the
108 # only one that guarantees retrieving the correct id under high
109 # concurrency. When this fails we will fall back to whatever secondary
110 # retrieval method is specified in _identity_method, but at this
111 # point we don't have many guarantees we will get what we expected.
112 # http://msdn.microsoft.com/en-us/library/ms190315.aspx
113 # http://davidhayden.com/blog/dave/archive/2006/01/17/2736.aspx
114 if (
115 $self->_perform_autoinc_retrieval
116 and
117 not $self->_no_scope_identity_query
118 and
119 not $suppress_identity_insert
120 ) {
121 $sql .= "\nSELECT SCOPE_IDENTITY()";
122 }
123  
124 return ($sql, $bind);
125 }
126  
127 sub _execute {
128 my $self = shift;
129  
130 # always list ctx - we need the $sth
131 my ($rv, $sth, @bind) = $self->next::method(@_);
132  
133 if ($self->_perform_autoinc_retrieval) {
134  
135 # attempt to bring back the result of SELECT SCOPE_IDENTITY() we tacked
136 # on in _prep_for_execute above
137 my $identity;
138  
139 # we didn't even try on ftds
140 unless ($self->_no_scope_identity_query) {
141 ($identity) = try { $sth->fetchrow_array };
142 $sth->finish;
143 }
144  
145 # SCOPE_IDENTITY failed, but we can do something else
146 if ( (! $identity) && $self->_identity_method) {
147 ($identity) = $self->_dbh->selectrow_array(
148 'select ' . $self->_identity_method
149 );
150 }
151  
152 $self->_identity($identity);
153 }
154  
155 return wantarray ? ($rv, $sth, @bind) : $rv;
156 }
157  
158 sub last_insert_id { shift->_identity }
159  
160  
161 #
162 # MSSQL is retarded wrt ordered subselects. One needs to add a TOP
163 # to *all* subqueries, but one also *can't* use TOP 100 PERCENT
164 # http://sqladvice.com/forums/permalink/18496/22931/ShowThread.aspx#22931
165 #
166 sub _select_args_to_query {
167 #my ($self, $ident, $select, $cond, $attrs) = @_;
168 my $self = shift;
169 my $attrs = $_[3];
170  
171 my $sql_bind = $self->next::method (@_);
172  
173 # see if this is an ordered subquery
174 if (
175 $$sql_bind->[0] !~ /^ \s* \( \s* SELECT \s+ TOP \s+ \d+ \s+ /xi
176 and
177 scalar $self->_extract_order_criteria ($attrs->{order_by})
178 ) {
179 $self->throw_exception(
180 'An ordered subselect encountered - this is not safe! Please see "Ordered Subselects" in DBIO::MSSQL::Storage'
181 ) unless $attrs->{unsafe_subselect_ok};
182  
183 $$sql_bind->[0] =~ s/^ \s* \( \s* SELECT (?=\s) / '(SELECT TOP ' . $self->sql_maker->__max_int /exi;
184 }
185  
186 $sql_bind;
187 }
188  
189  
190 # savepoint syntax is the same as in Sybase ASE
191  
192 sub _exec_svp_begin {
193 my ($self, $name) = @_;
194  
195 $self->_dbh->do("SAVE TRANSACTION $name");
196 }
197  
198 # A new SAVE TRANSACTION with the same name releases the previous one.
199 sub _exec_svp_release { 1 }
200  
201 sub _exec_svp_rollback {
202 my ($self, $name) = @_;
203  
204 $self->_dbh->do("ROLLBACK TRANSACTION $name");
205 }
206  
207 sub sqlt_type { 'SQLServer' }
208  
209  
210 sub _random_function { 'NEWID()' }
211  
212 # TODO: MSSQL needs a SQLMaker with apply_limit that uses RowNumberOver
213 # (>= 2005/v9) or Top (older) based on server version.
214  
215 sub _ping {
216 my $self = shift;
217  
218 my $dbh = $self->_dbh or return 0;
219  
220 local $dbh->{RaiseError} = 1;
221 local $dbh->{PrintError} = 0;
222  
223 return try {
224 $dbh->do('select 1');
225 1;
226 } catch {
227 0;
228 };
229 }
230  
231 sub with_deferred_fk_checks {
232 my ( $self, $sub ) = @_;
233  
234 my $txn_scope_guard = $self->txn_scope_guard;
235  
236 $self->_do_query(
237 'EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL"');
238  
239 my $sg = Scope::Guard->new(
240 sub {
241 $self->_do_query(
242 'EXEC sp_msforeachtable "ALTER TABLE ? CHECK CONSTRAINT ALL"'
243 );
244 } );
245  
246 return preserve_context { $sub->() } after => sub {
247 # explicitly check constraints because MSSQL does not check when
248 # re-enabling them
249 $self->_do_query(
250 'EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL"'
251 );
252 $txn_scope_guard->commit;
253 $sg->dismiss;
254 };
255 }
256  
257  
258  
259 1;
260  
261 __END__
262  
263 =pod
264  
265 =encoding UTF-8
266  
267 =head1 NAME
268  
269 DBIO::MSSQL::Storage - Base Class for Microsoft SQL Server support in DBIO
270  
271 =head1 VERSION
272  
273 version 0.900001
274  
275 =head1 DESCRIPTION
276  
277 Storage driver for Microsoft SQL Server databases. Handles identity column
278 (autoincrement) retrieval via C<SCOPE_IDENTITY()>, proper C<MONEY> column
279 casting on insert/update, ordered subselect safety checks, savepoint support,
280 deferred foreign key checks via C<sp_msforeachtable>, and datetime parsing.
281  
282 The limit dialect (C<RowNumberOver> or C<Top>) is detected automatically from
283 the server version. Uses L<DBIO::MSSQL::SQLMaker> for SQL generation.
284  
285 =head1 METHODS
286  
287 =head2 last_insert_id
288  
289 Returns the last identity value inserted, as retrieved by C<SCOPE_IDENTITY()>
290 or the fallback C<_identity_method>.
291  
292 =head2 sqlt_type
293  
294 Returns C<SQLServer>, identifying this storage to L<SQL::Translator>.
295  
296 =head2 with_deferred_fk_checks
297  
298 $storage->with_deferred_fk_checks(sub { ... });
299  
300 Runs the supplied coderef with all foreign key constraints disabled via
301 C<sp_msforeachtable>. Constraints are re-enabled and explicitly verified
302 afterwards, and the transaction is committed.
303  
304 =head1 SEE ALSO
305  
306 =over
307  
308 =item * L<DBIO::MSSQL> - MSSQL schema component
309  
310 =item * L<DBIO::MSSQL::SQLMaker> - MSSQL SQL dialect
311  
312 =item * L<DBIO::MSSQL::Storage::Sybase> - MSSQL via L<DBD::Sybase>
313  
314 =item * L<DBIO::Storage::DBI> - Base DBI storage class
315  
316 =back
317  
318 =head1 AUTHOR
319  
320 DBIO & DBIx::Class Authors
321  
322 =head1 COPYRIGHT AND LICENSE
323  
324 Copyright (C) 2026 DBIO Authors
325 Portions Copyright (C) 2005-2025 DBIx::Class Authors
326 Based on DBIx::Class, heavily modified.
327  
328 This is free software; you can redistribute it and/or modify it under
329 the same terms as the Perl 5 programming language system itself.
330  
331 =cut
« MSSQL.pm ↑ Summary Shortcut/ms.pm »