/[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 162 - (show annotations)
Sun Jun 15 17:47:39 2008 UTC (15 years, 9 months ago) by dpavlin
File size: 2170 byte(s)
added encoding to A3C::SQL so we can connect to databases which doesn't
have default UTF-8 encoding (like strix doesn't)
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 encoding) );
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 encoding => 'UTF-8',
32 });
33
34 =head2 sth
35
36 Execute query and return statement handle. Ususally you don't have to call this manually.
37
38 =cut
39
40 sub sth {
41 my $self = shift;
42 if ( ! $self->{_sth} ) {
43 my $dbh = $self->dbh || Jifty->handle->dbh;
44 my $sth = $dbh->prepare( $self->query ) or $dbh->errstr;
45 if ( $self->arguments ) {
46 Jifty->log->debug( $self->sql . ' arguments: ' . dump( $self->arguments ) );
47 $sth->execute( $self->arguments ) or die $dbh->errstr;
48 } else {
49 $sth->execute or die $dbh->errstr;
50 }
51 $self->{_sth} = $sth;
52 }
53
54 return $self->{_sth};
55 }
56
57 =head2 next
58
59 while ( my $row = $sql->next ) {
60 print $row->now;
61 }
62
63 =cut
64
65 sub next {
66 my $self = shift;
67 my $row = $self->sth->fetchrow_hashref;
68 return unless defined $row;
69 return A3C::SQL::row->new( $row, $self->encoding );
70 }
71
72 =head2 count
73
74 print $sql->count;
75
76 =cut
77
78 sub count {
79 my $self = shift;
80 return $self->sth->rows;
81 }
82
83 =head1 HELPERS
84
85 This helpers are accessor to L<DBI>
86
87 =head2 _column_names
88
89 my @columns = $sql->_column_names;
90
91 =cut
92
93 sub _column_names {
94 my $self = shift;
95 return @{ $self->sth->{NAME} };
96 }
97
98 package A3C::SQL::row;
99
100 use Encode qw/decode/;
101 use Data::Dump qw/dump/;
102 use base qw/Jifty::Object/;
103
104 our $AUTOLOAD;
105
106 sub new {
107 my $that = shift;
108 my $class = ref($that) || $that;
109 my $self = shift;
110 bless $self, $class;
111 $self->{__encoding} = shift || 'UTF-8';
112 return $self;
113 }
114
115 sub AUTOLOAD {
116 my $self = shift;
117 my $type = ref($self) or die "$self is not an object";
118 my $name = $AUTOLOAD;
119 $name =~ s/.*://;
120 Jifty->log->error("SQL: $name doesn't exist") unless defined($self->{$name});
121 return decode( $self->{__encoding}, $self->{$name} );
122 }
123
124 sub DESTROY {}
125
126 1;

  ViewVC Help
Powered by ViewVC 1.1.26