Permalink
Browse files

Add caching layer to transform()

Supports both package cache and instance cache.

Signed-off-by: Pedro Melo <melo@simplicidade.org>
  • Loading branch information...
1 parent f946969 commit 453203330353d33a7fe044319a624be662391d2e @melo committed Jun 4, 2012
Showing with 41 additions and 7 deletions.
  1. +19 −4 lib/DBIx/Nesting.pm
  2. +22 −3 t/20-transform.t
View
@@ -8,11 +8,26 @@ use strict;
use warnings;
use Eval::Closure ();
-sub transform {
- my ($self, $meta, $in) = @_;
+sub new { bless {}, shift }
- my $cb = $self->compile($meta);
- return $cb->($in);
+{
+ my %cache;
+
+ sub transform {
+ my ($self, $meta, $in, $key) = @_;
+
+ my $cb;
+ if ($key) {
+ my $cache = \%cache;
+ $cache = $self->{cache} ||= {} if ref($self);
+ $cb = $cache->{$key} ||= $self->compile($meta);
+ }
+ else {
+ $cb = $self->compile($meta);
+ }
+
+ return $cb->($in);
+ }
}
sub compile {
View
@@ -12,9 +12,28 @@ use DateTime::Format::MySQL;
my $n = 'DBIx::Nesting';
my $tc = read_all_test_cases(\*DATA);
-my $u = sub { $n->transform(@_) }; ## shortcut
+my $s = DBIx::Nesting->new;
+my $ic = sub { $s->transform(@_) };
+my $gc = sub { $n->transform(@_) };
+
for my $t (@{ $tc->{all} }) {
- cmp_deeply($u->($t->{meta}{data}, $t->{in}{data}), $t->{out}{data}, $t->{msg}{desc});
+ my $in = $t->{in}{data};
+ my $out = $t->{out}{data};
+ my $desc = $t->{msg}{desc};
+ my $meta = $t->{meta}{data};
+
+ ## normal run
+ cmp_deeply($gc->($meta, $in), $out, "Doing $desc");
+
+ ## caching run - global cache
+ cmp_deeply($gc->($meta, $in, $desc), $out, "... first run, init cache for $desc");
+ cmp_deeply($gc->($meta, $in, $desc), $out, "...... second run from cache for $desc");
+ cmp_deeply($gc->($meta, $in, $desc), $out, "...... third run from cache for $desc");
+
+ ## caching run - per-instance cache
+ cmp_deeply($ic->($meta, $in, $desc), $out, "... first run, init cache for $desc");
+ cmp_deeply($ic->($meta, $in, $desc), $out, "...... second run from cache for $desc");
+ cmp_deeply($ic->($meta, $in, $desc), $out, "...... third run from cache for $desc");
}
@@ -56,7 +75,7 @@ __DATA__
> end
-> msg simple case, single table, with a primary key definition
+> msg simple case, single table, with a primary key definition, with into level
>+ meta
{ prefix => 'p1', into => 't' }

0 comments on commit 4532033

Please sign in to comment.