View | Details | Raw Unified | Return to bug 36350
Collapse All | Expand All

(-)a/Koha/Acquisition/Currencies.pm (-3 / +3 lines)
Lines 21-27 use Koha::Database; Link Here
21
21
22
use Koha::Acquisition::Currency;
22
use Koha::Acquisition::Currency;
23
23
24
use base qw(Koha::Objects);
24
use base qw(Koha::Objects::Cached);
25
25
26
=head1 NAME
26
=head1 NAME
27
27
Lines 38-45 Koha::Acquisition::Currencies - Koha Acquisition Currency Object set class Link Here
38
=cut
38
=cut
39
39
40
sub get_active {
40
sub get_active {
41
    my ($self) = @_;
41
    my ( $self ) = @_;
42
    return $self->SUPER::search( { active => 1 } )->next;
42
    return $self->search( { active => 1 } )->next;
43
}
43
}
44
44
45
=head3 _type
45
=head3 _type
(-)a/Koha/Acquisition/Currency.pm (-1 / +1 lines)
Lines 19-25 use Modern::Perl; Link Here
19
19
20
use Koha::Database;
20
use Koha::Database;
21
21
22
use base qw(Koha::Object);
22
use base qw(Koha::Object::CachedExpiration);
23
23
24
=head1 NAME
24
=head1 NAME
25
25
(-)a/Koha/ILL/Requests.pm (-1 / +1 lines)
Lines 23-29 use Koha::Database; Link Here
23
use Koha::ILL::Request;
23
use Koha::ILL::Request;
24
use Koha::ILL::Request::Config;
24
use Koha::ILL::Request::Config;
25
25
26
use base qw(Koha::Objects::Mixin::ExtendedAttributes Koha::Objects);
26
use base qw(Koha::Objects);
27
27
28
=head1 NAME
28
=head1 NAME
29
29
(-)a/Koha/ItemType.pm (-1 / +1 lines)
Lines 24-30 use Koha::Database; Link Here
24
use Koha::CirculationRules;
24
use Koha::CirculationRules;
25
use Koha::Localizations;
25
use Koha::Localizations;
26
26
27
use base qw(Koha::Object Koha::Object::Limit::Library);
27
use base qw(Koha::Object::CachedExpiration Koha::Object::Limit::Library);
28
28
29
my $cache = Koha::Caches->get_instance();
29
my $cache = Koha::Caches->get_instance();
30
30
(-)a/Koha/ItemTypes.pm (-1 / +1 lines)
Lines 22-28 use C4::Languages; Link Here
22
use Koha::Database;
22
use Koha::Database;
23
use Koha::ItemType;
23
use Koha::ItemType;
24
24
25
use base qw(Koha::Objects Koha::Objects::Limit::Library);
25
use base qw(Koha::Objects::Cached Koha::Objects::Limit::Library);
26
26
27
=head1 NAME
27
=head1 NAME
28
28
(-)a/Koha/Libraries.pm (-1 / +1 lines)
Lines 28-34 use Koha::Items; Link Here
28
use Koha::Library;
28
use Koha::Library;
29
use Koha::Patrons;
29
use Koha::Patrons;
30
30
31
use base qw(Koha::Objects::Mixin::AdditionalFields Koha::Objects);
31
use base qw(Koha::Objects::Mixin::AdditionalFields Koha::Objects::Cached);
32
32
33
=head1 NAME
33
=head1 NAME
34
34
(-)a/Koha/Library.pm (-1 / +1 lines)
Lines 28-34 use Koha::StockRotationStages; Link Here
28
use Koha::SMTP::Servers;
28
use Koha::SMTP::Servers;
29
use Koha::Library::Hours;
29
use Koha::Library::Hours;
30
30
31
use base qw(Koha::Object::Mixin::AdditionalFields Koha::Object);
31
use base qw(Koha::Object::Mixin::AdditionalFields Koha::Object::CachedExpiration);
32
32
33
my $cache = Koha::Caches->get_instance();
33
my $cache = Koha::Caches->get_instance();
34
34
(-)a/Koha/Object.pm (+3 lines)
Lines 1017-1022 sub AUTOLOAD { Link Here
1017
        my $accessor = sub {
1017
        my $accessor = sub {
1018
            my $self = shift;
1018
            my $self = shift;
1019
            if (@_) {
1019
            if (@_) {
1020
                if ($self->isa("Koha::Object::CachedExpiration")) {
1021
                    $self->_objects_cache_expire();
1022
                }
1020
                $self->_result()->set_column( $method, @_ );
1023
                $self->_result()->set_column( $method, @_ );
1021
                return $self;
1024
                return $self;
1022
            } else {
1025
            } else {
(-)a/Koha/Object/CachedExpiration.pm (+68 lines)
Line 0 Link Here
1
package Koha::Object::CachedExpiration;
2
3
use parent qw( Koha::Object Koha::Objects::Cached::Base );
4
use Modern::Perl;
5
use Data::Dumper;
6
7
=head1 NAME
8
9
Koha::Object::CachedExpiration
10
11
=head1 SYNOPSIS
12
13
    package Koha::Foo;
14
15
    use parent qw( Koha::Object::CachedExpiration );
16
17
=head1 API
18
19
=head2 Class Methods
20
21
=cut
22
23
=head3 delete
24
25
Overloaded I<delete> method for cache expiration
26
27
=cut
28
29
sub delete {
30
    my ($self) = @_;
31
    $self->_objects_cache_expire();
32
    $self->SUPER::delete();
33
}
34
35
=head3 store
36
37
Overloaded I<store> method for cache expiration
38
39
=cut
40
41
sub store {
42
    my ($self) = @_;
43
    $self->_objects_cache_expire();
44
    $self->SUPER::store();
45
}
46
47
=head2 Internal methods
48
49
=head3 _objects_cache_expire
50
51
=cut
52
53
sub _objects_cache_expire {
54
    my ($self) = @_;
55
    if ($self->_result->in_storage) {
56
        my @primary_keys = $self->_result->id;
57
        my $ids_cache_key = $self->_objects_cache_cache_key('find', @primary_keys);
58
        $self->_objects_cache_clear($ids_cache_key);
59
    }
60
}
61
62
=head1 AUTHOR
63
64
David Gustafsson <david.gustafsson@ub.gu.se>
65
66
=cut
67
68
1;
(-)a/Koha/Objects.pm (-1 / +193 lines)
Lines 22-31 use Modern::Perl; Link Here
22
use Carp            qw( carp );
22
use Carp            qw( carp );
23
use List::MoreUtils qw( none );
23
use List::MoreUtils qw( none );
24
use Class::Inspector;
24
use Class::Inspector;
25
use Scalar::Util qw( reftype );
25
26
26
use Koha::Database;
27
use Koha::Database;
27
use Koha::Exceptions::Object;
28
use Koha::Exceptions::Object;
28
29
30
29
=head1 NAME
31
=head1 NAME
30
32
31
Koha::Objects - Koha Object set base class
33
Koha::Objects - Koha Object set base class
Lines 135-146 based on the query I<$params> and I<$attributes> that are passed (like in DBIC). Link Here
135
sub search {
137
sub search {
136
    my ( $self, $params, $attributes ) = @_;
138
    my ( $self, $params, $attributes ) = @_;
137
139
140
    $self->handle_query_extended_attributes(
141
        {
142
            attributes      => $attributes,
143
            filtered_params => $params,
144
        }
145
    ) if defined $attributes;
146
147
    my $rs = $self->_resultset()->search( $params, $attributes );
138
    my $class = ref($self) ? ref($self) : $self;
148
    my $class = ref($self) ? ref($self) : $self;
139
    my $rs    = $self->_resultset()->search( $params, $attributes );
140
149
141
    return $class->_new_from_dbic($rs);
150
    return $class->_new_from_dbic($rs);
142
}
151
}
143
152
153
=head3 handle_query_extended_attributes
154
155
    Checks for the presence of extended_attributes in a query
156
    If present, it builds the dynamic extended attributes relations and rewrites the query to include the extended_attributes relation
157
158
=cut
159
160
sub handle_query_extended_attributes {
161
    my ( $self, $args ) = @_;
162
163
    my $attributes      = $args->{attributes};
164
    my $filtered_params = $args->{filtered_params};
165
166
    if (   reftype( $attributes->{prefetch} )
167
        && reftype( $attributes->{prefetch} ) eq 'ARRAY'
168
        && grep ( /extended_attributes/, @{ $attributes->{prefetch} } ) )
169
    {
170
171
        my @array = $self->_get_extended_attributes_entries($filtered_params);
172
173
        # Calling our private method to build the extended attributes relations
174
        my @joins = $self->_build_extended_attributes_relations( \@array );
175
        push @{ $attributes->{join} }, @joins;
176
177
    }
178
}
179
180
=head3 _get_extended_attributes_entries
181
182
    $self->_get_extended_attributes_entries( $filtered_params, 0 )
183
184
Recursive function that returns the rewritten extended_attributes query entries.
185
186
Given:
187
[
188
    '-and',
189
    [
190
        {
191
            'extended_attributes.code'      => 'CODE_1',
192
            'extended_attributes.attribute' => { 'like' => '%Bar%' }
193
        },
194
        {
195
            'extended_attributes.attribute' => { 'like' => '%Bar%' },
196
            'extended_attributes.code'      => 'CODE_2'
197
        }
198
    ]
199
];
200
201
Returns :
202
203
[
204
    'CODE_1',
205
    'CODE_2'
206
]
207
208
=cut
209
210
sub _get_extended_attributes_entries {
211
    my ( $self, $params, @array ) = @_;
212
213
    if ( reftype($params) && reftype($params) eq 'HASH' ) {
214
215
        # rewrite additional_field_values table query params
216
        @array = _rewrite_related_metadata_query( $params, 'field_id', 'value', @array )
217
            if $params->{'extended_attributes.field_id'};
218
219
        # rewrite borrower_attributes table query params
220
        @array = _rewrite_related_metadata_query( $params, 'code', 'attribute', @array )
221
            if $params->{'extended_attributes.code'};
222
223
        # rewrite illrequestattributes table query params
224
        @array = _rewrite_related_metadata_query( $params, 'type', 'value', @array )
225
            if $params->{'extended_attributes.type'};
226
227
        foreach my $key ( keys %{$params} ) {
228
            return $self->_get_extended_attributes_entries( $params->{$key}, @array );
229
        }
230
    } elsif ( reftype($params) && reftype($params) eq 'ARRAY' ) {
231
        foreach my $ea_instance (@$params) {
232
            @array = $self->_get_extended_attributes_entries( $ea_instance, @array );
233
        }
234
        return @array;
235
    } else {
236
        return @array;
237
    }
238
}
239
240
=head3 _rewrite_related_metadata_query
241
242
        $extended_attributes_entries =
243
            _rewrite_related_metadata_query( $params, 'field_id', 'value', @array )
244
245
Helper function that rewrites all subsequent extended_attributes queries to match the alias generated by the dbic self left join
246
Take the below example (patrons):
247
        [
248
            {
249
                "extended_attributes.attribute":{"like":"%123%"},
250
                "extended_attributes.code":"CODE_1"
251
            }
252
        ],
253
        [
254
            {
255
                "extended_attributes.attribute":{"like":"%abc%" },
256
                "extended_attributes.code":"CODE_2"
257
            }
258
        ]
259
260
It'll be rewritten as:
261
        [
262
            {
263
                'extended_attributes_CODE_1.attribute' => { 'like' => '%123%' },
264
                'extended_attributes_CODE_1.code' => 'CODE_1'
265
            }
266
        ],
267
            [
268
            {
269
                'extended_attributes_CODE_2.attribute' => { 'like' => '%abc%' },
270
                'extended_attributes_CODE_2.code' => 'CODE_2'
271
            }
272
        ]
273
274
=cut
275
276
sub _rewrite_related_metadata_query {
277
    my ( $params, $key, $value, @array ) = @_;
278
279
    if ( ref \$params->{ 'extended_attributes.' . $key } eq 'SCALAR' ) {
280
        my $old_key_value = delete $params->{ 'extended_attributes.' . $key };
281
        my $new_key_value = "extended_attributes_$old_key_value" . "." . $key;
282
        $params->{$new_key_value} = $old_key_value;
283
284
        my $old_value_value = delete $params->{ 'extended_attributes.' . $value };
285
        my $new_value_value = "extended_attributes_$old_key_value" . "." . $value;
286
        $params->{$new_value_value} = $old_value_value;
287
        push @array, $old_key_value;
288
    }
289
290
    return @array;
291
}
292
293
=head3 _build_extended_attributes_relations
294
295
    Method to dynamically add has_many relations for Koha classes that support extended_attributes.
296
297
    Returns a list of relation accessor names.
298
299
=cut
300
301
sub _build_extended_attributes_relations {
302
    my ( $self, $types ) = @_;
303
304
    return if ( !grep ( /extended_attributes/, keys %{ $self->_resultset->result_source->_relationships } ) );
305
306
    my $ea_config = $self->extended_attributes_config;
307
308
    my $result_source = $self->_resultset->result_source;
309
    for my $type ( @{$types} ) {
310
        $result_source->add_relationship(
311
            "extended_attributes_$type",
312
            "$ea_config->{schema_class}",
313
            sub {
314
                my $args = shift;
315
316
                return {
317
                    "$args->{foreign_alias}.$ea_config->{id_field}->{foreign}" =>
318
                        { -ident => "$args->{self_alias}.$ea_config->{id_field}->{self}" },
319
                    "$args->{foreign_alias}.$ea_config->{key_field}" => { '=', $type },
320
                };
321
            },
322
            {
323
                accessor       => 'multi',
324
                join_type      => 'LEFT',
325
                cascade_copy   => 0,
326
                cascade_delete => 0,
327
                is_depends_on  => 0
328
            },
329
        );
330
331
    }
332
    return map { 'extended_attributes_' . $_ } @{$types};
333
}
334
335
144
=head3 search_related
336
=head3 search_related
145
337
146
    my $objects = Koha::Objects->search_related( $rel_name, $cond?, \%attrs? );
338
    my $objects = Koha::Objects->search_related( $rel_name, $cond?, \%attrs? );
(-)a/Koha/Objects/Cached.pm (+91 lines)
Line 0 Link Here
1
package Koha::Objects::Cached;
2
3
use parent qw( Koha::Objects Koha::Objects::Cached::Base );
4
use Modern::Perl;
5
6
=head1 NAME
7
8
Koha::Object::Cached
9
10
=head1 SYNOPSIS
11
12
    package Koha::Foo;
13
14
    use parent qw( Koha:Objects::Cached );
15
16
=head1 API
17
18
=head2 Class Methods
19
20
=cut
21
22
=head3 find
23
24
Overloaded I<find> method that provides in memory caching by arguments.
25
26
=cut
27
28
sub find {
29
    my ($class, @args) = @_;
30
    my $cache_key = $class->_objects_cache_cache_key('find', @args);
31
    # Store in the args bucket if has column value condiditions
32
    # or for some reason the attributes argument is provided
33
    my $has_options = @args > 1 && ref $args[$#args] eq 'HASH';
34
    my $cache = !($has_options && defined $args[$#args]->{cache} && !$args[$#args]->{cache});
35
    my $cache_bucket = ref $args[0] eq 'HASH' || $has_options ? 'args' : 'ids';
36
    my $object;
37
    if ($cache) {
38
        $object = $class->_objects_cache_get($cache_key, $cache_bucket);
39
    }
40
    if (!defined $object) {
41
        $object = $class->SUPER::find(@args);
42
        $object //= 'undef';
43
        $class->_objects_cache_set($cache_key, $object, $cache_bucket) if $cache;
44
    }
45
    elsif ($object ne 'undef' && defined $object->{'_cache'}) {
46
        # Clear object cache if set
47
        delete $object->{'_cache'};
48
    }
49
    return $object eq 'undef' ? undef : $object;
50
}
51
52
=head3 search
53
54
Overloaded I<search> method that provides in memory caching by arguments.
55
56
=cut
57
58
sub search {
59
    my ($class, $cond, $attrs) = @_;
60
    my $has_resultset = ref($class) && $class->{_resultset};
61
    $attrs //= {};
62
    $attrs->{cache} //= 1 unless $has_resultset;
63
64
    if ($has_resultset || !$attrs->{cache}) {
65
        return $class->SUPER::search($cond, $attrs);
66
    }
67
    else {
68
        my @args;
69
        push(@args , $cond) if defined $cond;
70
        # Don't include if only contains "cache" key
71
        push(@args, $attrs) unless keys %{$attrs} == 1 && defined $attrs->{cache};
72
        my $cache_key = $class->_objects_cache_cache_key('search', @args);
73
        my $objects = $class->_objects_cache_get($cache_key, 'args');
74
        if ($objects) {
75
            $objects->reset;
76
        }
77
        else {
78
            $objects = $class->SUPER::search($cond, $attrs);
79
            $class->_objects_cache_set($cache_key, $objects, 'args');
80
        }
81
        return $objects;
82
    }
83
}
84
85
=head1 AUTHOR
86
87
David Gustafsson <david.gustafsson@ub.gu.se>
88
89
=cut
90
91
1;
(-)a/Koha/Objects/Cached/Base.pm (+120 lines)
Line 0 Link Here
1
package Koha::Objects::Cached::Base;
2
3
use Modern::Perl;
4
use Digest::MD5 qw( md5_hex );
5
use Carp qw( croak );
6
use JSON;
7
use Data::Dumper;
8
9
use Koha::Cache::Memory::Lite;
10
11
=head1 NAME
12
13
Koha::Objects::Cached::Base
14
15
=head2 Internal methods
16
17
=head3 _objects_cache_cache_key
18
19
=cut
20
21
sub _objects_cache_cache_key {
22
    my ($self, @args) = @_;
23
    if (@args == 2 && !ref $args[1]) {
24
        return join(':', @args);
25
    }
26
    # JSON is much faster than Data::Dumper but throws
27
    # an exception for certain perl data strucures
28
    # (non boolean scalar refs for example which can
29
    # be used in DBIx conditions)
30
    my $cache_key = eval { md5_hex(JSON->new->canonical(1)->encode(\@args)) };
31
    if ($cache_key) {
32
        return $cache_key;
33
    } else {
34
        local $Data::Dumper::Sortkeys = 1;
35
        return md5_hex(Dumper(\@args));
36
    }
37
}
38
39
=head3 _objects_cache_bucket_key
40
41
=cut
42
43
sub _objects_cache_bucket_key {
44
    my ($self, $bucket) = @_;
45
    my %buckets = (
46
        'ids' => 'ObjectsCachedIds',
47
        'args' => 'ObjectsCachedArgs'
48
    );
49
    unless (exists $buckets{$bucket}) {
50
        croak "Invalid cache bucket $bucket";
51
    }
52
    return $self->_type . $buckets{$bucket};
53
54
55
}
56
57
=head3 _objects_cache_bucket
58
59
=cut
60
61
sub _objects_cache_bucket {
62
    my ($self, $bucket) = @_;
63
    my $memory_cache = Koha::Cache::Memory::Lite->get_instance();
64
    my $bucket_key = $self->_objects_cache_bucket_key($bucket);
65
    my $cache = $memory_cache->get_from_cache($bucket_key);
66
    unless ($cache) {
67
        $cache = {};
68
        $memory_cache->set_in_cache($bucket_key, $cache);
69
    }
70
    return $cache;
71
}
72
73
=head3 _objects_cache_get
74
75
=cut
76
77
sub _objects_cache_get {
78
    my ($self, $cache_key, $bucket) = @_;
79
    my $cache = $self->_objects_cache_bucket($bucket);
80
    return exists $cache->{$cache_key} ? $cache->{$cache_key} : undef;
81
}
82
83
=head3 _objects_cache_set
84
85
=cut
86
87
sub _objects_cache_set {
88
    my ($self, $cache_key, $object, $bucket) = @_;
89
    my $cache = $self->_objects_cache_bucket($bucket);
90
    $cache->{$cache_key} = $object;
91
}
92
93
=head3 _objects_cache_clear
94
95
=cut
96
97
sub _objects_cache_clear {
98
    my ($self, $ids_cache_key) = @_;
99
    my $memory_cache = Koha::Cache::Memory::Lite->get_instance();
100
    if ($ids_cache_key) {
101
        my $cache = $self->_objects_cache_bucket('ids');
102
        delete $cache->{$ids_cache_key};
103
    }
104
    else {
105
        $memory_cache->clear_from_cache(
106
            $self->_objects_cache_bucket_key('ids')
107
        );
108
    }
109
    $memory_cache->clear_from_cache(
110
        $self->_objects_cache_bucket_key('args')
111
    );
112
}
113
114
=head1 AUTHOR
115
116
David Gustafsson <david.gustafsson@ub.gu.se>
117
118
=cut
119
120
1;
(-)a/Koha/Objects/Mixin/AdditionalFields.pm (-2 lines)
Lines 2-9 package Koha::Objects::Mixin::AdditionalFields; Link Here
2
2
3
use Modern::Perl;
3
use Modern::Perl;
4
4
5
use base qw(Koha::Objects::Mixin::ExtendedAttributes);
6
7
=head1 NAME
5
=head1 NAME
8
6
9
Koha::Objects::Mixin::AdditionalFields
7
Koha::Objects::Mixin::AdditionalFields
(-)a/Koha/Objects/Mixin/ExtendedAttributes.pm (-234 lines)
Lines 1-234 Link Here
1
package Koha::Objects::Mixin::ExtendedAttributes;
2
3
# Copyright 2024 PTFS Europe Ltd
4
#
5
# This file is part of Koha.
6
#
7
# Koha is free software; you can redistribute it and/or modify it
8
# under the terms of the GNU General Public License as published by
9
# the Free Software Foundation; either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# Koha is distributed in the hope that it will be useful, but
13
# WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU General Public License for more details.
16
#
17
# You should have received a copy of the GNU General Public License
18
# along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20
use Modern::Perl;
21
use Scalar::Util qw( reftype );
22
23
=head1 NAME
24
25
Koha::Objects::Mixin::ExtendedAttributes
26
27
=head2 Class methods
28
29
30
=head3 search
31
32
    Overwrites the search method to include extended attributes rewrite and dynamic relation accessors
33
34
=cut
35
36
sub search {
37
    my ( $self, $params, $attributes ) = @_;
38
39
    my $class = ref($self) ? ref($self) : $self;
40
41
    $self->handle_query_extended_attributes(
42
        {
43
            attributes      => $attributes,
44
            filtered_params => $params,
45
        }
46
    );
47
48
    my $rs = $self->_resultset()->search( $params, $attributes );
49
    return $class->_new_from_dbic($rs);
50
}
51
52
=head3 handle_query_extended_attributes
53
54
    Checks for the presence of extended_attributes in a query
55
    If present, it builds the dynamic extended attributes relations and rewrites the query to include the extended_attributes relation
56
57
=cut
58
59
sub handle_query_extended_attributes {
60
    my ( $self, $args ) = @_;
61
62
    my $attributes      = $args->{attributes};
63
    my $filtered_params = $args->{filtered_params};
64
65
    if (   reftype( $attributes->{prefetch} )
66
        && reftype( $attributes->{prefetch} ) eq 'ARRAY'
67
        && grep ( /extended_attributes/, @{ $attributes->{prefetch} } ) )
68
    {
69
70
        my @array = $self->_get_extended_attributes_entries($filtered_params);
71
72
        # Calling our private method to build the extended attributes relations
73
        my @joins = $self->_build_extended_attributes_relations( \@array );
74
        push @{ $attributes->{join} }, @joins;
75
76
    }
77
}
78
79
=head3 _get_extended_attributes_entries
80
81
    $self->_get_extended_attributes_entries( $filtered_params, 0 )
82
83
Recursive function that returns the rewritten extended_attributes query entries.
84
85
Given:
86
[
87
    '-and',
88
    [
89
        {
90
            'extended_attributes.code'      => 'CODE_1',
91
            'extended_attributes.attribute' => { 'like' => '%Bar%' }
92
        },
93
        {
94
            'extended_attributes.attribute' => { 'like' => '%Bar%' },
95
            'extended_attributes.code'      => 'CODE_2'
96
        }
97
    ]
98
];
99
100
Returns :
101
102
[
103
    'CODE_1',
104
    'CODE_2'
105
]
106
107
=cut
108
109
sub _get_extended_attributes_entries {
110
    my ( $self, $params, @array ) = @_;
111
112
    if ( reftype($params) && reftype($params) eq 'HASH' ) {
113
114
        # rewrite additional_field_values table query params
115
        @array = _rewrite_related_metadata_query( $params, 'field_id', 'value', @array )
116
            if $params->{'extended_attributes.field_id'};
117
118
        # rewrite borrower_attributes table query params
119
        @array = _rewrite_related_metadata_query( $params, 'code', 'attribute', @array )
120
            if $params->{'extended_attributes.code'};
121
122
        # rewrite illrequestattributes table query params
123
        @array = _rewrite_related_metadata_query( $params, 'type', 'value', @array )
124
            if $params->{'extended_attributes.type'};
125
126
        foreach my $key ( keys %{$params} ) {
127
            return $self->_get_extended_attributes_entries( $params->{$key}, @array );
128
        }
129
    } elsif ( reftype($params) && reftype($params) eq 'ARRAY' ) {
130
        foreach my $ea_instance (@$params) {
131
            @array = $self->_get_extended_attributes_entries( $ea_instance, @array );
132
        }
133
        return @array;
134
    } else {
135
        return @array;
136
    }
137
}
138
139
=head3 _rewrite_related_metadata_query
140
141
        $extended_attributes_entries =
142
            _rewrite_related_metadata_query( $params, 'field_id', 'value', @array )
143
144
Helper function that rewrites all subsequent extended_attributes queries to match the alias generated by the dbic self left join
145
Take the below example (patrons):
146
        [
147
            {
148
                "extended_attributes.attribute":{"like":"%123%"},
149
                "extended_attributes.code":"CODE_1"
150
            }
151
        ],
152
        [
153
            {
154
                "extended_attributes.attribute":{"like":"%abc%" },
155
                "extended_attributes.code":"CODE_2"
156
            }
157
        ]
158
159
It'll be rewritten as:
160
        [
161
            {
162
                'extended_attributes_CODE_1.attribute' => { 'like' => '%123%' },
163
                'extended_attributes_CODE_1.code' => 'CODE_1'
164
            }
165
        ],
166
            [
167
            {
168
                'extended_attributes_CODE_2.attribute' => { 'like' => '%abc%' },
169
                'extended_attributes_CODE_2.code' => 'CODE_2'
170
            }
171
        ]
172
173
=cut
174
175
sub _rewrite_related_metadata_query {
176
    my ( $params, $key, $value, @array ) = @_;
177
178
    if ( ref \$params->{ 'extended_attributes.' . $key } eq 'SCALAR' ) {
179
        my $old_key_value = delete $params->{ 'extended_attributes.' . $key };
180
        my $new_key_value = "extended_attributes_$old_key_value" . "." . $key;
181
        $params->{$new_key_value} = $old_key_value;
182
183
        my $old_value_value = delete $params->{ 'extended_attributes.' . $value };
184
        my $new_value_value = "extended_attributes_$old_key_value" . "." . $value;
185
        $params->{$new_value_value} = $old_value_value;
186
        push @array, $old_key_value;
187
    }
188
189
    return @array;
190
}
191
192
=head3 _build_extended_attributes_relations
193
194
    Method to dynamically add has_many relations for Koha classes that support extended_attributes.
195
196
    Returns a list of relation accessor names.
197
198
=cut
199
200
sub _build_extended_attributes_relations {
201
    my ( $self, $types ) = @_;
202
203
    return if ( !grep ( /extended_attributes/, keys %{ $self->_resultset->result_source->_relationships } ) );
204
205
    my $ea_config = $self->extended_attributes_config;
206
207
    my $result_source = $self->_resultset->result_source;
208
    for my $type ( @{$types} ) {
209
        $result_source->add_relationship(
210
            "extended_attributes_$type",
211
            "$ea_config->{schema_class}",
212
            sub {
213
                my $args = shift;
214
215
                return {
216
                    "$args->{foreign_alias}.$ea_config->{id_field}->{foreign}" =>
217
                        { -ident => "$args->{self_alias}.$ea_config->{id_field}->{self}" },
218
                    "$args->{foreign_alias}.$ea_config->{key_field}" => { '=', $type },
219
                };
220
            },
221
            {
222
                accessor       => 'multi',
223
                join_type      => 'LEFT',
224
                cascade_copy   => 0,
225
                cascade_delete => 0,
226
                is_depends_on  => 0
227
            },
228
        );
229
230
    }
231
    return map { 'extended_attributes_' . $_ } @{$types};
232
}
233
234
1;
(-)a/Koha/Patron.pm (-6 / +10 lines)
Lines 68-74 use Koha::Subscription::Routinglists; Link Here
68
use Koha::Token;
68
use Koha::Token;
69
use Koha::Virtualshelves;
69
use Koha::Virtualshelves;
70
70
71
use base qw(Koha::Object);
71
use base qw(Koha::Object::CachedExpiration);
72
72
73
use constant ADMINISTRATIVE_LOCKOUT => -1;
73
use constant ADMINISTRATIVE_LOCKOUT => -1;
74
74
Lines 736-742 sub merge_with { Link Here
736
736
737
                next if $anonymous_patron && $patron_id eq $anonymous_patron;
737
                next if $anonymous_patron && $patron_id eq $anonymous_patron;
738
738
739
                my $patron = Koha::Patrons->find($patron_id);
739
                # Don't use cache as this could risk deleting a patron object
740
                #  which has a reference outside of this class
741
                my $patron = Koha::Patrons->find( $patron_id, { cache => 0 } );
740
742
741
                next unless $patron;
743
                next unless $patron;
742
744
Lines 2037-2044 sub libraries_where_can_see_things { Link Here
2037
    my $subpermission = $params->{subpermission};
2039
    my $subpermission = $params->{subpermission};
2038
    my $group_feature = $params->{group_feature};
2040
    my $group_feature = $params->{group_feature};
2039
2041
2040
    return @{ $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} }
2042
    $self->{'_cache'} //= {};
2041
        if exists( $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} );
2043
2044
    return @{ $self->{'_cache'}->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} }
2045
        if exists( $self->{'_cache'}->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} );
2042
2046
2043
    my $userenv = C4::Context->userenv;
2047
    my $userenv = C4::Context->userenv;
2044
2048
Lines 2071-2078 sub libraries_where_can_see_things { Link Here
2071
    @restricted_branchcodes = uniq(@restricted_branchcodes);
2075
    @restricted_branchcodes = uniq(@restricted_branchcodes);
2072
    @restricted_branchcodes = sort(@restricted_branchcodes);
2076
    @restricted_branchcodes = sort(@restricted_branchcodes);
2073
2077
2074
    $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} = \@restricted_branchcodes;
2078
    $self->{'_cache'}->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} = \@restricted_branchcodes;
2075
    return @{ $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} };
2079
    return @{ $self->{'_cache'}->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} };
2076
}
2080
}
2077
2081
2078
=head3 has_permission
2082
=head3 has_permission
(-)a/Koha/Patrons.pm (-1 / +1 lines)
Lines 29-35 use Koha::Exceptions::Patron; Link Here
29
use Koha::Exceptions::SysPref;
29
use Koha::Exceptions::SysPref;
30
use Koha::Patron::Categories;
30
use Koha::Patron::Categories;
31
31
32
use base qw(Koha::Objects::Mixin::ExtendedAttributes Koha::Objects);
32
use base qw(Koha::Objects::Cached);
33
33
34
=head1 NAME
34
=head1 NAME
35
35
(-)a/acqui/acqui-home.pl (-7 / +3 lines)
Lines 83-98 my $totordered_active = 0; Link Here
83
my $totavail_active   = 0;
83
my $totavail_active   = 0;
84
84
85
my @budget_loop;
85
my @budget_loop;
86
my %patrons        = ( $loggedinuser => Koha::Patrons->find($loggedinuser) );
86
my $loggedinpatron = Koha::Patrons->find($loggedinuser);
87
my $loggedinpatron = $patrons{$loggedinuser}->unblessed;
88
foreach my $budget ( @{$budget_arr} ) {
87
foreach my $budget ( @{$budget_arr} ) {
89
    next unless ( CanUserUseBudget( $loggedinpatron, $budget, $userflags ) );
88
    next unless ( CanUserUseBudget( $loggedinpatron, $budget, $userflags ) );
90
89
91
    if ( my $borrowernumber = $budget->{budget_owner_id} ) {
90
    if ( $budget->{budget_owner_id} ) {
92
        unless ( exists $patrons{$borrowernumber} ) {
91
        $budget->{budget_owner} = Koha::Patrons->find($budget->{budget_owner_id});
93
            $patrons{$borrowernumber} = Koha::Patrons->find($borrowernumber);
94
        }
95
        $budget->{budget_owner} = $patrons{$borrowernumber};
96
    }
92
    }
97
93
98
    if ( !defined $budget->{budget_amount} ) {
94
    if ( !defined $budget->{budget_amount} ) {
(-)a/t/db_dependent/Koha/Libraries.t (-1 / +201 lines)
Lines 33-38 use Koha::Library; Link Here
33
use Koha::Libraries;
33
use Koha::Libraries;
34
use Koha::Database;
34
use Koha::Database;
35
use Koha::CirculationRules;
35
use Koha::CirculationRules;
36
use Koha::Cache::Memory::Lite;
36
37
37
use t::lib::Mocks;
38
use t::lib::Mocks;
38
use t::lib::TestBuilder;
39
use t::lib::TestBuilder;
Lines 507-509 subtest 'outgoing_transfers' => sub { Link Here
507
508
508
    $schema->storage->txn_rollback;
509
    $schema->storage->txn_rollback;
509
};
510
};
510
- 
511
512
subtest 'cache tests' => sub {
513
    plan tests => 24;
514
515
    $schema->storage->txn_begin;
516
517
    my $library1 = $builder->build_object(
518
        {
519
            class => 'Koha::Libraries',
520
            value  => {
521
                branchname => 'My library'
522
            }
523
        }
524
    );
525
    my $library2 = $builder->build_object(
526
        {
527
            class => 'Koha::Libraries',
528
            value  => {
529
                branchname => 'My other library'
530
            }
531
        }
532
    );
533
534
    # Since build_object calls find internally
535
    # we first have to flush the cache since these
536
    # objects are now already cached
537
    Koha::Cache::Memory::Lite->get_instance()->flush();
538
539
    my $ids_bucket = Koha::Libraries->_objects_cache_bucket('ids');
540
    ok(!%{$ids_bucket}, 'Find cache has been cleared after flushing memory cache');
541
542
    my $cached_library = Koha::Libraries->find($library1->branchcode);
543
    Koha::Libraries->find($library2->branchcode);
544
545
    my $cached_library_ids_bucket = Koha::Libraries->_objects_cache_get(
546
        Koha::Libraries->_objects_cache_cache_key('find', $library1->branchcode),
547
        'ids'
548
    );
549
    is (ref($cached_library_ids_bucket), 'Koha::Library', 'Library should be cached after previously have been fetched');
550
    is ($cached_library_ids_bucket->branchcode, $library1->branchcode, 'The cashed library should be the expected library');
551
552
    # Set property of library by-passing the cache expiration logic
553
    # so we can veriy library is not only present in cache by also
554
    # properly retrieved in find
555
    $cached_library->_result->set_column('branchname', 'My library in cache');
556
    $cached_library = Koha::Libraries->find($library1->branchcode);
557
    is (
558
        $cached_library->branchname,
559
        'My library in cache',
560
        'The cashed library returned by find should be the cached library'
561
    );
562
563
    $library1->branchname('My expired library');
564
    $cached_library_ids_bucket = Koha::Libraries->_objects_cache_get(
565
        Koha::Libraries->_objects_cache_cache_key('find', $library1->branchcode),
566
        'ids'
567
    );
568
    is (
569
        $cached_library_ids_bucket,
570
        undef,
571
        'Cache has been expired after changing library property'
572
    );
573
574
    $cached_library = Koha::Libraries->_objects_cache_get(
575
        Koha::Libraries->_objects_cache_cache_key('find', $library2->branchcode),
576
        'ids'
577
    );
578
    is (
579
        ref($cached_library),
580
        'Koha::Library', 'Cache should still contain other cached libraries'
581
    );
582
583
    my $stored_library = Koha::Libraries->find($library1->branchcode);
584
    is (
585
        $stored_library->branchname,
586
        'My library',
587
        'Library is fetched from database after cache has been expired'
588
    );
589
590
    $cached_library = Koha::Libraries->_objects_cache_get(
591
        Koha::Libraries->_objects_cache_cache_key('find', $library1->branchcode),
592
        'ids'
593
    );
594
    is (
595
        ref($cached_library),
596
        'Koha::Library',
597
        'Library should be cached after previously have been fetched'
598
    );
599
600
    $library1->store();
601
    $cached_library = Koha::Libraries->_objects_cache_get(
602
        Koha::Libraries->_objects_cache_cache_key('find', $library1->branchcode),
603
        'ids'
604
    );
605
    is ($cached_library, undef, 'Cache has been expired after saving library to database');
606
607
    Koha::Libraries->find($library1->branchcode, { key => 'primary' });
608
    $cached_library = Koha::Libraries->_objects_cache_get(
609
        Koha::Libraries->_objects_cache_cache_key('find', $library1->branchcode, { key => 'primary' }),
610
        'args'
611
    );
612
    is (
613
        ref($cached_library),
614
        'Koha::Library',
615
        'The args cache bucket should be used if find is called with the attrs argument'
616
    );
617
    my $cached_value;
618
619
    for my $method ('find', 'search') {
620
621
        Koha::Libraries->$method({ branchcode => $library1->branchcode });
622
        Koha::Libraries->$method({ branchcode => $library2->branchcode });
623
624
        $cached_value = Koha::Libraries->_objects_cache_get(
625
            Koha::Libraries->_objects_cache_cache_key($method, { branchcode => $library1->branchcode }),
626
            'args'
627
        );
628
        $cached_library = $method eq 'search' ? $cached_value->next : $cached_value;
629
        is (
630
            ref($cached_library),
631
            'Koha::Library',
632
            'Library should be cached after previously have been fetched, and use the args cache bucket ' . ($method eq 'find' ? 'if find was called with column conditions' : 'if search was called')
633
        );
634
635
        $cached_library->_result->set_column('branchname', 'My library in cache');
636
        $cached_value = Koha::Libraries->$method({ branchcode => $library1->branchcode });
637
        $cached_library = $method eq 'search' ? $cached_value->next : $cached_value;
638
        is (
639
            $cached_library->branchname,
640
            'My library in cache',
641
            "The cashed library returned by $method should be the cached library, using the args cache bucket"
642
        );
643
644
        $cached_library->branchname('My expired library');
645
        $cached_value = Koha::Libraries->_objects_cache_get(
646
            Koha::Libraries->_objects_cache_cache_key($method, { branchcode => $library1->branchcode }),
647
            'args'
648
        );
649
        is (
650
            $cached_value,
651
            undef,
652
            'Cache has been expired after changing branchname, using the args cache bucket'
653
        );
654
655
        $cached_value = Koha::Libraries->_objects_cache_get(
656
            Koha::Libraries->_objects_cache_cache_key($method, { branchcode => $library2->branchcode }),
657
            'args'
658
        );
659
        is (
660
            $cached_value,
661
            undef,
662
            'The whole args cache bucket has been emptied after triggering cache expiration'
663
        );
664
    }
665
666
    Koha::Libraries->find($library2->branchcode);
667
668
    my $libraries = Koha::Libraries->search({ branchcode => $library1->branchcode });
669
    $libraries->next;
670
    is($libraries->next, undef, 'Cached libraries search result iterator has been exhausted');
671
672
    $libraries = Koha::Libraries->search({ branchcode => $library1->branchcode });
673
    is(ref($libraries->next), 'Koha::Library', 'Cached libraries search result iterator has been reset');
674
675
676
    my $cached_libraries = Koha::Libraries->_objects_cache_get(
677
        Koha::Libraries->_objects_cache_cache_key('search', { 'branchcode' => $library1->branchcode }),
678
        'args'
679
    );
680
    is (
681
        ref($cached_libraries),
682
        'Koha::Libraries',
683
        'Libraries should be cached after previously have been fetched'
684
    );
685
686
    $library1->delete();
687
    $cached_libraries = Koha::Libraries->_objects_cache_get(
688
        Koha::Libraries->_objects_cache_cache_key('search', { 'branchcode' => $library1->branchcode }),
689
        'args'
690
    );
691
    is ($cached_libraries, undef, 'Search cache has been expired after deleting library');
692
693
    $cached_library = Koha::Libraries->_objects_cache_get(
694
        Koha::Libraries->_objects_cache_cache_key('find', $library2->branchcode),
695
        'ids'
696
    );
697
    is (
698
        ref($cached_library),
699
        'Koha::Library',
700
        'Library should be cached after previously have been fetched'
701
    );
702
    $library2->delete();
703
    $cached_library = Koha::Libraries->_objects_cache_get(
704
        Koha::Libraries->_objects_cache_cache_key('find', $library2->branchcode),
705
        'ids'
706
    );
707
    is ($cached_library, undef, 'Find cache has been expired after deleting library');
708
709
    $schema->storage->txn_rollback;
710
}

Return to bug 36350