blib/lib/Oryx/DBI/Util.pm untested

filter: Statementstmt 0.0% 0 / 62 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 100 CC 6 SCAR 16.4
CC
6
Cov
0%
table_create
12.0
_carp
6.0
_croak
6.0
CRAP 5.2
1 package Oryx::DBI::Util;
2 use Carp qw(carp croak);
3  
4 sub _carp {
5 my $class = ref($_[0]) ? ref($_[0]) : $_[0];
6 carp("[$class] $_[1]");
7 }
8  
9 sub _croak {
10 my $class = ref($_[0]) ? ref($_[0]) : $_[0];
11 croak("[$class] $_[1]");
12 }
13  
14 sub new { return bless { }, $_[0] }
15  
16 sub type2sql {
17 my ($self, $type, $size) = @_;
18  
19 # Fetch the SQL type defined in %SQL_TYPES for the current class
20 my $class = ref $self;
21 my $sql_type = ${"${class}::SQL_TYPES"}{$type};
22  
23 # Append a size if given
24 $sql_type .= "($size)" if defined $size;
25  
26 return $sql_type;
27 }
28  
29 sub column_exists {
30 my ($self, $dbh, $table, $column) = @_;
31  
32 # Get the escape char and escape table and column names
33 my $esc = $dbh->get_info( 14 );
34 $table =~ s/([_%])/$esc$1/g;
35 $column =~ s/([_%])/$esc$1/g;
36  
37 # Is there such a column?
38 my $sth = $dbh->column_info('%', '%', $table, $column);
39 $sth->execute();
40 my @rv = @{ $sth->fetchall_arrayref };
41 $sth->finish;
42 return @rv;
43 }
44  
45 sub column_create {
46 my ($self, $dbh, $table, $colname, $coltype) = @_;
47  
48 # Create the column
49 my $sth = $dbh->prepare(<<"SQL");
50 ALTER TABLE $table ADD COLUMN $colname $coltype;
51 SQL
52 $sth->execute;
53 $sth->finish;
54 }
55  
56 # This works in MySQL and PostgreSQL.
57 sub column_drop {
58 my ($self, $dbh, $table, $column) = @_;
59  
60 # Drop the column
61 my $sth = $dbh->prepare(<<"SQL");
62 ALTER TABLE $table DROP COLUMN $column;
63 SQL
64 $sth->execute;
65 $sth->finish;
66 }
67  
68 sub table_exists {
69 my ($self, $dbh, $table) = @_;
70 my $sth = $dbh->table_info('%', '%', $table);
71 my $esc = $dbh->get_info( 14 );
72 $table =~ s/([_%])/$esc$1/g;
73 $sth->execute();
74 my @rv = @{$sth->fetchall_arrayref};
75 $sth->finish;
76 return @rv;
77 }
78
79 sub table_create {
80 my ($self, $dbh, $table, $columns, $types) = @_;
81  
82 my $sql = <<"SQL";
83 CREATE TABLE $table (
84 SQL
85  
86 if (defined $columns and defined $types) {
87 for (my $x = 0; $x < @$columns; $x++) {
88 $sql .= ' '.$columns->[$x].' '.$types->[$x];
89 $sql .= ($x != $#$columns) ? ",\n" : "\n";
90 }
91 }
92  
93 $sql .= <<SQL;
94 );
95 SQL
96  
97 my $sth = $dbh->prepare($sql);
98 $sth->execute;
99 $sth->finish;
100 }
101  
102 sub table_drop {
103 my ($self, $dbh, $table) = @_;
104 my $sql = "DROP TABLE $table";
105 my $sth = $dbh->prepare($sql);
106 $sth->execute();
107 $sth->finish;
108 }
109  
110 sub lastval {
111 my ($self, $dbh, $table) = @_;
112 return $dbh->last_insert_id('%', '%', $table, 'id');
113 }
114  
115 1;
116 __END__