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