blib/lib/DBIx/Class/Events.pm

filter: Statementstmt 100% 59 / 59 Branchbran 87.5% 14 / 16 Conditioncond 100% 5 / 5 MC/DCmcdc 100% 3 / 3 Subroutinesub 100% 12 / 12 Podpod 100% 6 / 6 totaltotal 98.0% 99 / 101 CC 11 SCAR 12.1
CC
11
Cov
98%
state_at
7.0
update
3.0
delete
2.0
CRAP 3.4
↑ Summary
1 package DBIx::Class::Events;
2  
3 # ABSTRACT: Store Events for your DBIC Results
4 2 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 our $VERSION = 'v0.9.3'; # VERSION
6  
7 2 ▶use v5.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use parent 'DBIx::Class';
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 2 __PACKAGE__->mk_classdata( events_relationship => 'events' );
15  
16 73 ▶sub event {
Subroutine event: called CC=2 SCAR=6.9
Pod documented
17 73 my ($self, $event, $col_data) = @_;
18  
19 # Just calling $object->event shouldn't work
20 73 ▶ croak("Event is required") unless defined $event;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $event 1 72 73
21  
22 my %col_data = (
23 $self->event_defaults($event, $col_data),
24  
25 # Ignore unknown columns when we enter the event.
26 # TODO: optimize the ->columns call
27 71 map { $_ => $col_data->{$_} }
28 72 grep { exists $col_data->{$_} }
29 $self->result_source
30 ->related_source( $self->events_relationship )->columns,
31 );
32  
33 72 return $self->create_related( $self->events_relationship,
34 { %col_data, event => $event } );
35 }
36  
37 72 ▶sub event_defaults {}
Subroutine event_defaults: called CC=1 SCAR=0.0
Pod documented
38  
39 17 ▶sub state_at {
Subroutine state_at: called CC=7 SCAR=19.5
Pod documented
40 17 my ($self, $time_stamp, @args) = @_;
41  
42 17 ▶ if (ref $time_stamp) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $time_stamp) 4 13 17
43 4 my $dtf = $self->result_source->schema->storage->datetime_parser;
44 4 $time_stamp = $dtf->format_datetime( $time_stamp );
45 }
46  
47 17 my $events = $self->search_related( $self->events_relationship );
48 17 my $alias = $events->current_source_alias;
49 $events = $events->search( {
50 "$alias.event" => { in => [qw( insert update delete )] },
51 "$alias.triggered_on" => { '<=', $time_stamp },
52 },
53 {
54 select => [ "$alias.event", "$alias.details" ],
55 order_by => [
56 17 map {"$alias.$_ desc"} 'triggered_on',
57 $events->result_source->primary_columns
58 ],
59 } )->search(@args);
60  
61 17 my $event = $events->next;
62 17 ▶ return undef if !$event or $event->event eq 'delete';
Branch: 1 branch
BranchTrueFalseTotal
if not $event or $event->event eq "delete" 6 11 17
Condition100%3/3
not $event or $event->event eq "delete"
l!l&&r!l&&!r
3311
MC/DC100%2/2
not $event or $event->event eq "delete"
not $event $event->event eq "delete"
Truth table100%3/3
not(A) or B
A= not $eventB= $event->event eq "delete"
ABresult
1X1
011
000
63  
64 11 my %state;
65 11 ▶ while ($event) {
Branch: 1 branch
BranchTrueFalseTotal
if ($event) 22 0 22
66 22 ▶ %state = ( %{ $event->details || {} }, %state );
Condition100%2/2
$event->details || {}
l!l
193
MC/DC100%1/1
$event->details || {}
$event->details
Truth table100%2/2
A
A= $event->details
Aresult
11
00
67  
68 22 ▶ last if $event->event eq 'insert';
Branch: 1 branch
BranchTrueFalseTotal
if $event->event eq "insert" 11 11 22
69 11 $event = $events->next;
70 }
71  
72 11 return \%state;
73 }
74  
75 22 ▶sub insert {
Subroutine insert: called CC=1 SCAR=0.0
Pod documented
76 22 my ( $class, @args ) = @_;
77  
78 22 my $self = $class->next::method(@args);
79  
80 22 my %inserted = $self->get_columns;
81 22 $self->event( insert => { details => \%inserted } );
82  
83 22 return $self;
84 };
85  
86 13 ▶sub update {
Subroutine update: called CC=3 SCAR=11.0
Pod documented
87 13 my ( $self, @args ) = @_;
88  
89 # Do this here instead of letting our parent do it
90 # so that we can use get_dirty_columns.
91 13 ▶ $self->set_inflated_columns(@args) if @args;
Branch: 1 branch
BranchTrueFalseTotal
if @args 2 11 13
92  
93 13 my %changed = $self->get_dirty_columns;
94  
95 13 $self->next::method(); # we already set_inflated_columns
96  
97 13 ▶ $self->event( update => { details => \%changed } ) if %changed;
Branch: 1 branch
BranchTrueFalseTotal
if %changed 10 3 13
98  
99 13 return $self;
100 };
101  
102 6 ▶sub delete {
Subroutine delete: called CC=2 SCAR=7.0
Pod documented
103 6 my ( $self, @args ) = @_;
104  
105 # DBIx::Class::Row::delete has a special edge case for calling
106 # delete as a class method, we however can't log it in that case.
107 6 ▶ if ( ref $self ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self) 6 0 6
108 6 my %deleted = $self->get_columns;
109 6 $self->event( delete => { details => \%deleted } );
110 }
111  
112 6 return $self->next::method(@args);
113  
114 };
115  
116 2 1;
117  
118 =pod
119  
120 =encoding UTF-8
121  
122 =head1 NAME
123  
124 DBIx::Class::Events - Store Events for your DBIC Results
125  
126 =head1 VERSION
127  
128 version v0.9.3
129  
130 =head1 SYNOPSIS
131  
132 my $artist
133 = $schema->resultset('Artist')->create( { name => 'Dead Salmon' } );
134 $artist->events->count; # is now 1, an 'insert' event
135  
136 $artist->change_name('Trout'); # add a name_change event
137 $artist->update; # An update event, last_name_change_id and name
138  
139 # Find their previous name
140 my $name_change = $artist->last_name_change;
141 print $name_change->details->{old}, "\n";
142  
143 See C<change_name> and C<last_name_change> example definitions
144 in L</CONFIGURATION AND ENVIRONMENT>.
145  
146 # Three more name_change events and one update event
147 $artist->change_name('Fried Trout');
148 $artist->change_name('Poached Trout in a White Wine Sauce');
149 $artist->change_name('Herring');
150 $artist->update;
151  
152 # Look up all the band's previous names
153 print "$_\n"
154 for map { $_->details->{old} }
155 $artist->events->search( { event => 'name_change' } );
156  
157 $artist->delete; # and then they break up.
158  
159 # We can find out now when they broke up, if we remember their id.
160 my $deleted_on
161 = $schema->resultset('ArtistEvent')
162 ->single( { artistid => $artist->id, event => 'delete' } )
163 ->triggered_on;
164  
165 # Find the state of the band was just before the breakup.
166 my $state_before_breakup
167 = $artist->state_at( $deleted_on->subtract( seconds => 1 ) );
168  
169 # Maybe this is common,
170 # so we have a column to link to who they used to be.
171 my $previous_artist_id = delete $state_before_breakup->{artistid};
172  
173 # Then we can form a new band, linked to the old,
174 # with the same values as the old band, but a new name.
175 $artist = $schema->resultset('Artist')->create( {
176 %{$state_before_breakup},
177 previousid => $previous_artist_id,
178 name => 'Red Herring',
179 } );
180  
181 # After a few more name changes, split-ups, and getting back together,
182 # we find an event we should have considered, but didn't.
183 my $death_event
184 = $artist->event( death => { details => { who => 'drummer' } } );
185  
186 # but, we then go back and modify it to note that it was only a rumor
187 $death_event->details->{only_a_rumour} = 1;
188 $death_event->make_column_dirty('details'); # changing the hashref doesn't
189 $death_event->update
190  
191 # And after even more new names and arguments, they split up again
192 $artist->delete;
193  
194 See L</CONFIGURATION AND ENVIRONMENT> for how to set up the tables.
195  
196 =head1 DESCRIPTION
197  
198 A framework for capturing events that happen to a Result in a table,
199 L</PRECONFIGURED EVENTS> are triggered automatically to track changes.
200  
201 This is useful for both being able to see the history of things
202 in the database as well as logging when events happen that
203 can be looked up later.
204  
205 Events can be used to track when things happen.
206  
207 =over
208  
209 =item when a user on a website clicks a particular button
210  
211 =item when a recipe was prepared
212  
213 =item when a song was played
214  
215 =item anything that doesn't fit in the main table
216  
217 =back
218  
219 =head1 CONFIGURATION AND ENVIRONMENT
220  
221 =head2 event_defaults
222  
223 A method that returns an even-sized list of default values that will be used
224 when creating a new event.
225  
226 my %defaults = $object->event_defaults( $event_type, \%col_data );
227  
228 The C<$event_type> is a string defining the "type" of event being created.
229 The C<%col_data> is a reference to the parameters passed in.
230  
231 No default values, but if your database doesn't set a default for
232 C<triggered_on>, you may want to set it to a C<< DateTime->now >> object.
233  
234 =head2 events_relationship
235  
236 An class accessor that returns the relationship to get from your object
237 to the relationship.
238  
239 Default is C<events>, but you can override it:
240  
241 __PACKAGE__->has_many(
242 'cd_events' =>
243 ( 'MyApp::Schema::Result::ArtistEvents', 'cdid' ),
244 { cascade_delete => 0 },
245 );
246  
247 __PACKAGE__->events_relationship('cd_events');
248  
249 =head2 Tables
250  
251 =head3 Tracked Table
252  
253 The table with events to be tracked in the L</Tracking Table>.
254  
255 It requires the Component and L</events_relationship> in the Result class:
256  
257 package MyApp::Schema::Result::Artist;
258 use base qw( DBIx::Class::Core );
259  
260 ...;
261  
262 __PACKAGE__->load_components( qw/ Events / );
263  
264 # A different name can be used with the "events_relationship" attribute
265 __PACKAGE__->has_many(
266 'events' => ( 'MyApp::Schema::Result::ArtistEvent', 'artistid' ),
267 { cascade_delete => 0 },
268 );
269  
270 You can also add custom events to track when something happens. For example,
271 you can create a method to add events when an artist changes their name:
272  
273 __PACKAGE__->add_column(
274 last_name_change_id => { data_type => 'integer' } );
275  
276 __PACKAGE__->has_one(
277 'last_name_change' => 'MyApp::Schema::Result::ArtistEvent',
278 { 'foreign.artisteventid' => 'self.last_name_change_id' },
279 { cascade_delete => 0 },
280 );
281  
282 sub change_name {
283 my ( $self, $new_name ) = @_;
284  
285 my $event = $self->event( name_change =>
286 { details => { new => $new_name, old => $self->name } } );
287 $self->last_name_change( $event );
288 # $self->update; # be lazy and make our caller call ->update
289  
290 $self->name( $new_name );
291 }
292  
293 =head3 Tracking Table
294  
295 This table holds the events for the L</Tracked Table>.
296  
297 The C<triggered_on> column must either provide a C<DEFAULT> value
298 or you should add a default to L</event_defaults>.
299  
300 package MyApp::Schema::Result::ArtistEvent;
301  
302 use warnings;
303 use strict;
304 use JSON;
305  
306 use base qw( DBIx::Class::Core );
307  
308 __PACKAGE__->load_components(qw/ InflateColumn::DateTime /);
309  
310 __PACKAGE__->table('artist_event');
311  
312 __PACKAGE__->add_columns(
313 artisteventid => { data_type => 'integer', is_auto_increment => 1 },
314 artistid => { data_type => 'integer' },
315  
316 # The type of event
317 event => { data_type => 'varchar' },
318  
319 # Any other custom columns you want to store for each event.
320  
321 triggered_on => {
322 data_type => 'datetime',
323 default_value => \'NOW()',
324 },
325  
326 # Where we store freeform data about what happened
327 details => { data_type => 'longtext' },
328 );
329  
330 __PACKAGE__->set_primary_key('artisteventid');
331  
332 # You should set up automatic inflation/deflation of the details column
333 # as it is used this way by "state_at" and the insert/update/delete
334 # events. Does not have to be JSON, just be able to serialize a hashref.
335 {
336 my $json = JSON->new->utf8;
337 __PACKAGE__->inflate_column( 'details' => {
338 inflate => sub { $json->decode(shift) },
339 deflate => sub { $json->encode(shift) },
340 } );
341 }
342  
343 This L<C<belongs_to>|DBIx::Class::Relationship/belongs_to>
344 relationship is optional,
345 and the examples and tests assume if it exists,
346 it is not a real database-enforced foreign key
347 that will trigger constraint violations if the thing being tracked is deleted.
348  
349 # A path back to the object that this event is for,
350 # not required unlike the has_many "events" relationship above
351 __PACKAGE__->belongs_to(
352 'artist' => ( 'MyApp::Schema::Result::Artist', 'artistid' ) );
353  
354 You probably also want an index for searching for events:
355  
356 sub sqlt_deploy_hook {
357 my ( $self, $sqlt_table ) = @_;
358 $sqlt_table->add_index(
359 name => 'artist_event_idx',
360 fields => [ "artistid", "triggered_on", "event" ],
361 );
362 }
363  
364 =head1 PRECONFIGURED EVENTS
365  
366 Automatically creates Events for actions that modify a row.
367  
368 See the L</BUGS AND LIMITATIONS> of bulk modifications on events.
369  
370 =over
371  
372 =item insert
373  
374 Logs all columns to the C<details> column, with an C<insert> event.
375  
376 =item update
377  
378 Logs dirty columns to the C<details> column, with an C<update> event.
379  
380 =item delete
381  
382 Logs all columns to the C<details> column, with a C<delete> event.
383  
384 See the L</BUGS AND LIMITATIONS> for more information about
385 using this method with a database enforced foreign key.
386  
387 =back
388  
389 =head1 METHODS
390  
391 =head2 event
392  
393 Inserts a new event with L</event_defaults>:
394  
395 my $new_event = $artist->event( $event => \%params );
396  
397 First, the L</event_defaults> method is called to build a list of values
398 to set on the new event. This method is passed the C<$event> and a reference
399 to C<%params>.
400  
401 Then, the C<%params>, filtered for valid L</events_relationship> C<columns>,
402 are added to the C<create_related> arguments, overriding the defaults.
403  
404 =head2 state_at
405  
406 Takes a timestamp and returns the state of the thing at that timestamp as a
407 hash reference. Can be either a correctly deflated string or a DateTime
408 object that will be deflated with C<format_datetime>.
409  
410 Returns undef if the object was not C<in_storage> at the timestamp.
411  
412 my $state = $schema->resultset('Artist')->find( { name => 'David Bowie' } )
413 ->state_at('2006-05-29 08:00');
414  
415 An idea is to use it to recreate an object as it was at that timestamp.
416 Of course, default values that the database provides will not be included,
417 unless the L</event_defaults> method accounts for that.
418  
419 my $resurrected_object
420 = $object->result_source->new( $object->state_at($timestamp) );
421  
422 See ".. format a DateTime object for searching?" under L<DBIx::Class::Manual::FAQ/Searching>
423 for details on formatting the timestamp.
424  
425 You can pass additional L<search|DBIx::Class::ResultSet/search> conditions and
426 attributes to this method. This is done in context of searching the events
427 table:
428  
429 my $state = $object->state_at($timestamp, \%search_cond, \%search_attrs);
430  
431 =head1 BUGS AND LIMITATIONS
432  
433 There is no attempt to handle bulk updates or deletes. So, any changes to the
434 database made by calling
435 L<"update"|DBIx::Class::ResultSet/update> or L<"delete"|DBIx::Class::ResultSet/delete>
436 will not create events the same as L<single row|DBIx::Class::Row> modifications. Use the
437 L<"update_all"|DBIx::Class::ResultSet/update_all> or L<"delete_all"|DBIx::Class::ResultSet/delete_all>
438 methods of the C<ResultSet> if you want these triggers.
439  
440 If you create the C<belongs_to> relationship
441 described under L</Tracking Table>
442 as a database-enforced foreign key
443 then deleting from the tracked table will fail due to those constraints.
444  
445 There are three required columns on the L</events_relationship> table:
446 C<event>, C<triggered_on>, and C<details>. We should eventually make those
447 configurable.
448  
449 =head1 SEE ALSO
450  
451 =over
452  
453 =item L<DBIx::Class::AuditAny>
454  
455 =item L<DBIx::Class::AuditLog>
456  
457 =item L<DBIx::Class::Journal>
458  
459 =item L<DBIx::Class::PgLog>
460  
461 =back
462  
463 =head1 AUTHOR
464  
465 Grant Street Group <developers@grantstreet.com>
466  
467 =head1 COPYRIGHT AND LICENSE
468  
469 This software is Copyright (c) 2018 - 2024 by Grant Street Group.
470  
471 This is free software, licensed under:
472  
473 The Artistic License 2.0 (GPL Compatible)
474  
475 =cut
476  
477 __END__
↑ Summary