Commit | Line | Data |
8b445e33 |
1 | package DBIx::Class::Storage::DBI; |
e673f011 |
2 | # -*- mode: cperl; cperl-indent-level: 2 -*- |
8b445e33 |
3 | |
a62cf8d4 |
4 | use base 'DBIx::Class::Storage'; |
5 | |
20a2c954 |
6 | use strict; |
7 | use warnings; |
8b445e33 |
8 | use DBI; |
aeaf3ce2 |
9 | use SQL::Abstract::Limit; |
28927b50 |
10 | use DBIx::Class::Storage::DBI::Cursor; |
92b858c9 |
11 | use IO::File; |
4386b954 |
12 | use Storable 'dclone'; |
701da8c4 |
13 | use Carp::Clan qw/DBIx::Class/; |
8b445e33 |
14 | |
bd7efd39 |
15 | BEGIN { |
16 | |
cb5f2eea |
17 | package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :( |
bd7efd39 |
18 | |
19 | use base qw/SQL::Abstract::Limit/; |
20 | |
54540863 |
21 | sub select { |
22 | my ($self, $table, $fields, $where, $order, @rest) = @_; |
6346a152 |
23 | $table = $self->_quote($table) unless ref($table); |
54540863 |
24 | @rest = (-1) unless defined $rest[0]; |
8839560b |
25 | local $self->{having_bind} = []; |
bc0c9800 |
26 | my ($sql, @ret) = $self->SUPER::select( |
27 | $table, $self->_recurse_fields($fields), $where, $order, @rest |
28 | ); |
8839560b |
29 | return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql; |
54540863 |
30 | } |
31 | |
6346a152 |
32 | sub insert { |
33 | my $self = shift; |
34 | my $table = shift; |
35 | $table = $self->_quote($table) unless ref($table); |
36 | $self->SUPER::insert($table, @_); |
37 | } |
38 | |
39 | sub update { |
40 | my $self = shift; |
41 | my $table = shift; |
42 | $table = $self->_quote($table) unless ref($table); |
43 | $self->SUPER::update($table, @_); |
44 | } |
45 | |
46 | sub delete { |
47 | my $self = shift; |
48 | my $table = shift; |
49 | $table = $self->_quote($table) unless ref($table); |
50 | $self->SUPER::delete($table, @_); |
51 | } |
52 | |
54540863 |
53 | sub _emulate_limit { |
54 | my $self = shift; |
55 | if ($_[3] == -1) { |
56 | return $_[1].$self->_order_by($_[2]); |
57 | } else { |
58 | return $self->SUPER::_emulate_limit(@_); |
59 | } |
60 | } |
61 | |
62 | sub _recurse_fields { |
63 | my ($self, $fields) = @_; |
64 | my $ref = ref $fields; |
65 | return $self->_quote($fields) unless $ref; |
66 | return $$fields if $ref eq 'SCALAR'; |
67 | |
68 | if ($ref eq 'ARRAY') { |
69 | return join(', ', map { $self->_recurse_fields($_) } @$fields); |
70 | } elsif ($ref eq 'HASH') { |
71 | foreach my $func (keys %$fields) { |
72 | return $self->_sqlcase($func) |
73 | .'( '.$self->_recurse_fields($fields->{$func}).' )'; |
74 | } |
75 | } |
76 | } |
77 | |
78 | sub _order_by { |
79 | my $self = shift; |
80 | my $ret = ''; |
8839560b |
81 | my @extra; |
54540863 |
82 | if (ref $_[0] eq 'HASH') { |
83 | if (defined $_[0]->{group_by}) { |
84 | $ret = $self->_sqlcase(' group by ') |
85 | .$self->_recurse_fields($_[0]->{group_by}); |
86 | } |
8839560b |
87 | if (defined $_[0]->{having}) { |
88 | my $frag; |
89 | ($frag, @extra) = $self->_recurse_where($_[0]->{having}); |
90 | push(@{$self->{having_bind}}, @extra); |
91 | $ret .= $self->_sqlcase(' having ').$frag; |
92 | } |
54540863 |
93 | if (defined $_[0]->{order_by}) { |
94 | $ret .= $self->SUPER::_order_by($_[0]->{order_by}); |
95 | } |
e535069e |
96 | } elsif(ref $_[0] eq 'SCALAR') { |
97 | $ret = $self->_sqlcase(' order by ').${ $_[0] }; |
54540863 |
98 | } else { |
99 | $ret = $self->SUPER::_order_by(@_); |
100 | } |
101 | return $ret; |
102 | } |
103 | |
f48dd03f |
104 | sub _order_directions { |
105 | my ($self, $order) = @_; |
106 | $order = $order->{order_by} if ref $order eq 'HASH'; |
107 | return $self->SUPER::_order_directions($order); |
108 | } |
109 | |
2a816814 |
110 | sub _table { |
bd7efd39 |
111 | my ($self, $from) = @_; |
112 | if (ref $from eq 'ARRAY') { |
113 | return $self->_recurse_from(@$from); |
114 | } elsif (ref $from eq 'HASH') { |
115 | return $self->_make_as($from); |
116 | } else { |
6346a152 |
117 | return $from; # would love to quote here but _table ends up getting called |
118 | # twice during an ->select without a limit clause due to |
119 | # the way S::A::Limit->select works. should maybe consider |
120 | # bypassing this and doing S::A::select($self, ...) in |
121 | # our select method above. meantime, quoting shims have |
122 | # been added to select/insert/update/delete here |
bd7efd39 |
123 | } |
124 | } |
125 | |
126 | sub _recurse_from { |
127 | my ($self, $from, @join) = @_; |
128 | my @sqlf; |
129 | push(@sqlf, $self->_make_as($from)); |
130 | foreach my $j (@join) { |
131 | my ($to, $on) = @$j; |
73856587 |
132 | |
54540863 |
133 | # check whether a join type exists |
134 | my $join_clause = ''; |
135 | if (ref($to) eq 'HASH' and exists($to->{-join_type})) { |
136 | $join_clause = ' '.uc($to->{-join_type}).' JOIN '; |
137 | } else { |
138 | $join_clause = ' JOIN '; |
139 | } |
73856587 |
140 | push(@sqlf, $join_clause); |
141 | |
bd7efd39 |
142 | if (ref $to eq 'ARRAY') { |
143 | push(@sqlf, '(', $self->_recurse_from(@$to), ')'); |
144 | } else { |
96cdbbab |
145 | push(@sqlf, $self->_make_as($to)); |
bd7efd39 |
146 | } |
147 | push(@sqlf, ' ON ', $self->_join_condition($on)); |
148 | } |
149 | return join('', @sqlf); |
150 | } |
151 | |
152 | sub _make_as { |
153 | my ($self, $from) = @_; |
54540863 |
154 | return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) } |
bc0c9800 |
155 | reverse each %{$self->_skip_options($from)}); |
73856587 |
156 | } |
157 | |
158 | sub _skip_options { |
54540863 |
159 | my ($self, $hash) = @_; |
160 | my $clean_hash = {}; |
161 | $clean_hash->{$_} = $hash->{$_} |
162 | for grep {!/^-/} keys %$hash; |
163 | return $clean_hash; |
bd7efd39 |
164 | } |
165 | |
166 | sub _join_condition { |
167 | my ($self, $cond) = @_; |
5efe4c79 |
168 | if (ref $cond eq 'HASH') { |
169 | my %j; |
bc0c9800 |
170 | for (keys %$cond) { |
171 | my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x; |
172 | }; |
5efe4c79 |
173 | return $self->_recurse_where(\%j); |
174 | } elsif (ref $cond eq 'ARRAY') { |
175 | return join(' OR ', map { $self->_join_condition($_) } @$cond); |
176 | } else { |
177 | die "Can't handle this yet!"; |
178 | } |
bd7efd39 |
179 | } |
180 | |
2a816814 |
181 | sub _quote { |
182 | my ($self, $label) = @_; |
183 | return '' unless defined $label; |
3b24f6ea |
184 | return "*" if $label eq '*'; |
41728a6e |
185 | return $label unless $self->{quote_char}; |
3b24f6ea |
186 | if(ref $self->{quote_char} eq "ARRAY"){ |
187 | return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1] |
188 | if !defined $self->{name_sep}; |
189 | my $sep = $self->{name_sep}; |
190 | return join($self->{name_sep}, |
191 | map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] } |
192 | split(/\Q$sep\E/,$label)); |
193 | } |
2a816814 |
194 | return $self->SUPER::_quote($label); |
195 | } |
196 | |
f66596f9 |
197 | sub _RowNum { |
198 | my $self = shift; |
199 | my $c; |
200 | $_[0] =~ s/SELECT (.*?) FROM/ |
201 | 'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e; |
202 | $self->SUPER::_RowNum(@_); |
203 | } |
204 | |
7be93b07 |
205 | # Accessor for setting limit dialect. This is useful |
206 | # for JDBC-bridge among others where the remote SQL-dialect cannot |
207 | # be determined by the name of the driver alone. |
208 | # |
209 | sub limit_dialect { |
210 | my $self = shift; |
211 | $self->{limit_dialect} = shift if @_; |
212 | return $self->{limit_dialect}; |
213 | } |
214 | |
2437a1e3 |
215 | sub quote_char { |
216 | my $self = shift; |
217 | $self->{quote_char} = shift if @_; |
218 | return $self->{quote_char}; |
219 | } |
220 | |
221 | sub name_sep { |
222 | my $self = shift; |
223 | $self->{name_sep} = shift if @_; |
224 | return $self->{name_sep}; |
225 | } |
226 | |
227 | |
228 | |
229 | |
486ad69b |
230 | package DBIx::Class::Storage::DBI::DebugCallback; |
231 | |
232 | sub print { |
233 | my ($self, $string) = @_; |
234 | $string =~ m/^(\w+)/; |
235 | ${$self}->($1, $string); |
236 | } |
237 | |
bd7efd39 |
238 | } # End of BEGIN block |
239 | |
8b445e33 |
240 | use base qw/DBIx::Class/; |
241 | |
1f692767 |
242 | __PACKAGE__->load_components(qw/AccessorGroup/); |
8b445e33 |
243 | |
223b8fe3 |
244 | __PACKAGE__->mk_group_accessors('simple' => |
1b45b01e |
245 | qw/_connect_info _dbh _sql_maker _conn_pid _conn_tid debug debugfh |
1346e22d |
246 | cursor on_connect_do transaction_depth/); |
8091aa91 |
247 | |
8b445e33 |
248 | sub new { |
223b8fe3 |
249 | my $new = bless({}, ref $_[0] || $_[0]); |
28927b50 |
250 | $new->cursor("DBIx::Class::Storage::DBI::Cursor"); |
d79f59b9 |
251 | $new->transaction_depth(0); |
5e65c358 |
252 | if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) && |
253 | ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) { |
bc0c9800 |
254 | $new->debugfh(IO::File->new($1, 'w')) |
255 | or $new->throw_exception("Cannot open trace file $1"); |
92b858c9 |
256 | } else { |
257 | $new->debugfh(IO::File->new('>&STDERR')); |
258 | } |
28927b50 |
259 | $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}; |
223b8fe3 |
260 | return $new; |
8b445e33 |
261 | } |
262 | |
1c339d71 |
263 | sub throw_exception { |
264 | my ($self, $msg) = @_; |
3b042bcb |
265 | croak($msg); |
1c339d71 |
266 | } |
267 | |
75d07914 |
268 | =head1 NAME |
8b445e33 |
269 | |
270 | DBIx::Class::Storage::DBI - DBI storage handler |
271 | |
272 | =head1 SYNOPSIS |
273 | |
274 | =head1 DESCRIPTION |
275 | |
276 | This class represents the connection to the database |
277 | |
278 | =head1 METHODS |
279 | |
8b445e33 |
280 | =cut |
281 | |
1b45b01e |
282 | =head2 connect_info |
283 | |
284 | Connection information arrayref. Can either be the same arguments |
285 | one would pass to DBI->connect, or a code-reference which returns |
286 | a connected database handle. In either case, there is an optional |
287 | final element in the arrayref, which can hold a hashref of |
288 | connection-specific Storage::DBI options. These include |
289 | C<on_connect_do>, and the sql_maker options C<limit_dialect>, |
290 | C<quote_char>, and C<name_sep>. Examples: |
291 | |
292 | ->connect_info([ 'dbi:SQLite:./foo.db' ]); |
293 | ->connect_info(sub { DBI->connect(...) }); |
294 | ->connect_info([ 'dbi:Pg:dbname=foo', |
295 | 'postgres', |
296 | '', |
297 | { AutoCommit => 0 }, |
298 | { quote_char => q{`}, name_sep => q{@} }, |
299 | ]); |
300 | |
d7c4c15c |
301 | =head2 on_connect_do |
302 | |
303 | Executes the sql statements given as a listref on every db connect. |
304 | |
92b858c9 |
305 | =head2 debug |
306 | |
307 | Causes SQL trace information to be emitted on C<debugfh> filehandle |
308 | (or C<STDERR> if C<debugfh> has not specifically been set). |
309 | |
310 | =head2 debugfh |
311 | |
312 | Sets or retrieves the filehandle used for trace/debug output. This |
313 | should be an IO::Handle compatible object (only the C<print> method is |
314 | used). Initially set to be STDERR - although see information on the |
315 | L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable. |
316 | |
486ad69b |
317 | =head2 debugcb |
318 | |
319 | Sets a callback to be executed each time a statement is run; takes a sub |
320 | reference. Overrides debugfh. Callback is executed as $sub->($op, $info) |
321 | where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally |
322 | be printed. |
323 | |
d7c4c15c |
324 | =cut |
325 | |
486ad69b |
326 | sub debugcb { |
327 | my ($self, $cb) = @_; |
328 | my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback'); |
329 | $self->debugfh($cb_obj); |
330 | } |
331 | |
412db1f4 |
332 | sub disconnect { |
333 | my ($self) = @_; |
334 | |
92925617 |
335 | if( $self->connected ) { |
336 | $self->_dbh->rollback unless $self->_dbh->{AutoCommit}; |
337 | $self->_dbh->disconnect; |
338 | $self->_dbh(undef); |
339 | } |
412db1f4 |
340 | } |
341 | |
342 | sub connected { |
8b445e33 |
343 | my ($self) = @_; |
412db1f4 |
344 | |
1346e22d |
345 | if(my $dbh = $self->_dbh) { |
346 | if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) { |
347 | $self->_sql_maker(undef); |
348 | return $self->_dbh(undef); |
349 | } |
350 | elsif($self->_conn_pid != $$) { |
351 | $self->_dbh->{InactiveDestroy} = 1; |
352 | $self->_sql_maker(undef); |
353 | return $self->_dbh(undef) |
354 | } |
355 | return ($dbh->FETCH('Active') && $dbh->ping); |
356 | } |
357 | |
358 | return 0; |
412db1f4 |
359 | } |
360 | |
361 | sub ensure_connected { |
362 | my ($self) = @_; |
363 | |
364 | unless ($self->connected) { |
8b445e33 |
365 | $self->_populate_dbh; |
366 | } |
412db1f4 |
367 | } |
368 | |
c235bbae |
369 | =head2 dbh |
370 | |
371 | Returns the dbh - a data base handle of class L<DBI>. |
372 | |
373 | =cut |
374 | |
412db1f4 |
375 | sub dbh { |
376 | my ($self) = @_; |
377 | |
378 | $self->ensure_connected; |
8b445e33 |
379 | return $self->_dbh; |
380 | } |
381 | |
48c69e7c |
382 | sub sql_maker { |
383 | my ($self) = @_; |
fdc1c3d0 |
384 | unless ($self->_sql_maker) { |
bd7efd39 |
385 | $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh )); |
48c69e7c |
386 | } |
387 | return $self->_sql_maker; |
388 | } |
389 | |
1b45b01e |
390 | sub connect_info { |
391 | my ($self, $info_arg) = @_; |
392 | |
393 | if($info_arg) { |
394 | my $info = [ @$info_arg ]; # copy because we can alter it |
395 | my $last_info = $info->[-1]; |
396 | if(ref $last_info eq 'HASH') { |
397 | my $used; |
398 | if(my $on_connect_do = $last_info->{on_connect_do}) { |
399 | $used = 1; |
67008979 |
400 | $self->on_connect_do($on_connect_do); |
1b45b01e |
401 | } |
67008979 |
402 | for my $sql_maker_opt (qw/limit_dialect quote_char name_sep/) { |
1b45b01e |
403 | if(my $opt_val = $last_info->{$sql_maker_opt}) { |
404 | $used = 1; |
405 | $self->sql_maker->$sql_maker_opt($opt_val); |
406 | } |
407 | } |
408 | |
409 | # remove our options hashref if it was there, to avoid confusing |
410 | # DBI in the case the user didn't use all 4 DBI options, as in: |
411 | # [ 'dbi:SQLite:foo.db', { quote_char => q{`} } ] |
412 | pop(@$info) if $used; |
413 | } |
414 | |
415 | $self->_connect_info($info); |
416 | } |
417 | |
418 | $self->_connect_info; |
419 | } |
420 | |
8b445e33 |
421 | sub _populate_dbh { |
422 | my ($self) = @_; |
1b45b01e |
423 | my @info = @{$self->_connect_info || []}; |
8b445e33 |
424 | $self->_dbh($self->_connect(@info)); |
8484b01d |
425 | my $dbh = $self->_dbh; |
426 | my $driver = $dbh->{Driver}->{Name}; |
427 | if ( $driver eq 'ODBC' and $dbh->get_info(17) =~ m{^DB2/400} ) { |
428 | $driver = 'ODBC400'; |
429 | } |
34470972 |
430 | eval "require DBIx::Class::Storage::DBI::${driver}"; |
431 | unless ($@) { |
843f8ecd |
432 | bless $self, "DBIx::Class::Storage::DBI::${driver}"; |
433 | } |
d7c4c15c |
434 | # if on-connect sql statements are given execute them |
435 | foreach my $sql_statement (@{$self->on_connect_do || []}) { |
436 | $self->_dbh->do($sql_statement); |
437 | } |
5ef3e508 |
438 | |
1346e22d |
439 | $self->_conn_pid($$); |
440 | $self->_conn_tid(threads->tid) if $INC{'threads.pm'}; |
8b445e33 |
441 | } |
442 | |
443 | sub _connect { |
444 | my ($self, @info) = @_; |
5ef3e508 |
445 | |
9d31f7dc |
446 | $self->throw_exception("You failed to provide any connection info") |
447 | if !@info; |
448 | |
90ec6cad |
449 | my ($old_connect_via, $dbh); |
450 | |
5ef3e508 |
451 | if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) { |
90ec6cad |
452 | $old_connect_via = $DBI::connect_via; |
5ef3e508 |
453 | $DBI::connect_via = 'connect'; |
5ef3e508 |
454 | } |
455 | |
75db246c |
456 | eval { |
457 | if(ref $info[0] eq 'CODE') { |
458 | $dbh = &{$info[0]}; |
459 | } |
460 | else { |
461 | $dbh = DBI->connect(@info); |
462 | } |
463 | }; |
90ec6cad |
464 | |
465 | $DBI::connect_via = $old_connect_via if $old_connect_via; |
466 | |
75db246c |
467 | if (!$dbh || $@) { |
468 | $self->throw_exception("DBI Connection failed: " . ($@ || $DBI::errstr)); |
469 | } |
90ec6cad |
470 | |
e571e823 |
471 | $dbh; |
8b445e33 |
472 | } |
473 | |
8091aa91 |
474 | =head2 txn_begin |
8b445e33 |
475 | |
8091aa91 |
476 | Calls begin_work on the current dbh. |
8b445e33 |
477 | |
181a28f4 |
478 | See L<DBIx::Class::Schema> for the txn_do() method, which allows for |
479 | an entire code block to be executed transactionally. |
480 | |
8b445e33 |
481 | =cut |
482 | |
8091aa91 |
483 | sub txn_begin { |
d79f59b9 |
484 | my $self = shift; |
a32e8402 |
485 | if ($self->{transaction_depth}++ == 0) { |
486 | my $dbh = $self->dbh; |
487 | if ($dbh->{AutoCommit}) { |
488 | $self->debugfh->print("BEGIN WORK\n") |
489 | if ($self->debug); |
490 | $dbh->begin_work; |
491 | } |
986e4fca |
492 | } |
8091aa91 |
493 | } |
8b445e33 |
494 | |
8091aa91 |
495 | =head2 txn_commit |
8b445e33 |
496 | |
8091aa91 |
497 | Issues a commit against the current dbh. |
8b445e33 |
498 | |
8091aa91 |
499 | =cut |
500 | |
501 | sub txn_commit { |
d79f59b9 |
502 | my $self = shift; |
503 | if ($self->{transaction_depth} == 0) { |
a32e8402 |
504 | my $dbh = $self->dbh; |
505 | unless ($dbh->{AutoCommit}) { |
986e4fca |
506 | $self->debugfh->print("COMMIT\n") |
507 | if ($self->debug); |
a32e8402 |
508 | $dbh->commit; |
986e4fca |
509 | } |
8091aa91 |
510 | } |
511 | else { |
986e4fca |
512 | if (--$self->{transaction_depth} == 0) { |
513 | $self->debugfh->print("COMMIT\n") |
514 | if ($self->debug); |
515 | $self->dbh->commit; |
516 | } |
8091aa91 |
517 | } |
518 | } |
519 | |
520 | =head2 txn_rollback |
521 | |
181a28f4 |
522 | Issues a rollback against the current dbh. A nested rollback will |
523 | throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception, |
524 | which allows the rollback to propagate to the outermost transaction. |
8b445e33 |
525 | |
526 | =cut |
527 | |
8091aa91 |
528 | sub txn_rollback { |
d79f59b9 |
529 | my $self = shift; |
a62cf8d4 |
530 | |
531 | eval { |
532 | if ($self->{transaction_depth} == 0) { |
a32e8402 |
533 | my $dbh = $self->dbh; |
534 | unless ($dbh->{AutoCommit}) { |
986e4fca |
535 | $self->debugfh->print("ROLLBACK\n") |
536 | if ($self->debug); |
a32e8402 |
537 | $dbh->rollback; |
986e4fca |
538 | } |
a62cf8d4 |
539 | } |
540 | else { |
986e4fca |
541 | if (--$self->{transaction_depth} == 0) { |
542 | $self->debugfh->print("ROLLBACK\n") |
543 | if ($self->debug); |
544 | $self->dbh->rollback; |
545 | } |
546 | else { |
1346e22d |
547 | die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new; |
986e4fca |
548 | } |
a62cf8d4 |
549 | } |
550 | }; |
551 | |
552 | if ($@) { |
553 | my $error = $@; |
554 | my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION"; |
555 | $error =~ /$exception_class/ and $self->throw_exception($error); |
556 | $self->{transaction_depth} = 0; # ensure that a failed rollback |
557 | $self->throw_exception($error); # resets the transaction depth |
8091aa91 |
558 | } |
559 | } |
8b445e33 |
560 | |
223b8fe3 |
561 | sub _execute { |
562 | my ($self, $op, $extra_bind, $ident, @args) = @_; |
563 | my ($sql, @bind) = $self->sql_maker->$op($ident, @args); |
944f30bf |
564 | unshift(@bind, @$extra_bind) if $extra_bind; |
f59ffc79 |
565 | if ($self->debug) { |
e673f011 |
566 | my @debug_bind = map { defined $_ ? qq{'$_'} : q{'NULL'} } @bind; |
181a28f4 |
567 | $self->debugfh->print("$sql: " . join(', ', @debug_bind) . "\n"); |
f59ffc79 |
568 | } |
75db246c |
569 | my $sth = eval { $self->sth($sql,$op) }; |
570 | |
571 | if (!$sth || $@) { |
572 | $self->throw_exception('no sth generated via sql (' . ($@ || $self->_dbh->errstr) . "): $sql"); |
573 | } |
574 | |
438adc0e |
575 | @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args |
701da8c4 |
576 | my $rv; |
75d07914 |
577 | if ($sth) { |
95dad7e2 |
578 | $rv = eval { $sth->execute(@bind) }; |
579 | |
580 | if ($@ || !$rv) { |
581 | $self->throw_exception("Error executing '$sql': ".($@ || $sth->errstr)); |
582 | } |
75d07914 |
583 | } else { |
1c339d71 |
584 | $self->throw_exception("'$sql' did not generate a statement."); |
701da8c4 |
585 | } |
223b8fe3 |
586 | return (wantarray ? ($rv, $sth, @bind) : $rv); |
587 | } |
588 | |
8b445e33 |
589 | sub insert { |
590 | my ($self, $ident, $to_insert) = @_; |
bc0c9800 |
591 | $self->throw_exception( |
592 | "Couldn't insert ".join(', ', |
593 | map "$_ => $to_insert->{$_}", keys %$to_insert |
594 | )." into ${ident}" |
595 | ) unless ($self->_execute('insert' => [], $ident, $to_insert)); |
8b445e33 |
596 | return $to_insert; |
597 | } |
598 | |
599 | sub update { |
223b8fe3 |
600 | return shift->_execute('update' => [], @_); |
8b445e33 |
601 | } |
602 | |
603 | sub delete { |
223b8fe3 |
604 | return shift->_execute('delete' => [], @_); |
8b445e33 |
605 | } |
606 | |
de705b51 |
607 | sub _select { |
8b445e33 |
608 | my ($self, $ident, $select, $condition, $attrs) = @_; |
223b8fe3 |
609 | my $order = $attrs->{order_by}; |
610 | if (ref $condition eq 'SCALAR') { |
611 | $order = $1 if $$condition =~ s/ORDER BY (.*)$//i; |
612 | } |
8839560b |
613 | if (exists $attrs->{group_by} || $attrs->{having}) { |
bc0c9800 |
614 | $order = { |
615 | group_by => $attrs->{group_by}, |
616 | having => $attrs->{having}, |
617 | ($order ? (order_by => $order) : ()) |
618 | }; |
54540863 |
619 | } |
5c91499f |
620 | my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order); |
9229f20a |
621 | if ($attrs->{software_limit} || |
622 | $self->sql_maker->_default_limit_syntax eq "GenericSubQ") { |
623 | $attrs->{software_limit} = 1; |
5c91499f |
624 | } else { |
625 | push @args, $attrs->{rows}, $attrs->{offset}; |
626 | } |
de705b51 |
627 | return $self->_execute(@args); |
628 | } |
629 | |
630 | sub select { |
631 | my $self = shift; |
632 | my ($ident, $select, $condition, $attrs) = @_; |
cb5f2eea |
633 | return $self->cursor->new($self, \@_, $attrs); |
8b445e33 |
634 | } |
635 | |
6157db4f |
636 | # Need to call finish() to work round broken DBDs |
637 | |
1a14aa3f |
638 | sub select_single { |
de705b51 |
639 | my $self = shift; |
640 | my ($rv, $sth, @bind) = $self->_select(@_); |
6157db4f |
641 | my @row = $sth->fetchrow_array; |
642 | $sth->finish(); |
643 | return @row; |
1a14aa3f |
644 | } |
645 | |
8b445e33 |
646 | sub sth { |
cb5f2eea |
647 | my ($self, $sql) = @_; |
91fa659e |
648 | # 3 is the if_active parameter which avoids active sth re-use |
649 | return $self->dbh->prepare_cached($sql, {}, 3); |
8b445e33 |
650 | } |
651 | |
a953d8d9 |
652 | =head2 columns_info_for |
653 | |
654 | Returns database type info for a given table columns. |
655 | |
656 | =cut |
657 | |
658 | sub columns_info_for { |
0d67fe74 |
659 | my ($self, $table) = @_; |
bfe10d87 |
660 | |
a32e8402 |
661 | my $dbh = $self->dbh; |
662 | |
663 | if ($dbh->can('column_info')) { |
a953d8d9 |
664 | my %result; |
a32e8402 |
665 | my $old_raise_err = $dbh->{RaiseError}; |
666 | my $old_print_err = $dbh->{PrintError}; |
667 | $dbh->{RaiseError} = 1; |
668 | $dbh->{PrintError} = 0; |
0d67fe74 |
669 | eval { |
4d272ce5 |
670 | my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table); |
671 | my $sth = $dbh->column_info( undef,$schema, $tab, '%' ); |
0d67fe74 |
672 | $sth->execute(); |
673 | while ( my $info = $sth->fetchrow_hashref() ){ |
bfe10d87 |
674 | my %column_info; |
0d67fe74 |
675 | $column_info{data_type} = $info->{TYPE_NAME}; |
676 | $column_info{size} = $info->{COLUMN_SIZE}; |
677 | $column_info{is_nullable} = $info->{NULLABLE} ? 1 : 0; |
678 | $column_info{default_value} = $info->{COLUMN_DEF}; |
679 | |
680 | $result{$info->{COLUMN_NAME}} = \%column_info; |
681 | } |
682 | }; |
a32e8402 |
683 | $dbh->{RaiseError} = $old_raise_err; |
684 | $dbh->{PrintError} = $old_print_err; |
0d67fe74 |
685 | return \%result if !$@; |
686 | } |
687 | |
688 | my %result; |
a32e8402 |
689 | my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0"); |
0d67fe74 |
690 | $sth->execute; |
691 | my @columns = @{$sth->{NAME_lc}}; |
692 | for my $i ( 0 .. $#columns ){ |
693 | my %column_info; |
694 | my $type_num = $sth->{TYPE}->[$i]; |
695 | my $type_name; |
a32e8402 |
696 | if(defined $type_num && $dbh->can('type_info')) { |
697 | my $type_info = $dbh->type_info($type_num); |
0d67fe74 |
698 | $type_name = $type_info->{TYPE_NAME} if $type_info; |
a953d8d9 |
699 | } |
0d67fe74 |
700 | $column_info{data_type} = $type_name ? $type_name : $type_num; |
701 | $column_info{size} = $sth->{PRECISION}->[$i]; |
702 | $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0; |
703 | |
704 | if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) { |
705 | $column_info{data_type} = $1; |
706 | $column_info{size} = $2; |
707 | } |
708 | |
709 | $result{$columns[$i]} = \%column_info; |
710 | } |
bfe10d87 |
711 | |
0d67fe74 |
712 | return \%result; |
a953d8d9 |
713 | } |
714 | |
843f8ecd |
715 | sub last_insert_id { |
716 | my ($self, $row) = @_; |
717 | |
718 | return $self->dbh->func('last_insert_rowid'); |
719 | |
720 | } |
721 | |
90ec6cad |
722 | sub sqlt_type { shift->dbh->{Driver}->{Name} } |
1c339d71 |
723 | |
e673f011 |
724 | sub create_ddl_dir |
725 | { |
4386b954 |
726 | my ($self, $schema, $databases, $version, $dir, $preversion, $sqltargs) = @_; |
e673f011 |
727 | |
728 | if(!$dir || !-d $dir) |
729 | { |
730 | warn "No directory given, using ./\n"; |
731 | $dir = "./"; |
732 | } |
733 | $databases ||= ['MySQL', 'SQLite', 'PostgreSQL']; |
734 | $databases = [ $databases ] if(ref($databases) ne 'ARRAY'); |
735 | $version ||= $schema->VERSION || '1.x'; |
736 | |
1c339d71 |
737 | eval "use SQL::Translator"; |
738 | $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@; |
e673f011 |
739 | |
740 | my $sqlt = SQL::Translator->new({ |
741 | # debug => 1, |
742 | add_drop_table => 1, |
743 | }); |
744 | foreach my $db (@$databases) |
745 | { |
746 | $sqlt->reset(); |
747 | $sqlt->parser('SQL::Translator::Parser::DBIx::Class'); |
748 | # $sqlt->parser_args({'DBIx::Class' => $schema); |
749 | $sqlt->data($schema); |
750 | $sqlt->producer($db); |
751 | |
752 | my $file; |
4386b954 |
753 | my $filename = $schema->ddl_filename($dir, $db, $version); |
e673f011 |
754 | if(-e $filename) |
755 | { |
4386b954 |
756 | warn("$filename already exists, skipping $db"); |
e673f011 |
757 | next; |
758 | } |
759 | open($file, ">$filename") |
4386b954 |
760 | or warn("Can't open $filename for writing ($!)"), next; |
e673f011 |
761 | my $output = $sqlt->translate; |
e673f011 |
762 | if(!$output) |
763 | { |
4386b954 |
764 | warn("Failed to translate to $db, skipping. (" . $sqlt->error . ")"); |
e673f011 |
765 | next; |
766 | } |
767 | print $file $output; |
768 | close($file); |
4386b954 |
769 | |
770 | if($preversion) |
771 | { |
772 | eval "use SQL::Translator::Diff"; |
773 | warn("Can't diff versions without SQL::Translator::Diff: $@"), next if $@; |
774 | |
775 | my $prefilename = $schema->ddl_filename($dir, $db, $preversion); |
776 | print "Previous version $prefilename\n"; |
777 | if(!-e $prefilename) |
778 | { |
779 | warn("No previous schema file found ($prefilename)"); |
780 | next; |
781 | } |
782 | #### We need to reparse the SQLite file we just wrote, so that |
783 | ## Diff doesnt get all confoosed, and Diff is *very* confused. |
784 | ## FIXME: rip Diff to pieces! |
785 | # my $target_schema = $sqlt->schema; |
786 | # unless ( $target_schema->name ) { |
787 | # $target_schema->name( $filename ); |
788 | # } |
789 | my $sqlt = SQL::Translator->new(); |
790 | $sqlt->parser("SQL::Translator::Parser::$db"); |
791 | $sqlt->filename($filename); |
792 | $sqlt->translate() or warn("Failed to parse $filename as $db, (" . |
793 | $sqlt->error . ")"), next; |
794 | my $target_schema = $sqlt->schema; |
795 | unless ( $target_schema->name ) { |
796 | $target_schema->name( $filename ); |
797 | } |
798 | ## end FIXME |
799 | |
800 | my $psqlt = SQL::Translator->new(); |
801 | $psqlt->parser("SQL::Translator::Parser::$db"); |
802 | $psqlt->filename($prefilename); |
803 | $psqlt->translate() or warn("Failed to parse $filename as $db, (" . |
804 | $sqlt->error . ")"), next ; |
805 | my $source_schema = $psqlt->schema; |
806 | unless ( $source_schema->name ) { |
807 | $source_schema->name( $prefilename ); |
808 | } |
809 | |
810 | my $diff = SQL::Translator::Diff::schema_diff($source_schema, $db, |
811 | $target_schema, $db, |
812 | {} |
813 | ); |
200427a4 |
814 | my $difffile = $schema->ddl_filename($dir, $db, $version, $preversion); |
4386b954 |
815 | if(-e $difffile) |
816 | { |
817 | warn("$difffile already exists, skipping"); |
818 | next; |
819 | } |
820 | open $file, ">$difffile" or |
821 | warn("Can't write to $difffile ($!)"), next; |
822 | print $file $diff; |
823 | close($file); |
824 | } |
e673f011 |
825 | } |
826 | |
827 | } |
828 | |
829 | sub deployment_statements { |
830 | my ($self, $schema, $type, $version, $dir, $sqltargs) = @_; |
831 | $type ||= $self->sqlt_type; |
832 | $version ||= $schema->VERSION || '1.x'; |
833 | $dir ||= './'; |
0382d607 |
834 | eval "use SQL::Translator"; |
835 | if(!$@) |
836 | { |
837 | eval "use SQL::Translator::Parser::DBIx::Class;"; |
838 | $self->throw_exception($@) if $@; |
839 | eval "use SQL::Translator::Producer::${type};"; |
840 | $self->throw_exception($@) if $@; |
841 | my $tr = SQL::Translator->new(%$sqltargs); |
842 | SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema ); |
843 | return "SQL::Translator::Producer::${type}"->can('produce')->($tr); |
844 | } |
e673f011 |
845 | |
4386b954 |
846 | my $filename = $schema->ddl_filename($dir, $type, $version); |
e673f011 |
847 | if(!-f $filename) |
848 | { |
0382d607 |
849 | # $schema->create_ddl_dir([ $type ], $version, $dir, $sqltargs); |
850 | $self->throw_exception("No SQL::Translator, and no Schema file found, aborting deploy"); |
851 | return; |
e673f011 |
852 | } |
853 | my $file; |
854 | open($file, "<$filename") |
855 | or $self->throw_exception("Can't open $filename ($!)"); |
856 | my @rows = <$file>; |
857 | close($file); |
858 | |
859 | return join('', @rows); |
860 | |
1c339d71 |
861 | } |
843f8ecd |
862 | |
1c339d71 |
863 | sub deploy { |
cb561d1a |
864 | my ($self, $schema, $type, $sqltargs) = @_; |
e673f011 |
865 | foreach my $statement ( $self->deployment_statements($schema, $type, undef, undef, $sqltargs) ) { |
e4fe9ba3 |
866 | for ( split(";\n", $statement)) { |
e673f011 |
867 | next if($_ =~ /^--/); |
868 | next if(!$_); |
869 | # next if($_ =~ /^DROP/m); |
870 | next if($_ =~ /^BEGIN TRANSACTION/m); |
871 | next if($_ =~ /^COMMIT/m); |
e4fe9ba3 |
872 | $self->debugfh->print("$_\n") if $self->debug; |
873 | $self->dbh->do($_) or warn "SQL was:\n $_"; |
874 | } |
75d07914 |
875 | } |
1c339d71 |
876 | } |
843f8ecd |
877 | |
200427a4 |
878 | sub backup |
879 | { |
880 | my ($self) = @_; |
881 | |
882 | ## Does nothing, override in DBI::XX classes |
883 | } |
884 | |
92925617 |
885 | sub DESTROY { shift->disconnect } |
886 | |
8b445e33 |
887 | 1; |
888 | |
92b858c9 |
889 | =head1 ENVIRONMENT VARIABLES |
890 | |
891 | =head2 DBIX_CLASS_STORAGE_DBI_DEBUG |
892 | |
893 | If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information |
894 | is produced (as when the L<debug> method is set). |
895 | |
896 | If the value is of the form C<1=/path/name> then the trace output is |
897 | written to the file C</path/name>. |
898 | |
8b445e33 |
899 | =head1 AUTHORS |
900 | |
daec44b8 |
901 | Matt S. Trout <mst@shadowcatsystems.co.uk> |
8b445e33 |
902 | |
9f19b1d6 |
903 | Andy Grundman <andy@hybridized.org> |
904 | |
4386b954 |
905 | Jess Robinson <castaway@desert-island.demon.co.uk> |
906 | |
8b445e33 |
907 | =head1 LICENSE |
908 | |
909 | You may distribute this code under the same terms as Perl itself. |
910 | |
911 | =cut |
912 | |