1 |
package A3C::SQL; |
2 |
|
3 |
use strict; |
4 |
use warnings; |
5 |
|
6 |
=head1 NAME |
7 |
|
8 |
A3C::SQL |
9 |
|
10 |
=head1 DESCRIPTION |
11 |
|
12 |
Issue SQL queries |
13 |
|
14 |
=head1 METHODS |
15 |
|
16 |
=head2 new |
17 |
|
18 |
my $sql = A3C::SQL->new({ query => 'select now()' }); |
19 |
|
20 |
=cut |
21 |
|
22 |
use base qw(Jifty::Object Class::Accessor::Fast); |
23 |
__PACKAGE__->mk_accessors( qw(query arguments) ); |
24 |
|
25 |
use Data::Dump qw/dump/; |
26 |
|
27 |
=head2 sth |
28 |
|
29 |
Execute query and return statement handle. Ususally you don't have to call this manually. |
30 |
|
31 |
=cut |
32 |
|
33 |
sub sth { |
34 |
my $self = shift; |
35 |
if ( ! $self->{_sth} ) { |
36 |
my $dbh = Jifty->handle->dbh; |
37 |
my $sth = $dbh->prepare( $self->query ) or $dbh->errstr; |
38 |
if ( $self->arguments ) { |
39 |
Jifty->log->debug( $self->sql . ' arguments: ' . dump( $self->arguments ) ); |
40 |
$sth->execute( $self->arguments ) or $dbh->errstr; |
41 |
} else { |
42 |
$sth->execute or $dbh->errstr; |
43 |
} |
44 |
$self->{_sth} = $sth; |
45 |
} |
46 |
|
47 |
return $self->{_sth}; |
48 |
} |
49 |
|
50 |
=head2 next |
51 |
|
52 |
while ( my $row = $sql->next ) { |
53 |
print $row->now; |
54 |
} |
55 |
|
56 |
=cut |
57 |
|
58 |
sub next { |
59 |
my $self = shift; |
60 |
my $row = $self->sth->fetchrow_hashref; |
61 |
return unless defined $row; |
62 |
return A3C::SQL::row->new( $row ); |
63 |
} |
64 |
|
65 |
=head2 count |
66 |
|
67 |
print $sql->count; |
68 |
|
69 |
=cut |
70 |
|
71 |
sub count { |
72 |
my $self = shift; |
73 |
return $self->sth->rows; |
74 |
} |
75 |
|
76 |
package A3C::SQL::row; |
77 |
|
78 |
use Encode qw/decode/; |
79 |
use Data::Dump qw/dump/; |
80 |
|
81 |
our $AUTOLOAD; |
82 |
|
83 |
sub new { |
84 |
my $that = shift; |
85 |
my $class = ref($that) || $that; |
86 |
my $self = shift; |
87 |
bless $self, $class; |
88 |
return $self; |
89 |
} |
90 |
|
91 |
sub AUTOLOAD { |
92 |
my $self = shift; |
93 |
my $type = ref($self) or die "$self is not an object"; |
94 |
my $name = $AUTOLOAD; |
95 |
$name =~ s/.*://; |
96 |
# warn "SQL: $name doesn't exist" unless defined($self->{$name}); |
97 |
return decode('UTF-8', $self->{$name}); |
98 |
} |
99 |
|
100 |
sub DESTROY {} |
101 |
|
102 |
1; |