/[A3C]/lib/A3C/SQL.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Contents of /lib/A3C/SQL.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.26