File: DB.pm

package info (click to toggle)
rex 1.14.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,012 kB
  • sloc: perl: 35,587; xml: 264; sh: 51; makefile: 13
file content (220 lines) | stat: -rw-r--r-- 4,556 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#
# (c) Jan Gehring <jan.gehring@gmail.com>
#

=head1 NAME

Rex::Commands::DB - Simple Database Access

=head1 DESCRIPTION

This module gives you simple access to a database. Currently I<select>, I<delete>, I<insert> and I<update> is supported.

Version <= 1.0: All these functions will not be reported.

=head1 SYNOPSIS

 use Rex::Commands::DB {
                  dsn    => "DBI:mysql:database=test;host=dbhost",
                  user    => "username",
                  password => "password",
                };
 
 task "list", sub {
   my @data = db select => {
            fields => "*",
            from  => "table",
            where  => "enabled=1",
          };
 
  db insert => "table", {
           field1 => "value1",
            field2 => "value2",
            field3 => 5,
          };
 
  db update => "table", {
              set => {
                field1 => "newvalue",
                field2 => "newvalue2",
              },
              where => "id=5",
           };
 
  db delete => "table", {
            where => "id < 5",
          };
 
 };


=head1 EXPORTED FUNCTIONS

=cut

package Rex::Commands::DB;

use v5.12.5;
use warnings;

our $VERSION = '1.14.1'; # VERSION

BEGIN {
  use Rex::Require;
  DBI->require;
}

use Rex::Logger;
use Data::Dumper;
use Symbol;

use vars qw(@EXPORT $dbh);

@EXPORT = qw(db);

=head2 db

Do a database action.

 my @data = db select => {
          fields => "*",
          from  => "table",
          where  => "host='myhost'",
        };
 
 db insert => "table", {
          field1 => "value1",
          field2 => "value2",
          field3 => 5,
        };
 
 db update => "table", {
            set => {
              field1 => "newvalue",
              field2 => "newvalue2",
            },
            where => "id=5",
         };
 
 db delete => "table", {
          where => "id < 5",
        };

=cut

sub db {

  my ( $type, $table, $data ) = @_;
  if ( ref($table) ) {
    my %d = %{$table};
    delete $d{"from"};
    $data = \%d;

    $table = $table->{"from"};
  }

  unless ($table) {
    Rex::Logger::info("No table defined...')");
    return;
  }

  if ( $type eq "select" ) {
    my $sql = sprintf(
      "SELECT %s FROM %s WHERE %s",
      $data->{"fields"} || "*",
      $table, $data->{"where"} || "1=1"
    );
    if ( defined $data->{"order"} ) {
      $sql .= " ORDER BY " . $data->{"order"};
    }
    Rex::Logger::debug("sql: $sql");

    my $sth = $dbh->prepare($sql);
    $sth->execute or die( $sth->errstr );

    my @return;

    while ( my $row = $sth->fetchrow_hashref ) {
      push @return, $row;
    }
    $sth->finish;

    return @return;
  }
  elsif ( $type eq "insert" ) {
    my $sql = "INSERT INTO %s (%s) VALUES(%s)";

    my @values;
    for my $key ( keys %{$data} ) {
      push( @values, "?" );
    }

    $sql =
      sprintf( $sql, $table, join( ",", keys %{$data} ), join( ",", @values ) );
    Rex::Logger::debug("sql: $sql");

    my $sth = $dbh->prepare($sql);
    my $i   = 1;
    for my $key ( keys %{$data} ) {
      $data->{$key} ||= '';
      Rex::Logger::debug( "sql: binding: " . $data->{$key} );
      $sth->bind_param( $i, $data->{$key} ) or die( $sth->errstr );
      $i++;
    }

    $sth->execute or die( $sth->errstr );
  }
  elsif ( $type eq "update" ) {
    my $sql = "UPDATE %s SET %s WHERE %s";

    my @values;
    for my $key ( keys %{ $data->{"set"} } ) {
      push( @values, "$key = ?" );
    }

    $sql = sprintf( $sql, $table, join( ",", @values ), $data->{"where"} );
    Rex::Logger::debug("sql: $sql");

    my $sth = $dbh->prepare($sql);
    my $i   = 1;
    for my $key ( keys %{ $data->{"set"} } ) {
      Rex::Logger::debug( "sql: binding: " . $data->{"set"}->{$key} );
      $sth->bind_param( $i, $data->{"set"}->{$key} ) or die( $sth->errstr );
      $i++;
    }

    $sth->execute or die( $sth->errstr );
  }
  elsif ( $type eq "delete" ) {
    my $sql = sprintf( "DELETE FROM %s WHERE %s", $table, $data->{"where"} );
    my $sth = $dbh->prepare($sql);
    $sth->execute or die( $sth->errstr );
  }
  else {
    Rex::Logger::info("DB: action $type not supported.");
  }

}

sub import {

  my ( $class, $opt ) = @_;

  if ($opt) {
    $dbh = DBI->connect(
      $opt->{"dsn"},            $opt->{"user"},
      $opt->{"password"} || "", $opt->{"attr"}
    );
    $dbh->{mysql_auto_reconnect} = 1;
  }

  my ( $ns_register_to, $file, $line ) = caller;

  for my $func_name (@EXPORT) {
    my $ref_to_function = qualify_to_ref( $func_name, $ns_register_to );
    *{$ref_to_function} = \&$func_name;
  }

}

1;