From 1c5e0c47c92128afebef5614407d84cd72c12b35 Mon Sep 17 00:00:00 2001 From: Byron Jones Date: Wed, 28 Nov 2012 16:40:21 +0800 Subject: Bug 814411: Add a caching mechanism to Bugzilla::Object to avoid querying the database repeatedly for the same information --- Bugzilla/Object.pm | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) (limited to 'Bugzilla/Object.pm') diff --git a/Bugzilla/Object.pm b/Bugzilla/Object.pm index 8089c6ccc..96651d191 100644 --- a/Bugzilla/Object.pm +++ b/Bugzilla/Object.pm @@ -72,6 +72,8 @@ sub new { sub _init { my $class = shift; my ($param) = @_; + my $object = $class->_cache_get($param); + return $object if $object; my $dbh = Bugzilla->dbh; my $columns = join(',', $class->_get_db_columns); my $table = $class->DB_TABLE; @@ -82,7 +84,6 @@ sub _init { if (ref $param eq 'HASH') { $id = $param->{id}; } - my $object; if (defined $id) { # We special-case if somebody specifies an ID, so that we can @@ -125,9 +126,48 @@ sub _init { "SELECT $columns FROM $table WHERE $condition", undef, @values); } + $class->_cache_set($param, $object) if $object; return $object; } +# Provides a mechanism for objects to be cached in the request_cahce + +sub _cache_get { + my $class = shift; + my ($param) = @_; + my $cache_key = $class->cache_key($param) + || return; + return Bugzilla->request_cache->{$cache_key}; +} + +sub _cache_set { + my $class = shift; + my ($param, $object) = @_; + my $cache_key = $class->cache_key($param) + || return; + Bugzilla->request_cache->{$cache_key} = $object; +} + +sub _cache_remove { + my $class = shift; + my ($param, $object) = @_; + $param->{cache} = 1; + my $cache_key = $class->cache_key($param) + || return; + delete Bugzilla->request_cache->{$cache_key}; +} + +sub cache_key { + my $class = shift; + my ($param) = @_; + if (ref($param) && $param->{cache} && ($param->{id} || $param->{name})) { + $class = blessed($class) if blessed($class); + return $class . ',' . ($param->{id} || $param->{name}); + } else { + return; + } +} + sub check { my ($invocant, $param) = @_; my $class = ref($invocant) || $invocant; @@ -406,6 +446,7 @@ sub update { $self->audit_log(\%changes) if $self->AUDIT_UPDATES; $dbh->bz_commit_transaction(); + $self->_cache_remove({ id => $self->id }); if (wantarray) { return (\%changes, $old_self); @@ -424,6 +465,7 @@ sub remove_from_db { $self->audit_log(AUDIT_REMOVE) if $self->AUDIT_REMOVES; $dbh->do("DELETE FROM $table WHERE $id_field = ?", undef, $self->id); $dbh->bz_commit_transaction(); + $self->_cache_remove({ id => $self->id }); undef $self; } -- cgit v1.2.3-24-g4f1b