diff options
Diffstat (limited to 'lib/TUWF')
-rw-r--r-- | lib/TUWF/DB.pm | 21 | ||||
-rw-r--r-- | lib/TUWF/DB.pod | 15 |
2 files changed, 26 insertions, 10 deletions
diff --git a/lib/TUWF/DB.pm b/lib/TUWF/DB.pm index 14bfb17..aae8e41 100644 --- a/lib/TUWF/DB.pm +++ b/lib/TUWF/DB.pm @@ -10,7 +10,7 @@ use Time::HiRes 'time'; our $VERSION = '1.1'; our @EXPORT = qw| dbInit dbh dbCheck dbDisconnect dbCommit dbRollBack - dbExec dbRow dbAll dbPage + dbExec dbVal dbRow dbAll dbPage |; our @EXPORT_OK = ('sqlprint'); @@ -89,15 +89,21 @@ sub dbExec { } +# ..return the first column of the first row +sub dbVal { + return sqlhelper(shift, 1, @_); +} + + # ..return the first row as an hashref sub dbRow { - return sqlhelper(shift, 1, @_); + return sqlhelper(shift, 2, @_); } # ..return all rows as an arrayref of hashrefs sub dbAll { - return sqlhelper(shift, 2, @_); + return sqlhelper(shift, 3, @_); } @@ -130,8 +136,9 @@ sub sqlhelper { # type, query, @list my $ret = eval { $q = $self->dbh->prepare($q[0]); $q->execute($#q ? @q[1..$#q] : ()); - $r = $type == 1 ? $q->fetchrow_hashref : - $type == 2 ? $q->fetchall_arrayref({}) : + $r = $type == 1 ? ($q->fetchrow_array)[0] : + $type == 2 ? $q->fetchrow_hashref : + $type == 3 ? $q->fetchall_arrayref({}) : $q->rows; 1; }; @@ -140,8 +147,8 @@ sub sqlhelper { # type, query, @list croak($self->dbh->errstr || $@) if !$ret; $r = 0 if $type == 0 && (!$r || $r == 0); - $r = {} if $type == 1 && (!$r || ref($r) ne 'HASH'); - $r = [] if $type == 2 && (!$r || ref($r) ne 'ARRAY'); + $r = {} if $type == 2 && (!$r || ref($r) ne 'HASH'); + $r = [] if $type == 3 && (!$r || ref($r) ne 'ARRAY'); return $r; } diff --git a/lib/TUWF/DB.pod b/lib/TUWF/DB.pod index 0c6bde5..5982654 100644 --- a/lib/TUWF/DB.pod +++ b/lib/TUWF/DB.pod @@ -99,6 +99,17 @@ Example of an "UPDATE or INSERT" query: Of course, the use of the extended formatting in the above example is not very practical. Their advantage is more apparent when the queries get more dynamic. +=head2 dbVal(query, @params) + +Accepts the same arguments as C<dbExec()>, and returns the first value of the +first row. + +Examples: + + my $count = tuwf->dbVal('SELECT COUNT(*) FROM users'); + + my $exists = tuwf->dbVal('SELECT 1 FROM users WHERE id = ?', $id); + =head2 dbRow(query, @params) Accepts the same arguments as C<dbExec()>, and returns the first row of the @@ -106,9 +117,7 @@ result as a hashref. The return value is equivalent to C<$sth-E<gt>fetchrow_hashref()>, except C<dbRow()> returns an empty hash if the query did not return any rows. -Examples: - - my $count = tuwf->dbRow('SELECT COUNT(*) AS num FROM users')->{num}; +Example: my %latest_announcement = %{ tuwf->dbRow(q{ SELECT title, message, post_date |