| 1 | package Hash::Storage::Driver::Files; | ||
| 2 | |||
| 3 | our $VERSION = '0.02'; | ||
| 4 | |||
| 5 | 1 | ▶ | use v5.10; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 7 | 1 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | |||
| 9 | 1 | ▶ | use File::Slurp; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 10 | 1 | ▶ | use Carp qw/croak/; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 11 | 1 | ▶ | use Digest::MD5 qw/md5_hex/; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 12 | |||
| 13 | 1 | ▶ | use base "Hash::Storage::Driver::Base"; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 14 | |||
| 15 | sub new { | ||
| 16 | my ($class, %args) = @_; | ||
| 17 | |||
| 18 | my $self = $class->SUPER::new(%args); | ||
| 19 | croak "WRONG DIR [$self->{dir}]" unless -d $self->{dir}; | ||
| 20 | return $self; | ||
| 21 | } | ||
| 22 | |||
| 23 | sub init { | ||
| 24 | my ($self) = @_; | ||
| 25 | |||
| 26 | } | ||
| 27 | |||
| 28 | sub get { | ||
| 29 | my ( $self, $id ) = @_; | ||
| 30 | |||
| 31 | my $file = $self->_file_by_id($id); | ||
| 32 | return unless -e $file; | ||
| 33 | |||
| 34 | my $serialized = read_file($file); | ||
| 35 | return $self->{serializer}->deserialize($serialized); | ||
| 36 | } | ||
| 37 | |||
| 38 | sub set { | ||
| 39 | my ( $self, $id, $fields ) = @_; | ||
| 40 | |||
| 41 | $self->do_exclusively( sub { | ||
| 42 | my $data = $self->get($id) || {}; | ||
| 43 | @{$data}{ keys %$fields } = values %$fields; | ||
| 44 | |||
| 45 | my $serialized = $self->{serializer}->serialize($data); | ||
| 46 | write_file( $self->_file_by_id($id), { atomic => 1 }, $serialized ); | ||
| 47 | } ); | ||
| 48 | } | ||
| 49 | |||
| 50 | sub del { | ||
| 51 | my ( $self, $id ) = @_; | ||
| 52 | $self->do_exclusively( sub { | ||
| 53 | unlink( $self->_file_by_id($id) ); | ||
| 54 | }); | ||
| 55 | } | ||
| 56 | |||
| 57 | sub list { | ||
| 58 | my ( $self, @query ) = @_; | ||
| 59 | my $dir = $self->{dir}; | ||
| 60 | my @hashes; | ||
| 61 | |||
| 62 | opendir( my $dh , $dir ) or die "Cannot open dir [$dir]"; | ||
| 63 | while ( my $file = readdir($dh) ){ | ||
| 64 | next if $file !~ /^[a-f0-9]+\.hst$/; | ||
| 65 | |||
| 66 | my $serialized = read_file("$dir/$file"); | ||
| 67 | push @hashes, $self->{serializer}->deserialize($serialized); | ||
| 68 | } | ||
| 69 | |||
| 70 | return $self->do_filtering(\@hashes, \@query); | ||
| 71 | } | ||
| 72 | |||
| 73 | sub count { | ||
| 74 | my ( $self, $filter ) = @_; | ||
| 75 | my $hashes = $self->list(where => $filter); | ||
| 76 | return scalar(@$hashes); | ||
| 77 | } | ||
| 78 | |||
| 79 | sub _file_by_id { | ||
| 80 | my ( $self, $id ) = @_; | ||
| 81 | return $self->{dir} . '/' . md5_hex($id) . '.hst'; | ||
| 82 | } | ||
| 83 | |||
| 84 | 1; | ||