]> git.donarmstrong.com Git - debbugs.git/blob - lib/Debbugs/DB/Util.pm
7c52a044eb918916771ec1ac261fbda8d31abc28
[debbugs.git] / lib / Debbugs / DB / Util.pm
1 # This module is part of debbugs, and is released
2 # under the terms of the GPL version 2, or any later version. See the
3 # file README and COPYING for more information.
4 # Copyright 2017 by Don Armstrong <don@donarmstrong.com>.
5
6 package Debbugs::DB::Util;
7
8 =head1 NAME
9
10 Debbugs::DB::Util -- Utility routines for the database
11
12 =head1 SYNOPSIS
13
14
15 =head1 DESCRIPTION
16
17
18 =head1 BUGS
19
20 None known.
21
22 =cut
23
24 use warnings;
25 use strict;
26
27 use base qw(DBIx::Class);
28
29 use Debbugs::Common qw(open_compressed_file);
30
31 =head2 select
32
33 Routines for select requests
34
35 =over
36
37 =item select_one
38
39         $schema->select_one($sql,@bind_vals)
40
41 Returns the first column from the first row returned from a select statement
42
43 =cut
44
45 sub select_one {
46     my ($self,$sql,@bind_vals) = @_;
47     my $results =
48         $self->storage->
49         dbh_do(sub {
50                    my ($s,$dbh) = @_;
51                    my $sth = $dbh->
52         prepare_cached($sql,
53                       {dbi_dummy => __FILE__.__LINE__ })
54         or die "Unable to prepare statement: $sql";
55                    $sth->execute(@bind_vals) or
56                        die "Unable to select one: ".$dbh->errstr();
57                    my $results = $sth->fetchall_arrayref([0]);
58                    $sth->finish();
59                    return $results;
60                });
61     return (ref($results) and ref($results->[0]))?$results->[0][0]:undef;
62 }
63
64 =item prepare_execute
65
66         $schema->prepare_execute($sql,@bind_vals)
67
68 Prepares and executes a statement
69
70 =cut
71
72 sub prepare_execute {
73     my ($self,$sql,@bind_vals) = @_;
74     $self->storage->
75         dbh_do(sub {
76                    my ($s,$dbh) = @_;
77                    my $sth = $dbh->
78                        prepare_cached($sql,
79                       {dbi_dummy => __FILE__.__LINE__ })
80                        or die "Unable to prepare statement: $sql";
81                    $sth->execute(@bind_vals) or
82                        die "Unable to execute statement: ".$dbh->errstr();
83                    $sth->finish();
84                });
85 }
86
87 =item sql_file_in_txn
88
89 C<sql_file_in_txn();>
90
91
92
93 =cut
94 sub sql_file_in_txn {
95     my ($self,$fn) = @_;
96     my $fh = open_compressed_file($fn) or
97         die "Unable to open $fn for reading: $!";
98     local $/;
99     my $sql = <$fh>;
100     defined($sql) or die "Unable to read from file: $!";
101     $self->prepare_execute($sql);
102 }
103
104
105 =back
106
107 =cut
108
109 1;
110
111
112 __END__