| 1 | package Biblio::Zotero::DB::Role::CopyDB; | ||
| 2 | # ABSTRACT: A role to copy the database to a temporary file. | ||
| 3 | $Biblio::Zotero::DB::Role::CopyDB::VERSION = '0.004'; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | use Moo::Role; | ||
| 7 | |||
| 8 | use File::Temp; | ||
| 9 | use File::Copy; | ||
| 10 | use Path::Class; | ||
| 11 | |||
| 12 | has db_file_temp => ( is => 'rw', builder => 1, lazy => 1, clearer => 1); | ||
| 13 | |||
| 14 | sub _build_db_file_temp { | ||
| 15 | return File::Temp->new(); | ||
| 16 | } | ||
| 17 | |||
| 18 | around schema => sub { | ||
| 19 | my $orig = shift; | ||
| 20 | my $self = $_[0]; | ||
| 21 | |||
| 22 | my $orig_db_file = $self->db_file; | ||
| 23 | my $copy_db_file = "@{[$self->db_file_temp]}"; | ||
| 24 | # for L<File::Temp>, this will call ->filename on it | ||
| 25 | |||
| 26 | copy($orig_db_file, $copy_db_file) or die "could not copy $orig_db_file to $copy_db_file"; | ||
| 27 | |||
| 28 | $self->db_file($copy_db_file); # swap the copy in | ||
| 29 | my $ret = $orig->(@_); # get the schema | ||
| 30 | $self->db_file($orig_db_file); # restore the original | ||
| 31 | $ret; | ||
| 32 | }; | ||
| 33 | |||
| 34 | 1; | ||
| 35 | |||
| 36 | __END__ |