Archive.pm

filter: Statementstmt 85.7% 72 / 84 Branchbran 45.8% 11 / 24 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 88.2% 15 / 17 Podpod 0.0% 0 / 6 totaltotal 74.8% 98 / 131 CC 15 SCAR 16.6
CC
15
Cov
77%
new
12.6
build_db
7.1
create_db
3.2
CRAP 5.3
↑ Summary Temp.pm »
1 package SQLite::Archive;
2  
3 =pod
4  
5 =head1 NAME
6  
7 SQLite::Archive - Version-agnostic storage and manipulation of SQLite databases
8  
9 =head1 DESCRIPTION
10  
11 SQLite (and the Perl module for it L<DBD::SQLite>) is an extremely handy
12 database for storing various types of simple information.
13  
14 However, as SQLite has developed, the binary structure of the SQLite
15 database format itself has changed and evolved, and continues to change
16 and evolve. As new releases come out, new versions of L<DBD::SQLite> are
17 also released with matching code.
18  
19 This makes SQLite database files suboptimal (at best) for use in
20 distributing data sets between disparate systems.
21  
22 At the same time, a giant raw .sql script says very little about the
23 data itself (such as which database and version it is intended for),
24 requires a client front end to throw the SQL script at, and it not
25 easily editable or manipulatable while dumped.
26  
27 B<SQLite::Archive> provides a straight forward mechanism for exporting
28 (and importing) SQLite databases, and moving that data around as a
29 single file to (or from) other hosts.
30  
31 It uses a regular tar archive, with the data stored in CSV files, and
32 the table structure stored in a create.sql file.
33  
34 Given a SQLite archive file (B<SQLite::Archive> will take anything
35 supported by L<Archive::Extract>) it will extract the tarball to a
36 temporary directory, create a SQLite database (in a location of your
37 choice or also in a temp directory) and then populate the SQLite
38 database with the data from the archive.
39  
40 =head1 METHODS
41  
42 =cut
43  
44 2 ▶use 5.005;
Subroutine BEGIN: called CC=1 SCAR=0.0
45 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
46 2 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
47 2 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
48 2 ▶use File::Temp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
49 2 ▶use Archive::Extract ();
Subroutine BEGIN: called CC=1 SCAR=0.0
50 2 ▶use SQL::Script ();
Subroutine BEGIN: called CC=1 SCAR=0.0
51 2 ▶use Parse::CSV ();
Subroutine BEGIN: called CC=1 SCAR=0.0
52 2 ▶use DBI ();
Subroutine BEGIN: called CC=1 SCAR=0.0
53  
54 2 ▶use vars qw{$VERSION};
Subroutine BEGIN: called CC=1 SCAR=0.0
55 2 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
56 2 $VERSION = '0.02';
57 }
58  
59  
60  
61  
62  
63 #####################################################################
64 # Constructor and Accessors
65  
66 =pod
67  
68 =head1 new
69  
70 SQLite::Archive->new( file => 'data.tar.gz' );
71 SQLite::Archive->new( file => 'data.zip' );
72 SQLite::Archive->new( dir => 'extracted' );
73  
74 The C<new> constructor creates a new SQLite archive object.
75  
76 It takes a data source as either a C<file> param (which should be
77 an L<Archive::Extract>-compatible archive, or a C<dir> param (which
78 should contain the equivalent of the content of the archive, but
79 already expanded as single files).
80  
81 Returns a new B<SQLite::Archive> object, or throws an exception
82 on error.
83  
84 =cut
85  
86 1 ▶sub new {
Subroutine new: called CC=7 SCAR=25.3
Pod undocumented
87 1 my $class = shift;
88 1 my $self = bless { @_ }, $class;
89  
90 # Check the archive directory
91 1 ▶ unless ( defined $self->dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->dir) 0 1 1
92 # Check the archive file
93 0 ▶ unless ( -f $self->file ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $self->file) 0 0 0
94 0 croak("The file '" . $self->file . "' does not exist");
95 }
96  
97 # Extract the archive
98 0 my $archive = Archive::Extract->new( archive => $self->file );
99 0 my $tempdir = File::Temp::tempdir( CLEANUP => 1 );
100 0 ▶ $archive->extract( to => $tempdir ) or die $archive->error;
Branch: 1 branch
BranchTrueFalseTotal
$archive->extract("to", $tempdir) or die $archive->error 0 0 0
101 0 $self->{dir} = $archive->extract_path;
102 }
103 1 ▶ unless ( -d $self->dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $self->dir) 0 1 1
104 0 croak("The directory '" . $self->dir . "' does not exist");
105 }
106  
107 # Locate all data files
108 1 ▶ opendir( ARCHIVE, $self->dir ) or die "opendir: $!";
Branch: 1 branch
BranchTrueFalseTotal
opendir ARCHIVE, $self->dir or die "opendir: $!" 1 0 1
109 1 my @files = sort readdir( ARCHIVE );
110 1 ▶ closedir( ARCHIVE ) or die "closedir: $!";
Branch: 1 branch
BranchTrueFalseTotal
closedir ARCHIVE or die "closedir: $!" 1 0 1
111 1 $self->{sql} = [ grep { /^\w+\.sql/ } @files ];
112 1 $self->{csv} = [ grep { /^\w+\.csv/ } @files ];
113  
114 1 return $self;
115 }
116  
117 0 ▶sub uri {
Subroutine uri: not called CC=1 SCAR=6.9
Pod undocumented
118 0 $_[0]->{uri};
119 }
120  
121 0 ▶sub file {
Subroutine file: not called CC=1 SCAR=6.9
Pod undocumented
122 0 $_[0]->{file};
123 }
124  
125 4 ▶sub dir {
Subroutine dir: called CC=1 SCAR=0.0
Pod undocumented
126 4 $_[0]->{dir};
127 }
128  
129  
130  
131  
132  
133 #####################################################################
134 # Main Methods
135  
136 =pod
137  
138 =head1 create_db
139  
140 $dbh = $archive->create_db; # Temp file created
141 $dbh = $archive->create_db( 'dir/sqlite.db' );
142  
143 The C<create_db> method create a new (empty) SQLite database.
144  
145 It optionally takes a single param of a path at which it should
146 create the SQLite file.
147  
148 If created as a temp file, the database file will be destroyed
149 until END-time (as opposed to being destroyed when the DBI
150 connection handle goes out of scope).
151  
152 Returns a L<DBI> connection (as a B<DBI::db> object) or throws
153 an exception on error.
154  
155 =cut
156  
157 1 ▶sub create_db {
Subroutine create_db: called CC=3 SCAR=11.7
Pod undocumented
158 1 my $self = shift;
159 1 my $file = undef;
160 1 ▶ if ( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 0 1 1
161 # Explicit file name
162 0 die "CODE INCOMPLETE";
163 } else {
164 # Get a temp file name
165 1 my $dir = File::Temp::tempdir( CLEANUP => 1 );
166 1 $file = File::Spec->catfile( $dir, 'sqlite.db' );
167 }
168  
169 # Create the database
170 1 my $db = DBI->connect( 'dbi:SQLite:' . $file );
171 1 ▶ unless ( $db ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($db) 0 1 1
172 0 croak("Failed to create test DB handle");
173 }
174  
175 1 return $db;
176 }
177  
178 =pod
179  
180 =head1 build_db
181  
182 $dbh = $archive->build_db; # Temp file created
183 $dbh = $archive->build_db( 'dir/sqlite.db' );
184  
185 The C<build_db> method provides the main functionality for SQLite::Archive.
186  
187 It creates a new SQLite database (at a temporary file if needed), executes
188 any SQL scripts, populates tables from any CSV files, and returns a DBI
189 handle.
190  
191 Returns a BDI::db object, or throws an exception on error.
192  
193 =cut
194  
195 1 ▶sub build_db {
Subroutine build_db: called CC=7 SCAR=19.6
Pod undocumented
196 1 my $self = shift;
197 1 my $dbh = $self->create_db(@_);
198  
199 # Execute any SQL files first, in order
200 1 my $dir = $self->dir;
201 1 foreach my $sql ( @{$self->{sql}} ) {
202 1 my $file = File::Spec->catfile( $dir, $sql );
203  
204 # Load the script
205 1 my $script = SQL::Script->new;
206 1 $script->read( $file );
207  
208 # Execute the script
209 1 $script->run( $dbh );
210 }
211  
212 # Now parse and insert any CSV data
213 1 foreach my $csv ( @{$self->{csv}} ) {
214 1 my $file = File::Spec->catfile( $dir, $csv );
215  
216 # Create the parser for the file
217 1 ▶ my $parser = Parse::CSV->new(
Branch: 1 branch
BranchTrueFalseTotal
my $parser = "Parse::CSV"->new("file", $file, "fields", "auto") or die "Failed to create CSV::Parser for $csv" 1 0 1
218 file => $file,
219 fields => 'auto',
220 ) or die "Failed to create CSV::Parser for $csv";
221 1 my (undef, undef, $table) = File::Spec->splitpath($file);
222 1 ▶ $table =~ s/\.csv$// or die "Failed to find table name";
Branch: 1 branch
BranchTrueFalseTotal
$table =~ s/\.csv$// or die "Failed to find table name" 1 0 1
223  
224 # Process the inserts
225 # Don't bother chunking for now, just auto-commit.
226 1 ▶ while ( my $row = $parser->fetch ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $parser->fetch) 2 1 3
227 my $sql = "INSERT INTO $table ( "
228 . join( ', ', keys %$row )
229 . " ) values ( "
230 2 . join( ', ', map { '?' } values %$row )
231 . " )";
232 2 ▶ $dbh->do( $sql, {}, values %$row ) and next;
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do($sql, {}, values %$row) and next 2 0 2
233 0 die "Table insert failed in $csv: $DBI::errstr";
234 }
235 }
236  
237 1 return $dbh;
238 }
239  
240 2 1;
241  
242 __END__
↑ Summary Temp.pm »