/[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 159 - (show annotations)
Sun Jun 15 14:40:50 2008 UTC (15 years, 10 months ago) by dpavlin
File size: 2059 byte(s)
added _column_names accessor to A3C::SQL
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 =head1 HELPERS
83
84 This helpers are accessor to L<DBI>
85
86 =head2 _column_names
87
88 my @columns = $sql->_column_names;
89
90 =cut
91
92 sub _column_names {
93 my $self = shift;
94 return @{ $self->sth->{NAME} };
95 }
96
97 package A3C::SQL::row;
98
99 use Encode qw/decode/;
100 use Data::Dump qw/dump/;
101 use base qw/Jifty::Object/;
102
103 our $AUTOLOAD;
104
105 sub new {
106 my $that = shift;
107 my $class = ref($that) || $that;
108 my $self = shift;
109 bless $self, $class;
110 return $self;
111 }
112
113 sub AUTOLOAD {
114 my $self = shift;
115 my $type = ref($self) or die "$self is not an object";
116 my $name = $AUTOLOAD;
117 $name =~ s/.*://;
118 Jifty->log->error("SQL: $name doesn't exist") unless defined($self->{$name});
119 return decode('UTF-8', $self->{$name});
120 }
121
122 sub DESTROY {}
123
124 1;

  ViewVC Help
Powered by ViewVC 1.1.26