AuditAny.pm

filter: Statementstmt 71.1% 284 / 399 Branchbran 38.1% 58 / 152 Conditioncond 24.3% 10 / 41 MC/DCmcdc 0.0% 0 / 24 Subroutinesub 75.0% 60 / 80 Podpod 94.7% 18 / 19 totaltotal 60.1% 430 / 715 CC 116 SCAR 33.4
CC
116
Cov
59%
track
91.1
__ANON__
72.0
audit_take_snapshot
72.0
CRAP 28.2
« AuditAny/Role/Storage.pm ↑ Summary AuditAny/AuditContext/Change.pm »
1 package DBIx::Class::AuditAny;
2 12 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 12 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 # ABSTRACT: Flexible change tracking framework for DBIx::Class
6  
7 12 our $VERSION = '0.200002';
8  
9 12 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 12 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 12 ▶use MooX::Types::MooseLike::Base 0.19 qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 12 ▶use Class::MOP;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 12 ▶use Class::MOP::Class;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 12 ▶use DateTime;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 12 ▶use DBIx::Class::AuditAny::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 12 ▶use DBIx::Class::AuditAny::Util::BuiltinDatapoints;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 12 ▶use DBIx::Class::AuditAny::Role::Schema;
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 12 ▶use Term::ANSIColor qw(:constants);
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 15 ▶has 'time_zone', is => 'ro', isa => Str, default => sub{'local'};
Subroutine __ANON__: called CC=1 SCAR=0.0
24 13 ▶sub get_dt { DateTime->now( time_zone => (shift)->time_zone ) }
Subroutine get_dt: called CC=1 SCAR=0.0
Pod documented
25  
26 12 has 'schema', is => 'ro', required => 1, isa => InstanceOf['DBIx::Class::Schema']; #<--- This won't go back to Moose
27 13 ▶has 'track_immutable', is => 'ro', isa => Bool, default => sub{0};
Subroutine __ANON__: called CC=1 SCAR=0.0
28 15 ▶has 'track_actions', is => 'ro', isa => ArrayRef, default => sub { [qw(insert update delete)] };
Subroutine __ANON__: called CC=1 SCAR=0.0
29 15 ▶has 'allow_multiple_auditors', is => 'ro', isa => Bool, default => sub{0};
Subroutine __ANON__: called CC=1 SCAR=0.0
30  
31 15 ▶has 'source_context_class', is => 'ro', default => sub{'AuditContext::Source'};
Subroutine __ANON__: called CC=1 SCAR=0.0
32 15 ▶has 'change_context_class', is => 'ro', default => sub{'AuditContext::Change'};
Subroutine __ANON__: called CC=1 SCAR=0.0
33 15 ▶has 'changeset_context_class', is => 'ro', default => sub{'AuditContext::ChangeSet'};
Subroutine __ANON__: called CC=1 SCAR=0.0
34 15 ▶has 'column_context_class', is => 'ro', default => sub{'AuditContext::Column'};
Subroutine __ANON__: called CC=1 SCAR=0.0
35 15 ▶has 'default_datapoint_class', is => 'ro', default => sub{'DataPoint'};
Subroutine __ANON__: called CC=1 SCAR=0.0
36 12 has 'collector_class', is => 'ro', isa => Str;
37  
38 around $_ => sub {
39 271 ▶ my $orig = shift; my $self = shift;
Subroutine __ANON__: called CC=1 SCAR=0.0
40 271 resolve_localclass $self->$orig(@_);
41 12 } for qw(
42 source_context_class change_context_class
43 changeset_context_class column_context_class
44 default_datapoint_class collector_class
45 );
46  
47 0 ▶has 'collector_params', is => 'ro', isa => HashRef, default => sub {{}};
Subroutine __ANON__: not called CC=1 SCAR=1.2
48 15 ▶has 'primary_key_separator', is => 'ro', isa => Str, default => sub{'|~|'};
Subroutine __ANON__: called CC=1 SCAR=0.0
49 13 ▶has 'datapoint_configs', is => 'ro', isa => ArrayRef[HashRef], default => sub {[]};
Subroutine __ANON__: called CC=1 SCAR=0.0
50 15 ▶has 'auto_include_user_defined_datapoints', is => 'ro', isa => Bool, default => sub{1};
Subroutine __ANON__: called CC=1 SCAR=0.0
51 7 ▶has 'rename_datapoints', is => 'ro', isa => Maybe[HashRef[Str]], default => sub{undef};
Subroutine __ANON__: called CC=1 SCAR=0.0
52 15 ▶has 'disable_datapoints', is => 'ro', isa => ArrayRef, default => sub {[]};
Subroutine __ANON__: called CC=1 SCAR=0.0
53 15 ▶has 'record_empty_changes', is => 'ro', isa => Bool, default => sub{0};
Subroutine __ANON__: called CC=1 SCAR=0.0
54  
55 has 'datapoints', is => 'ro', isa => ArrayRef[Str],
56 6 ▶ default => sub{[qw(
Subroutine __ANON__: called CC=1 SCAR=0.0
57 change_ts
58 action
59 source
60 pri_key_value
61 column_name
62 old_value
63 new_value
64 12 )]};
65  
66 has 'collector', is => 'ro', lazy => 1, default => sub {
67 15 ▶ my $self = shift;
Subroutine __ANON__: called CC=1 SCAR=0.0
68 return ($self->collector_class)->new(
69 15 %{$self->collector_params},
70 AuditObj => $self
71 );
72 12 };
73  
74 # Any sources within the tracked schema that the collector is writing to; these
75 # sources are not allowed to be tracked because it would create infinite recursion:
76 has 'log_sources', is => 'ro', isa => ArrayRef[Str], lazy => 1, init_arg => undef, default => sub {
77 4 ▶ my $self = shift;
Subroutine __ANON__: called CC=1 SCAR=0.0
78 4 return $self->collector->writes_bound_schema_sources;
79 12 };
80  
81 15 ▶has 'tracked_action_functions', is => 'ro', isa => HashRef, default => sub {{}};
Subroutine __ANON__: called CC=1 SCAR=0.0
82 15 ▶has 'tracked_sources', is => 'ro', isa => HashRef[Str], default => sub {{}};
Subroutine __ANON__: called CC=1 SCAR=0.0
83 15 ▶has 'calling_action_function', is => 'ro', isa => HashRef[Bool], default => sub {{}};
Subroutine __ANON__: called CC=1 SCAR=0.0
84 15 ▶has 'active_changeset', is => 'rw', isa => Maybe[Object], default => sub{undef};
Subroutine __ANON__: called CC=1 SCAR=0.0
85 15 ▶has 'auto_finish', is => 'rw', isa => Bool, default => sub{0};
Subroutine __ANON__: called CC=1 SCAR=0.0
86  
87 0 ▶has 'track_init_args', is => 'ro', isa => Maybe[HashRef], default => sub{undef};
Subroutine __ANON__: not called CC=1 SCAR=1.2
88 12 has 'build_init_args', is => 'ro', isa => HashRef, required => 1;
89  
90 around BUILDARGS => sub {
91 15 ▶ my $orig = shift;
Subroutine __ANON__: called CC=3 SCAR=11.6
92 15 my $class = shift;
93 15 ▶ my %opts = (ref($_[0]) eq 'HASH') ? %{ $_[0] } : @_; # <-- arg as hash or hashref
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 0 15 15
94  
95 15 ▶ die 'Cannot specify build_init_args in new()' if (exists $opts{build_init_args});
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"build_init_args"} 0 15 15
96 15 $opts{build_init_args} = { %opts };
97 15 return $class->$orig(%opts);
98 12 };
99  
100 sub track {
101 15 ▶ my $class = shift;
Subroutine track: called CC=28 SCAR=45.1
Pod documented
102 15 ▶ my %opts = (ref($_[0]) eq 'HASH') ? %{ $_[0] } : @_; # <-- arg as hash or hashref
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 0 15 15
103 15 ▶ die "track cannot be called on object instances" if (ref $class);
Branch: 1 branch
BranchTrueFalseTotal
if ref $class 0 15 15
104
105 # Record the track init arguments:
106 15 $opts{track_init_args} = { %opts };
107
108 15 ▶ my $sources = exists $opts{track_sources} ? delete $opts{track_sources} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'track_sources'} ? : 0 15 15
109 15 ▶ die 'track_sources must be an arrayref' if ($sources and ! ref($sources) eq 'ARRAY');
Branch: 1 branch
BranchTrueFalseTotal
if $sources and !ref($sources) eq "ARRAY" 0 15 15
Condition33%1/3
$sources and !ref($sources) eq "ARRAY"
!ll&&!rl&&r
1500
MC/DC0%0/2
$sources and !ref($sources) eq "ARRAY"
$sources !ref($sources) eq "ARRAY"
Truth table33%1/3
A and not(B)
A= $sourcesB= !ref($sources) eq "ARRAY"
ABresult
0X0
100
111
110 15 ▶ my $track_all = exists $opts{track_all_sources} ? delete $opts{track_all_sources} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'track_all_sources'} ? : 15 0 15
111 15 ▶ die "track_sources and track_all_sources are incompatible" if ($sources && $track_all);
Branch: 1 branch
BranchTrueFalseTotal
if $sources and $track_all 0 15 15
Condition33%1/3
$sources and $track_all
!ll&&!rl&&r
1500
MC/DC0%0/2
$sources and $track_all
$sources $track_all
Truth table33%1/3
A and B
A= $sourcesB= $track_all
ABresult
0X0
100
111
112
113 15 ▶ my $init_sources = exists $opts{init_sources} ? delete $opts{init_sources} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'init_sources'} ? : 0 15 15
114 15 ▶ die 'init_sources must be an arrayref' if ($init_sources and ! ref($init_sources) eq 'ARRAY');
Branch: 1 branch
BranchTrueFalseTotal
if $init_sources and !ref($init_sources) eq "ARRAY" 0 15 15
Condition33%1/3
$init_sources and !ref($init_sources) eq "ARRAY"
!ll&&!rl&&r
1500
MC/DC0%0/2
$init_sources and !ref($init_sources) eq "ARRAY"
$init_sources !ref($init_sources) eq "ARRAY"
Truth table33%1/3
A and not(B)
A= $init_sourcesB= !ref($init_sources) eq "ARRAY"
ABresult
0X0
100
111
115 15 ▶ my $init_all = exists $opts{init_all_sources} ? delete $opts{init_all_sources} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'init_all_sources'} ? : 0 15 15
116 15 ▶ die "init_sources and init_all_sources are incompatible" if ($init_sources && $init_all);
Branch: 1 branch
BranchTrueFalseTotal
if $init_sources and $init_all 0 15 15
Condition33%1/3
$init_sources and $init_all
!ll&&!rl&&r
1500
MC/DC0%0/2
$init_sources and $init_all
$init_sources $init_all
Truth table33%1/3
A and B
A= $init_sourcesB= $init_all
ABresult
0X0
100
111
117
118 15 ▶ my $collect = exists $opts{collect} ? delete $opts{collect} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'collect'} ? : 2 13 15
119 15 ▶ if ($collect) {
Branch: 1 branch
BranchTrueFalseTotal
if ($collect) 2 13 15
120 die "'collect' cannot be used with 'collector_params', 'collector_class' or 'collector'"
121 2 ▶ if ($opts{collector_params} || $opts{collector_class} || $opts{collector});
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"collector_params"} or $opts{"collector_class"} or $opts{"collector"} 0 2 2
Condition33%2/6
$opts{"collector_params"} or $opts{"collector_class"} or $opts{"collector"}
l!l&&r!l&&!r
002
$opts{"collector_params"} or $opts{"collector_class"}
l!l&&r!l&&!r
002
MC/DC0%0/3
$opts{"collector_params"} or $opts{"collector_class"} or $opts{"collector"}
$opts{"collector_params"} $opts{"collector_class"} $opts{"collector"}
Truth table25%1/4
A or B or C
A= $opts{"collector_params"}B= $opts{"collector_class"}C= $opts{"collector"}
ABCresult
1XX1
01X1
0011
0000
122
123 2 $opts{collector_class} = 'Collector::Code';
124 2 $opts{collector_params} = { collect_coderef => $collect };
125 }
126
127 15 ▶ if($opts{collector}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"collector"}) 0 15 15
128 die "'collector' cannot be used with 'collector_params', 'collector_class' or 'collect'"
129 0 ▶ if ($opts{collector_params} || $opts{collector_class} || $opts{collect});
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"collector_params"} or $opts{"collector_class"} or $opts{"collect"} 0 0 0
Condition0%0/6
$opts{"collector_params"} or $opts{"collector_class"} or $opts{"collect"}
l!l&&r!l&&!r
000
$opts{"collector_params"} or $opts{"collector_class"}
l!l&&r!l&&!r
000
MC/DC0%0/3
$opts{"collector_params"} or $opts{"collector_class"} or $opts{"collect"}
$opts{"collector_params"} $opts{"collector_class"} $opts{"collect"}
Truth table0%0/4
A or B or C
A= $opts{"collector_params"}B= $opts{"collector_class"}C= $opts{"collect"}
ABCresult
1XX1
01X1
0011
0000
130 }
131
132 15 my $self = $class->new(%opts);
133
134 4 ▶ $self->track_sources(@$sources) if ($sources);
Branch: 1 branch
BranchTrueFalseTotal
if $sources 0 4 4
135 4 ▶ $self->track_all_sources if ($track_all);
Branch: 1 branch
BranchTrueFalseTotal
if $track_all 4 0 4
136
137 4 ▶ $self->init_sources(@$init_sources) if ($init_sources);
Branch: 1 branch
BranchTrueFalseTotal
if $init_sources 0 4 4
138 4 ▶ $self->init_all_sources if ($init_all);
Branch: 1 branch
BranchTrueFalseTotal
if $init_all 0 4 4
139 4 return $self;
140 }
141  
142  
143 sub _get_datapoint_configs {
144 15 ▶ my $self = shift;
Subroutine _get_datapoint_configs: called CC=2 SCAR=6.9
145
146 15 my @configs = DBIx::Class::AuditAny::Util::BuiltinDatapoints->all_configs;
147
148 # strip out any being redefined:
149 15 my %cust = map {$_->{name}=>1} @{$self->datapoint_configs};
150 15 @configs = grep { !$cust{$_->{name}} } @configs;
151
152 # Set flag to mark the configs that were user defined
153 15 $_->{user_defined} = 1 for (@{$self->datapoint_configs});
154
155 15 push @configs, @{$self->datapoint_configs};
156
157 15 return @configs;
158 }
159  
160 15 ▶has '_datapoints', is => 'ro', isa => HashRef, default => sub {{}};
Subroutine __ANON__: called CC=1 SCAR=0.0
161 15 ▶has '_datapoints_context', is => 'ro', isa => HashRef, default => sub {{}};
Subroutine __ANON__: called CC=1 SCAR=0.0
162  
163 # Also index datapoints by 'original_name' which will be different from 'name'
164 # whenever 'rename_datapoints' has been applied
165 15 ▶has '_datapoints_orig_names', is => 'ro', isa => HashRef, default => sub {{}};
Subroutine __ANON__: called CC=1 SCAR=0.0
166 11 ▶sub get_datapoint_orig { (shift)->_datapoints_orig_names->{(shift)} }
Subroutine get_datapoint_orig: called CC=1 SCAR=0.0
Pod documented
167  
168 sub add_datapoints {
169 156 ▶ my $self = shift;
Subroutine add_datapoints: called CC=7 SCAR=20.4
Pod documented
170 156 my $class = $self->default_datapoint_class;
171 156 foreach my $cnf (@_) {
172 156 ▶ die "'$cnf' not expected ref" unless (ref $cnf);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cnf 0 156 156
173 156 ▶ $class = delete $cnf->{class} if ($cnf->{class});
Branch: 1 branch
BranchTrueFalseTotal
if $cnf->{"class"} 0 156 156
174 156 ▶ my $DataPoint = ref($cnf) eq $class ? $cnf : $class->new($cnf);
Branch: 1 branch
BranchTrueFalseTotal
ref $cnf eq $class ? : 0 156 156
175 156 ▶ die "Error creating datapoint object" unless (ref($DataPoint) eq $class);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $DataPoint eq $class 0 156 156
176 156 ▶ die "Duplicate datapoint name '" . $DataPoint->name . "'" if ($self->_datapoints->{$DataPoint->name});
Branch: 1 branch
BranchTrueFalseTotal
if $self->_datapoints->{$DataPoint->name} 0 156 156
177 156 $self->_datapoints->{$DataPoint->name} = $DataPoint;
178 156 $self->_datapoints_context->{$DataPoint->context}->{$DataPoint->name} = $DataPoint;
179 156 $self->_datapoints_orig_names->{$DataPoint->original_name} = $DataPoint;
180 }
181 }
182 0 ▶sub all_datapoints { values %{(shift)->_datapoints} }
Subroutine all_datapoints: not called CC=1 SCAR=6.9
Pod documented
183  
184 sub get_context_datapoints {
185 39 ▶ my $self = shift;
Subroutine get_context_datapoints: called CC=1 SCAR=0.0
Pod documented
186 39 my @contexts = grep { exists $self->_datapoints_context->{$_} } @_;
187 39 return map { values %{$self->_datapoints_context->{$_}} } @contexts;
188 }
189  
190 sub get_context_datapoint_names {
191 0 ▶ my $self = shift;
Subroutine get_context_datapoint_names: not called CC=1 SCAR=6.9
Pod documented
192 0 return map { $_->name } $self->get_context_datapoints(@_);
193 }
194  
195  
196 0 ▶sub local_datapoint_data { (shift)->base_datapoint_values }
Subroutine local_datapoint_data: not called CC=1 SCAR=6.9
Pod documented
197 has 'base_datapoint_values', is => 'ro', isa => HashRef, lazy => 1, default => sub {
198 0 ▶ my $self = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
199 0 return { map { $_->name => $_->get_value($self) } $self->get_context_datapoints('base') };
200 12 };
201  
202 sub _init_datapoints {
203 15 ▶ my $self = shift;
Subroutine _init_datapoints: called CC=14 SCAR=26.6
204
205 15 my @configs = $self->_get_datapoint_configs;
206
207 15 ▶ if($self->rename_datapoints) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rename_datapoints) 8 7 15
208 8 my $rename = $self->rename_datapoints;
209
210 8 ▶ @{$self->datapoints} = map { $rename->{$_} || $_ } @{$self->datapoints};
Branch: 1 branch
BranchTrueFalseTotal
$rename->{$_} or $_ 52 36 88
211
212 8 foreach my $cnf (@configs) {
213 180 ▶ next unless (exists $rename->{$cnf->{name}});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$rename{$cnf->{"name"}} 132 48 180
214 48 $cnf->{original_name} = $cnf->{name};
215 48 $cnf->{name} = $rename->{$cnf->{name}};
216 }
217 }
218
219 15 my %seen = ();
220 15 ▶ $seen{$_}++ and die "Duplicate datapoint name '$_'" for (@{$self->datapoints});
Branch: 1 branch
BranchTrueFalseTotal
$seen{$_}++ and die "Duplicate datapoint name '${_}'" 0 152 152
221
222 15 my %disable = map {$_=>1} @{$self->disable_datapoints};
223 15 my %activ = map {$_=>1} grep { !$disable{$_} } @{$self->datapoints};
224
225 15 ▶ if($self->auto_include_user_defined_datapoints) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->auto_include_user_defined_datapoints) 15 0 15
226 15 ▶ $activ{$_->{name}} = 1 for(grep { $_->{name} && $_->{user_defined} } @configs);
Branch: 1 branch
BranchTrueFalseTotal
$_->{"name"} and $_->{"user_defined"} 334 0 334
227 }
228
229 15 foreach my $cnf (@configs) {
230 # Do this just to throw the exception for no name:
231 334 ▶ $self->add_datapoints($cnf) unless ($cnf->{name});
Branch: 1 branch
BranchTrueFalseTotal
unless $cnf->{"name"} 0 334 334
232
233 334 ▶ next unless $activ{$cnf->{name}};
Branch: 1 branch
BranchTrueFalseTotal
unless $activ{$cnf->{"name"}} 178 156 334
234 156 delete $activ{$cnf->{name}};
235 156 $self->add_datapoints({%$cnf, AuditObj => $self});
236 }
237
238 15 ▶ die "Unknown datapoint(s) specified (" . join(',',keys %activ) . ')'
Branch: 1 branch
BranchTrueFalseTotal
if scalar keys %activ > 0 0 15 15
239 if (scalar(keys %activ) > 0);
240 }
241  
242  
243 sub BUILD {
244 15 ▶ my $self = shift;
Subroutine BUILD: called CC=1 SCAR=0.0
Pod undocumented
245
246 # init all classes first:
247 15 $self->change_context_class;
248 15 $self->changeset_context_class;
249 15 $self->source_context_class;
250 15 $self->column_context_class;
251 15 $self->default_datapoint_class;
252
253 15 $self->_init_datapoints;
254 15 $self->_bind_schema;
255
256 # init collector object:
257 15 $self->collector;
258 }
259  
260  
261 sub _init_apply_schema_class {
262 15 ▶ my $self = shift;
Subroutine _init_apply_schema_class: called CC=3 SCAR=11.3
263 15 ▶ die "schema is not a reference" unless (ref $self->schema);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self->schema 0 15 15
264
265 Moo::Role->apply_roles_to_object($self->schema,'DBIx::Class::AuditAny::Role::Schema')
266 15 ▶ unless try{$self->schema->does('DBIx::Class::AuditAny::Role::Schema')};
Subroutine __ANON__: called CC=1 SCAR=0.2
Branch: 1 branch
BranchTrueFalseTotal
unless &try(sub { $self->schema->does("DBIx::Class::AuditAny::Role::Schema"); } ) 15 0 15
267
268 # Important!
269 15 $self->schema->_apply_storage_role;
270 }
271  
272  
273  
274  
275  
276 sub _bind_schema {
277 15 ▶ my $self = shift;
Subroutine _bind_schema: called CC=5 SCAR=17.8
278 15 $self->_init_apply_schema_class;
279
280 15 ▶ die "Supplied Schema instance already has a bound Auditor - to allow multple " .
Branch: 1 branch
BranchTrueFalseTotal
if $self->schema->auditor_count > 0 and not $self->allow_multiple_auditors 0 15 15
Condition33%1/3
$self->schema->auditor_count > 0 and not $self->allow_multiple_auditors
!ll&&!rl&&r
1500
MC/DC0%0/2
$self->schema->auditor_count > 0 and not $self->allow_multiple_auditors
$self->schema->auditor_count > 0 not $self->allow_multiple_auditors
Truth table33%1/3
A and not(B)
A= $self->schema->auditor_count > 0B= not $self->allow_multiple_auditors
ABresult
0X0
100
111
281 "Auditors, set 'allow_multiple_auditors' to true"
282 if($self->schema->auditor_count > 0 and ! $self->allow_multiple_auditors);
283
284 15 ▶ $_ == $self and return for($self->schema->auditors);
Branch: 1 branch
BranchTrueFalseTotal
$_ == $self and return 0 15 15
285
286 15 return $self->schema->add_auditor($self);
287 }
288  
289  
290  
291  
292 sub track_sources {
293 4 ▶ my ($self,@sources) = @_;
Subroutine track_sources: called CC=5 SCAR=16.3
Pod documented
294
295 4 foreach my $name (@sources) {
296 21 ▶ my $Source = $self->schema->source($name) or die "Bad Result Source name '$name'";
Branch: 1 branch
BranchTrueFalseTotal
my $Source = $self->schema->source($name) or die "Bad Result Source name '${name}'" 0 21 21
297
298 21 my $class = $self->source_context_class;
299 21 my $AuditSourceContext = $class->new(
300 AuditObj => $self,
301 ResultSource => $Source
302 );
303
304 21 my $source_name = $AuditSourceContext->source;
305
306 21 my %log_sources = map {$_=>1} @{$self->log_sources};
307 die "The Log Source (" . $source_name . ") cannot track itself!!"
308 21 ▶ if ($log_sources{$source_name});
Branch: 1 branch
BranchTrueFalseTotal
if $log_sources{$source_name} 0 21 21
309  
310 # Skip sources we've already setup:
311 21 ▶ return if ($self->tracked_sources->{$source_name});
Branch: 1 branch
BranchTrueFalseTotal
if $self->tracked_sources->{$source_name} 0 21 21
312
313 21 $self->_add_row_trackers_methods($AuditSourceContext);
314 21 $self->tracked_sources->{$source_name} = $AuditSourceContext;
315 }
316 }
317  
318 sub track_all_sources {
319 4 ▶ my ($self,@exclude) = @_;
Subroutine track_all_sources: called CC=3 SCAR=11.0
Pod documented
320 #$class->_init;
321
322 4 push @exclude, @{$self->log_sources};
323
324 # temp - auto exclude sources without exactly one primary key
325 4 foreach my $source_name ($self->schema->sources) {
326 24 my $Source = $self->schema->source($source_name);
327 24 ▶ push @exclude, $source_name unless (scalar($Source->primary_columns) == 1);
Branch: 1 branch
BranchTrueFalseTotal
unless scalar $Source->primary_columns == 1 0 24 24
328 }
329
330 4 my %excl = map {$_=>1} @exclude;
331 4 return $self->track_sources(grep { !$excl{$_} } $self->schema->sources);
332 }
333  
334 # This is the original, Row-based solution for initializing existing data. This
335 # is going to be refactored and replaced, but with what has not been decided yet
336 # See also _add_additional_row_methods() below
337 sub init_sources {
338 0 ▶ my ($self,@sources) = @_;
Subroutine init_sources: not called CC=1 SCAR=6.9
Pod documented
339
340 $self->schema->txn_do(sub {
341
342 0 ▶ foreach my $name (@sources) {
Subroutine __ANON__: not called CC=4 SCAR=30.0
343 0 ▶ my $SourceContext = $self->tracked_sources->{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $SourceContext = $self->tracked_sources->{$name} or die "Source '${name}' is not being tracked" 0 0 0
344 or die "Source '$name' is not being tracked";
345
346 0 print STDERR "\n";
347
348 0 my $msg = "Initializing Audit Records for $name: ";
349 0 print STDERR $msg . "\r";
350
351 0 my $Rs = $SourceContext->ResultSource->resultset;
352 0 my $total = $Rs->count;
353 0 my $count = 0;
354 0 foreach my $Row ($Rs->all) {
355 0 print STDERR $msg . ++$count . '/' . $total . "\r";
356 0 $Row->audit_init($self);
357 }
358 }
359
360 0 print STDERR "\n\n";
361 0 });
362 }
363  
364 sub init_all_sources {
365 0 ▶ my $self = shift;
Subroutine init_all_sources: not called CC=1 SCAR=6.9
Pod documented
366 0 $self->init_sources(keys %{$self->track_sources});
367 }
368  
369  
370 12 our $NESTED_CALL = 0;
371 sub _add_row_trackers_methods {
372 21 ▶ my $self = shift;
Subroutine _add_row_trackers_methods: called CC=3 SCAR=11.0
373 21 my $AuditSourceContext = shift;
374
375 21 my $source_name = $AuditSourceContext->source;
376 21 my $result_class = $self->schema->class($source_name);
377
378 21 foreach my $action (@{$self->track_actions}) {
379 63 my $func_name = $source_name . '::' . $action;
380 63 ▶ return if $self->tracked_action_functions->{$func_name}++;
Branch: 1 branch
BranchTrueFalseTotal
if $self->tracked_action_functions->{$func_name}++ 0 63 63
381 }
382
383 21 $self->_add_additional_row_methods($result_class);
384 }
385  
386  
387  
388 # TODO/FIXME: This needs to be refactored to use a cleaner API. Probably
389 # totally different (this code is leftover from before the switch to the
390 # Storage Role API)
391 sub _add_additional_row_methods {
392 21 ▶ my $self = shift;
Subroutine _add_additional_row_methods: called CC=6 SCAR=32.8
393 21 my $result_class = shift;
394
395 21 my $meta = Class::MOP::Class->initialize($result_class);
396 21 my $immutable = $meta->is_immutable;
397
398 21 ▶ die "Won't add tracker/modifier method to immutable Result Class '$result_class' " .
Branch: 1 branch
BranchTrueFalseTotal
if $immutable and not $self->track_immutable 0 21 21
Condition33%1/3
$immutable and not $self->track_immutable
!ll&&!rl&&r
2100
MC/DC0%0/2
$immutable and not $self->track_immutable
$immutable not $self->track_immutable
Truth table33%1/3
A and not(B)
A= $immutableB= not $self->track_immutable
ABresult
0X0
100
111
399 '(hint: did you forget to remove __PACKAGE__->meta->make_immutable ??)' .
400 ' - to force/override, set "track_immutable" to true.'
401 if ($immutable && !$self->track_immutable);
402
403 # Tempory turn mutable back on, saving any immutable_options, first:
404 21 my %immut_opts = ();
405 21 ▶ if($immutable) {
Branch: 1 branch
BranchTrueFalseTotal
if ($immutable) 0 21 21
406 0 %immut_opts = $meta->immutable_options;
407 0 $meta->make_mutable;
408 }
409
410 21 ▶ return if ($meta->has_method('audit_take_snapshot'));
Branch: 1 branch
BranchTrueFalseTotal
if $meta->has_method("audit_take_snapshot") 3 18 21
411
412 $meta->add_method( audit_take_snapshot => sub {
413 0 ▶ my $Row = shift;
Subroutine __ANON__: not called CC=8 SCAR=42.8
Subroutine audit_take_snapshot: not called CC=8 SCAR=42.8
414 0 ▶ my $AuditObj = shift or die "AuditObj not supplied in argument.";
Branch: 2 branches
BranchTrueFalseTotal
my $AuditObj = shift() or die "AuditObj not supplied in argument." 0 0 0
my $AuditObj = shift() or die "AuditObj not supplied in argument." 0 0 0
415
416 0 ▶ my $Auditors = $Row->result_source->schema->auditors || [];
Condition0%0/4
$Row->result_source->schema->auditors || []
l!l
00
$Row->result_source->schema->auditors || []
l!l
00
MC/DC0%0/1
$Row->result_source->schema->auditors || []
$Row->result_source->schema->auditors
MC/DC0%0/1
$Row->result_source->schema->auditors || []
$Row->result_source->schema->auditors
Truth table0%0/2
A
A= $Row->result_source->schema->auditors
Aresult
11
00
Truth table0%0/2
A
A= $Row->result_source->schema->auditors
Aresult
11
00
417 0 my $found = 0;
418 0 ▶ $_ == $AuditObj and $found = 1 for (@$Auditors);
Branch: 2 branches
BranchTrueFalseTotal
$_ == $AuditObj and $found = 1 0 0 0
$_ == $AuditObj and $found = 1 0 0 0
419 0 ▶ die "Supplied AuditObj is not an active Auditor on this Row's schema instance"
Branch: 2 branches
BranchTrueFalseTotal
unless $found 0 0 0
unless $found 0 0 0
420 unless ($found);
421
422 0 my $source_name = $Row->result_source->source_name;
423 0 ▶ my $SourceContext = $AuditObj->tracked_sources->{$source_name}
Branch: 2 branches
BranchTrueFalseTotal
my $SourceContext = $AuditObj->tracked_sources->{$source_name} or die "Source '${source_name}' is not being tracked by the supplied Auditor" 0 0 0
my $SourceContext = $AuditObj->tracked_sources->{$source_name} or die "Source '${source_name}' is not being tracked by the supplied Auditor" 0 0 0
424 or die "Source '$source_name' is not being tracked by the supplied Auditor";
425
426 0 ▶ unless ($AuditObj->active_changeset) {
Branch: 2 branches
BranchTrueFalseTotal
unless ($AuditObj->active_changeset) 0 0 0
unless ($AuditObj->active_changeset) 0 0 0
427 0 $AuditObj->start_changeset;
428 0 $AuditObj->auto_finish(1);
429 }
430
431 0 my $class = $AuditObj->change_context_class;
432 0 my $ChangeContext = $class->new(
433 AuditObj => $AuditObj,
434 SourceContext => $SourceContext,
435 ChangeSetContext => $AuditObj->active_changeset,
436 #Row => $Row,
437 old_columns => $self->_get_old_columns($Row),
438 action => 'select'
439 );
440 0 $ChangeContext->record;
441 0 $AuditObj->record_changes($ChangeContext);
442 0 return $Row;
443 18 });
444
445 $meta->add_method( audit_init => sub {
446 0 ▶ my $Row = shift;
Subroutine audit_init: not called CC=7 SCAR=40.3
447 0 ▶ my $AuditObj = shift or die "AuditObj not supplied in argument.";
Branch: 1 branch
BranchTrueFalseTotal
my $AuditObj = shift() or die "AuditObj not supplied in argument." 0 0 0
448
449 0 ▶ my $Auditors = $Row->result_source->schema->auditors || [];
Condition0%0/2
$Row->result_source->schema->auditors || []
l!l
00
MC/DC0%0/1
$Row->result_source->schema->auditors || []
$Row->result_source->schema->auditors
Truth table0%0/2
A
A= $Row->result_source->schema->auditors
Aresult
11
00
450 0 my $found = 0;
451 0 ▶ $_ == $AuditObj and $found = 1 for (@$Auditors);
Branch: 1 branch
BranchTrueFalseTotal
$_ == $AuditObj and $found = 1 0 0 0
452 0 ▶ die "Supplied AuditObj is not an active Auditor on this Row's schema instance"
Branch: 1 branch
BranchTrueFalseTotal
unless $found 0 0 0
453 unless ($found);
454
455 0 my $Collector = $AuditObj->collector;
456 0 ▶ return $Row->audit_take_snapshot($AuditObj) unless ($Collector->has_full_row_stored($Row));
Branch: 1 branch
BranchTrueFalseTotal
unless $Collector->has_full_row_stored($Row) 0 0 0
457 0 return $Row;
458 18 });
459
460 # Restore immutability to the way to was:
461 18 ▶ $meta->make_immutable(%immut_opts) if ($immutable);
Branch: 1 branch
BranchTrueFalseTotal
if $immutable 0 18 18
462 }
463  
464  
465 ##########
466 ##########
467  
468 # Starts a new changeset if there isn't one active:
469 sub start_unless_changeset {
470 0 ▶ my $self = shift;
Subroutine start_unless_changeset: not called CC=2 SCAR=17.9
Pod documented
471 0 ▶ return $self->active_changeset ? undef : $self->start_changeset;
Branch: 1 branch
BranchTrueFalseTotal
$self->active_changeset ? : 0 0 0
472 }
473  
474 sub start_changeset {
475 0 ▶ my $self = shift;
Subroutine start_changeset: not called CC=2 SCAR=17.9
Pod documented
476 0 ▶ die "Cannot start_changeset because a changeset is already active" if ($self->active_changeset);
Branch: 1 branch
BranchTrueFalseTotal
if $self->active_changeset 0 0 0
477
478 0 my $class = $self->changeset_context_class;
479 0 $self->active_changeset($class->new( AuditObj => $self ));
480 0 return $self->active_changeset;
481 }
482  
483 sub finish_if_changeset {
484 0 ▶ my $self = shift;
Subroutine finish_if_changeset: not called CC=2 SCAR=17.9
Pod documented
485 0 ▶ return $self->active_changeset ? $self->finish_changeset : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->active_changeset ? : 0 0 0
486 }
487  
488 15 ▶has '_finishing_changeset', is => 'rw', isa => Bool, default => sub{0};
Subroutine __ANON__: called CC=1 SCAR=0.0
489 sub finish_changeset {
490 0 ▶ my $self = shift;
Subroutine finish_changeset: not called CC=6 SCAR=37.4
Pod documented
491 0 ▶ die "Cannot finish_changeset because there isn't one active" unless ($self->active_changeset);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->active_changeset 0 0 0
492
493 # Protect against deep recursion. This is needed for cases where the collector
494 # is writing to tables within the tracked schema
495 0 ▶ return if ($self->_finishing_changeset);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_finishing_changeset 0 0 0
496 0 $self->_finishing_changeset(1);
497
498 0 ▶ unless($self->record_empty_changes) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->record_empty_changes) 0 0 0
499 0 my $count_cols = 0;
500 $count_cols = $count_cols + scalar($_->all_column_changes)
501 0 for (@{$self->active_changeset->changes});
502 0 ▶ unless ($count_cols > 0) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($count_cols > 0) 0 0 0
503 0 $self->clear_changeset;
504 0 return 1;
505 }
506 }
507
508 0 $self->active_changeset->finish;
509
510 #####
511 0 $self->collector->record_changes($self->active_changeset);
512 #####
513
514 0 $self->clear_changeset;
515 0 return 1;
516 }
517  
518 sub _exception_cleanup {
519 0 ▶ my $self = shift;
Subroutine _exception_cleanup: not called CC=1 SCAR=6.9
520 0 my $err = shift;
521 0 $self->clear_changeset;
522 0 $self->_current_change_group([]);
523 }
524  
525 sub clear_changeset {
526 0 ▶ my $self = shift;
Subroutine clear_changeset: not called CC=1 SCAR=6.9
Pod documented
527 0 $self->active_changeset(undef);
528 0 $self->auto_finish(0);
529 0 $self->_finishing_changeset(0);
530 }
531  
532 sub record_changes {
533 0 ▶ my ($self, @ChangeContexts) = @_;
Subroutine record_changes: not called CC=3 SCAR=24.8
Pod documented
534
535 0 my $local_changeset = $self->start_unless_changeset;
536
537 0 $self->active_changeset->add_changes($_) for (@ChangeContexts);
538
539 0 ▶ $self->finish_changeset if ($local_changeset);
Branch: 1 branch
BranchTrueFalseTotal
if $local_changeset 0 0 0
540 }
541  
542  
543 ## Change 'group' vs Change 'set'
544 #
545 # I am using the term 'group' (to distinguish from 'set') to represent a group
546 # of changes (rows) that are being changed within a single query/sql statement.
547 # (vs. set which is any number of query/sql statements grouped in a transaction)
548 # This should only happen from making changes via ResultSet objects instead of
549 # Row objects, and in these cases we normalize these into individual (row) changes
550 # TODO: should ChangeGroup be made into a 6th Context? For now, I think no because
551 # it is overkill.
552 ##
553  
554 # -- This is a glorified tmp variable used just to allow groups of changes
555 # to be associated with the correct auditor. TODO: This is probably a
556 # poor solution to a complex scoping problem. This exposes us to the
557 # risk of processing stale data, so we have to be sure (manually) to keep
558 # this clear/empty outside its *very* short lifespan, by regularly resetting it
559 15 ▶has '_current_change_group', is => 'rw', isa => ArrayRef[Object], default => sub{[]};
Subroutine __ANON__: called CC=1 SCAR=0.0
560 # --
561  
562 sub _start_current_change_group {
563 4 ▶ my ($self, $Source, $nested, $action, @changes) = @_;
Subroutine _start_current_change_group: called CC=4 SCAR=14.0
564
565 4 ▶ my $Group = $self->_current_change_group || [];
Condition50%1/2
$self->_current_change_group || []
l!l
40
MC/DC0%0/1
$self->_current_change_group || []
$self->_current_change_group
Truth table50%1/2
A
A= $self->_current_change_group
Aresult
11
00
566 4 ▶ $Group = [] unless ($nested);
Branch: 1 branch
BranchTrueFalseTotal
unless $nested 4 0 4
567
568 4 $self->_current_change_group($Group); # just for good measure
569
570 4 my $source_name = $Source->source_name;
571 4 my $func_name = $source_name . '::' . $action;
572
573 4 ▶ return () unless ($self->tracked_action_functions->{$func_name});
Branch: 1 branch
BranchTrueFalseTotal
unless $self->tracked_action_functions->{$func_name} 0 4 4
574
575 my @ChangeContexts = map {
576 4 $self->_new_change_context(
577 AuditObj => $self,
578 4 SourceContext => $self->tracked_sources->{$source_name},
579 ChangeSetContext => $self->active_changeset, # could be undef
580 action => $action,
581 $self->_validated_change_hash($_)
582 )
583 } @changes;
584
585 4 push @$Group, @ChangeContexts;
586 4 $self->_current_change_group($Group);
587 4 return @ChangeContexts;
588 }
589  
590 sub _validated_change_hash {
591 4 ▶ my ($self, $data) = @_;
Subroutine _validated_change_hash: called CC=5 SCAR=17.0
592
593 4 require Data::Dumper::Concise;
594
595 4 ▶ die "change data must be a HashRef:\n" .
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 4 4
596 Data::Dumper::Concise::Dumper($data) unless (ref($data) eq 'HASH');
597
598 4 my %allowed_keys = map {$_=>1} qw(old_columns to_columns new_columns);
599
600 $allowed_keys{$_} && ref($data->{$_}) eq 'HASH' or
601 die "Bad data in change hash:\n" . Data::Dumper::Concise::Dumper($data)
602 4 ▶ for (grep { $_ ne 'condition' } keys %$data);
Branch: 1 branch
BranchTrueFalseTotal
$allowed_keys{$_} and ref $data->{$_} eq "HASH" or die "Bad data in change hash:\n" . Data::Dumper::Concise::Dumper($data) 0 4 4
Condition33%1/3
$allowed_keys{$_} and ref $data->{$_} eq "HASH"
!ll&&!rl&&r
004
MC/DC0%0/2
$allowed_keys{$_} and ref $data->{$_} eq "HASH"
$allowed_keys{$_} ref $data->{$_} eq "HASH"
Truth table33%1/3
A and B
A= $allowed_keys{$_}B= ref $data->{$_} eq "HASH"
ABresult
0X0
100
111
603  
604 4 return %$data;
605 }
606  
607  
608 sub _finish_current_change_group {
609 0 ▶ my $self = shift;
Subroutine _finish_current_change_group: not called CC=2 SCAR=17.9
610 0 ▶ $self->record_changes(@{$self->_current_change_group || []});
Branch: 1 branch
BranchTrueFalseTotal
$self->_current_change_group or [] 0 0 0
611 0 $self->_current_change_group([]); #<-- critical to reset!
612 }
613  
614 # factory-like helper:
615 sub _new_change_context {
616 4 ▶ my $self = shift;
Subroutine _new_change_context: called CC=1 SCAR=0.0
617 4 my $class = $self->change_context_class;
618 4 return $class->new(@_);
619 }
620  
621  
622  
623 12 1;
624  
625  
626 __END__
627  
628 =head1 NAME
629  
630 DBIx::Class::AuditAny - Flexible change tracking framework for L<DBIx::Class>
631  
632 =begin HTML
633  
634 <a href='https://coveralls.io/r/vanstyn/DBIx-Class-AuditAny?branch=master'>
635 <img
636 src='https://coveralls.io/repos/vanstyn/DBIx-Class-AuditAny/badge.svg?branch=master'
637 alt='Coverage Status'
638 />
639 </a>
640  
641 =end HTML
642  
643 =head1 SYNOPSIS
644  
645 my $schema = My::Schema->connect(@connect);
646  
647 use DBIx::Class::AuditAny;
648  
649 my $Auditor = DBIx::Class::AuditAny->track(
650 schema => $schema,
651 track_all_sources => 1,
652 collector_class => 'Collector::AutoDBIC',
653 collector_params => {
654 sqlite_db => 'db/audit.db',
655 }
656 );
657  
658 =head1 DESCRIPTION
659  
660 This module provides a generalized way to track changes to DBIC databases. The aim is
661 to provide quick/turn-key options to be able to hit the ground running, while also
662 being highly flexible and customizable with sane APIs.
663  
664 C<DBIx::Class::AuditAny> wants to be a general framework on top of which other Change
665 Tracking modules for DBIC can be written, while also providing fully fleshed, end-user
666 solutions that can be dropped in and work out-of-the-box.
667  
668 =head2 Background
669  
670 This module was originally written in 2012 for an internal client project, and the process
671 of getting it released open-source as a stand-alone, general-purpose module was started in
672 2013. However, I got busy with other projects and wasn't able to complete a CPAN release at
673 that time (mainly due to missing docs and minor loose ends). I finally came back to this
674 project (May 2015) to actually get a release out to CPAN. So, even though the release date
675 is in 2015, the majority of the code is actually several years old (and has been running
676 perfectly in production for several client apps the whole time).
677  
678  
679 =head2 API and Usage
680  
681 AuditAny uses a different API than typical DBIC components. Instead of loading at the
682 schema/result class level with C<load_components>, AuditAny is used by attaching an
683 "Auditor" to an existing schema I<object> instance:
684  
685 my $schema = My::Schema->connect(@connect);
686
687 my $Auditor = DBIx::Class::AuditAny->track(
688 schema => $schema,
689 track_all_sources => 1,
690 collector_class => 'Collector::AutoDBIC',
691 collector_params => {
692 sqlite_db => 'db/audit.db',
693 }
694 );
695  
696 The rationale of this approach is that change tracking isn't necessarily something that
697 needs to be, or should be, defined as a built-in attribute of the schema class.
698 Additionally, because of the object-based approach, it is possible to attach multiple
699 Auditors to a single schema object with multiple calls to DBIx::Class::AuditAny->track.
700  
701 =head1 DATAPOINTS
702  
703 As changes occur in the tracked schema, information is collected in the form of
704 I<datapoints> at various stages - or I<contexts> - before being passed to the
705 configured Collector. A datapoint has a globally unique name and code used to calculate
706 its value. Code is called at the stage defined by the I<context> of the datapoint.
707 The available contexts are:
708  
709 =over 4
710  
711 =item set
712  
713 =over 5
714  
715 =item base
716  
717 =back
718  
719 =item change
720  
721 =over 5
722  
723 =item source
724  
725 =back
726  
727 =item column
728  
729  
730 =back
731  
732 B<set> (AKA changeset) datapoints are specific to an entire set of changes - insert/
733 update/delete statements grouped in a transaction. Example changeset datapoints include
734 C<changeset_ts> and other broad items. B<base> datapoints are logically the same as
735 B<set> but only need to be calculated once (instead of with every change set). These
736 include things like C<schema> and C<schema_ver>.
737  
738 B<change> datapoints apply to a specific C<insert>, C<update> or C<delete> statement,
739 and range from simple items such as C<action> (one of 'insert', 'update' or 'delete')
740 to more exotic and complex items like C<column_changes_json>. B<source> datapoints are
741 logically the same as B<change>, but like B<base> datapoints, only need to be
742 calculated once (per source). These include things like C<table_name> and C<source>
743 (source name).
744  
745 Finally, B<column> datapoints cover information specific to an individual column, such
746 as C<column_name>, C<old_value> and C<new_value>.
747  
748 There are a number of built-in datapoints (currently stored in
749 L<DBIx::Class::AuditAny::Util::BuiltinDatapoints> which is likely to change), but custom
750 datapoints can also be defined. The Auditor config defines a specific set of datapoints to
751 be calculated (built-in and/or custom). If no datapoints are specified, the default list is used
752 (currently C<change_ts, action, source, pri_key_value, column_name, old_value, new_value>).
753  
754 The list of datapoints is specified as an ArrayRef in the config. For example:
755  
756 datapoints => [qw(action_id column_name new_value)],
757  
758 =head2 Custom Datapoints
759  
760 Custom datapoints are specified as HashRef configs with 3 parameters:
761  
762 =over 4
763  
764 =item name
765  
766 The unique name of the datapoint. Should be all lowercase letters, numbers and
767 underscore and must be different from all other datapoints (across all contexts).
768  
769 =item context
770  
771 The context of the datapoint: base, source, set, change or column.
772  
773 =item method
774  
775 CodeRef to calculate and return the value. The CodeRef is called according to the
776 context, and a different context object is supplied for each context. Each context has
777 its own context object type except B<base> which is supplied the Auditor object itself.
778 See Audit Context Objects below.
779  
780 =back
781  
782  
783 Custom datapoints are defined in the C<datapoint_configs> param. After defining a new
784 datapoint config it can then be used like any other datapoint. For example:
785  
786 datapoints => [qw(action_id column_name new_value client_ip)],
787 datapoint_configs => [
788 {
789 name => 'client_ip',
790 context => 'set',
791 method => sub {
792 my $contextObj = shift;
793 my $c = some_func(...);
794 return $c->req->address;
795 }
796 }
797 ]
798  
799 =head2 Datapoint Names
800  
801 Datapoint names must be unique, which means all the built-in datapoint names are
802 reserved. However, if you really want to use an existing datapoint name, or if you want
803 a built-in datapoint to use a different name, you can rename any datapoints like so:
804  
805 rename_datapoints => {
806 new_value => 'new',
807 old_value => 'old',
808 column_name => 'column',
809 },
810  
811 =head1 COLLECTORS
812  
813 Once the Auditor calculates the configured datapoints it passes them to the configured
814 I<Collector>. There are several built-in Collectors provided, but writing a custom Collector
815 is a trivial matter. All you need to do is write a L<Moo>-compatible class which consumes
816 the L<DBIx::Class::AuditAny::Role::Collector> role and implement a C<record_changes()> method.
817 This method is called with a L<ChangeSet|DBIx::Class::AuditAny::AuditContext::ChangeSet> object
818 supplied as the argument at the end of every database transaction which performs a write operation.
819  
820 No matter how small or large the transaction, the ChangeSet object provides APIs to a nested
821 structure to be able to access all information regarding what changed during the given transaction.
822 (See L<AUDIT CONTEXT OBJECTS|DBIx::Class::AuditAny#AUDIT_CONTEXT_OBJECTS> below).
823  
824  
825 =head2 Supplied Collector Classes
826  
827 The following built-in collector classes are already provided:
828  
829 =over
830  
831 =item *
832  
833 L<DBIx::Class::AuditAny::Collector::AutoDBIC>
834  
835 =item *
836  
837 L<DBIx::Class::AuditAny::Collector::DBIC>
838  
839 =item *
840  
841 L<DBIx::Class::AuditAny::Collector::Code>
842  
843 =back
844  
845 =head1 AUDIT CONTEXT OBJECTS
846  
847 Inspired in part by the Catalyst Context object design, the internal machinery which captures and
848 organizes the change datapoints associated with a modifying transaction is wrapped in a nested
849 structure of 3 kinds of "context" objects:
850  
851 =over
852  
853 =item *
854  
855 L<DBIx::Class::AuditAny::AuditContext::ChangeSet>
856  
857 =item *
858  
859 L<DBIx::Class::AuditAny::AuditContext::Change>
860  
861 =item *
862  
863 L<DBIx::Class::AuditAny::AuditContext::Column>
864  
865 =back
866  
867 This provides a clean and straightforward API for which Collector classes are able to identify and
868 act on the data in any manner they want, be it recording to a database, logging to a simple file,
869 or taking any kind of programmatic action. Collectors can really be thought of as a structure for
870 powerful external triggers.
871  
872 =head1 ATTRIBUTES
873  
874 Note: Documentation of all the individual attrs and methods of this class (shown below) is still
875 TBD. However, most meaningful scenarios involving interacting with these is already covered above,
876 or is covered further down in the L<Examples|DBIx::Class::AuditAny#EXAMPLES>.
877  
878 =head2 datapoints
879  
880 =head2 allow_multiple_auditors
881  
882 =head2 auto_include_user_defined_datapoints
883  
884 =head2 build_init_args
885  
886 =head2 calling_action_function
887  
888 =head2 change_context_class
889  
890 =head2 changeset_context_class
891  
892 =head2 collector_class
893  
894 =head2 collector_params
895  
896 =head2 column_context_class
897  
898 =head2 datapoint_configs
899  
900 =head2 default_datapoint_class
901  
902 =head2 disable_datapoints
903  
904 =head2 primary_key_separator
905  
906 =head2 record_empty_changes
907  
908 =head2 rename_datapoints
909  
910 =head2 schema
911  
912 =head2 source_context_class
913  
914 =head2 time_zone
915  
916 =head2 track_actions
917  
918 =head2 track_immutable
919  
920 =head2 track_init_args
921  
922 =head2 tracked_action_functions
923  
924 =head2 tracked_sources
925  
926 =head1 METHODS
927  
928 =head2 get_dt
929  
930 =head2 track
931  
932 =head2 get_datapoint_orig
933  
934 =head2 add_datapoints
935  
936 =head2 all_datapoints
937  
938 =head2 get_context_datapoint_names
939  
940 =head2 get_context_datapoints
941  
942 =head2 local_datapoint_data
943  
944 =head2 track_sources
945  
946 =head2 track_all_sources
947  
948 =head2 init_all_sources
949  
950 =head2 init_sources
951  
952 =head2 start_unless_changeset
953  
954 =head2 start_changeset
955  
956 =head2 finish_changeset
957  
958 =head2 finish_if_changeset
959  
960 =head2 clear_changeset
961  
962 =head2 record_changes
963  
964  
965 =head1 EXAMPLES
966  
967 =head3 simple dedicated audit db
968  
969 Record all changes into a *separate*, auto-generated and initialized SQLite schema/db
970 with default datapoints (Quickest/simplest usage - SYNOPSIS example):
971  
972 Uses the Collector L<DBIx::Class::AuditAny::Collector::AutoDBIC>
973  
974 my $schema = My::Schema->connect(@connect);
975  
976 use DBIx::Class::AuditAny;
977  
978 my $Auditor = DBIx::Class::AuditAny->track(
979 schema => $schema,
980 track_all_sources => 1,
981 collector_class => 'Collector::AutoDBIC',
982 collector_params => {
983 sqlite_db => 'db/audit.db',
984 }
985 );
986  
987 =head3 recording to the same db
988  
989 Record all changes - into specified target sources within the *same*/tracked
990 schema - using specific datapoints:
991  
992 Uses the Collector L<DBIx::Class::AuditAny::Collector::DBIC>
993  
994 DBIx::Class::AuditAny->track(
995 schema => $schema,
996 track_all_sources => 1,
997 collector_class => 'Collector::DBIC',
998 collector_params => {
999 target_source => 'MyChangeSet', # ChangeSet source name
1000 change_data_rel => 'changes', # Change source, via rel within ChangeSet
1001 column_data_rel => 'change_columns', # ColumnChange source, via rel within Change
1002 },
1003 datapoints => [ # predefined/built-in named datapoints:
1004 (qw(changeset_ts changeset_elapsed)),
1005 (qw(change_elapsed action source pri_key_value)),
1006 (qw(column_name old_value new_value)),
1007 ],
1008 );
1009
1010  
1011 =head3 coderef collector to a file
1012  
1013 Dump raw change data for specific sources (Artist and Album) to a file,
1014 ignore immutable flags in the schema/result classes, and allow more than
1015 one DBIx::Class::AuditAny Auditor to be attached to the same schema object:
1016  
1017 Uses 'collect' sugar param to setup a bare-bones CodeRef Collector
1018 (L<DBIx::Class::AuditAny::Role::Collector>)
1019  
1020 my $Auditor = DBIx::Class::AuditAny->track(
1021 schema => $schema,
1022 track_sources => [qw(Artist Album)],
1023 track_immutable => 1,
1024 allow_multiple_auditors => 1,
1025 collect => sub {
1026 my $cntx = shift; # ChangeSet context object
1027 require Data::Dumper;
1028 print $fh Data::Dumper->Dump([$cntx],[qw(changeset)]);
1029
1030 # Do other custom stuff...
1031 }
1032 );
1033  
1034 =head3 more customizations
1035  
1036 Record all updates (but *not* inserts/deletes) - into specified target sources
1037 within the same/tracked schema - using specific datapoints, including user-defined
1038 datapoints and built-in datapoints with custom names:
1039  
1040 DBIx::Class::AuditAny->track(
1041 schema => CoolCatalystApp->model('Schema')->schema,
1042 track_all_sources => 1,
1043 track_actions => [qw(update)],
1044 collector_class => 'Collector::DBIC',
1045 collector_params => {
1046 target_source => 'MyChangeSet', # ChangeSet source name
1047 change_data_rel => 'changes', # Change source, via rel within ChangeSet
1048 column_data_rel => 'change_columns', # ColumnChange source, via rel within Change
1049 },
1050 datapoints => [
1051 (qw(changeset_ts changeset_elapsed)),
1052 (qw(change_elapsed action_id table_name pri_key_value)),
1053 (qw(column_name old_value new_value)),
1054 ],
1055 datapoint_configs => [
1056 {
1057 name => 'client_ip',
1058 context => 'set',
1059 method => sub {
1060 my $c = some_func(...);
1061 return $c->req->address;
1062 }
1063 },
1064 {
1065 name => 'user_id',
1066 context => 'set',
1067 method => sub {
1068 my $c = some_func(...);
1069 $c->user->id;
1070 }
1071 }
1072 ],
1073 rename_datapoints => {
1074 changeset_elapsed => 'total_elapsed',
1075 change_elapsed => 'elapsed',
1076 pri_key_value => 'row_key',
1077 new_value => 'new',
1078 old_value => 'old',
1079 column_name => 'column',
1080 },
1081 );
1082  
1083  
1084 =head3 user-defined collector
1085  
1086 Record all changes into a user-defined custom Collector class - using
1087 default datapoints:
1088  
1089 my $Auditor = DBIx::Class::AuditAny->track(
1090 schema => $schema,
1091 track_all_sources => 1,
1092 collector_class => '+MyApp::MyCollector',
1093 collector_params => {
1094 foo => 'blah',
1095 anything => $val
1096 }
1097 );
1098  
1099 =head3 query the audit db
1100  
1101 Access/query the audit db of Collector::DBIC and Collector::AutoDBIC collectors:
1102  
1103 my $audit_schema = $Auditor->collector->target_schema;
1104 $audit_schema->resultset('AuditChangeSet')->search({...});
1105
1106 # Print the ddl that auto-generated and deployed with a Collector::AutoDBIC collector:
1107 print $audit_schema->resultset('DeployInfo')->first->deployed_ddl;
1108  
1109 =head2 more examples
1110  
1111 See the unit tests (which are extensive) for more examples.
1112  
1113  
1114 =head1 TODO
1115  
1116 =over
1117  
1118 =item *
1119  
1120 Enable tracking multi-primary-key sources (code currently disabled)
1121  
1122 =item *
1123  
1124 Write more tests
1125  
1126 =item *
1127  
1128 Write more documentation
1129  
1130 =item *
1131  
1132 Add more built-in datapoints
1133  
1134 =item *
1135  
1136 Expand the Collector API to be able to provide datapoint configs
1137  
1138 =item *
1139  
1140 Separate set/change/column datapoints into 'pre' and 'post' stages
1141  
1142 =item *
1143  
1144 Add mechanism to enable/disable tracking (localizable global?)
1145  
1146 =item *
1147  
1148 Switch to use L<Types::Standard>
1149  
1150 =back
1151  
1152 =head1 SIMILAR MODULES
1153  
1154 =head2 DBIx::Class::Journal
1155  
1156 L<DBIx::Class::Journal> was the first DBIC change tracking module released to CPAN. It works,
1157 but is inflexible and mandates a single mode of operation, which is not ideal in many ways.
1158  
1159 =head2 DBIx::Class::AuditLog
1160  
1161 L<DBIx::Class::AuditLog> takes a more casual approach than L<DBIx::Class::Journal>, which makes
1162 it easier to work with. However, it still forces a narrow and specific manner in which it stores
1163 the change history data which doesn't fit all workflows.
1164  
1165 AuditAny was designed specifically for flexibility. By separating the I<Auditor> - which captures the
1166 change data as it happens - from the I<Collector>, which handles storing the data, all sorts of
1167 different styles and manners of formatting and storing the audit data can be achieved. In fact,
1168 L<DBIx::Class::AuditLog> could be written using AuditAny, and store the data in exactly the same
1169 manner by implementing a custom collector class.
1170  
1171 =head2 DBIx::Class::Shadow
1172  
1173 Shadow is a different animal. It is very sophisticated, and places accuracy above all else, with the
1174 idea of being able to do things such as reliably "revive" the previous state of rows, etc. The
1175 downside of this is that it is also not flexible, in that it handles the entire change life cycle
1176 within its logic. This is different from AuditAny, which is more like a packet capture lib for DBIC
1177 (like tcpdump/libpcap is a packet capture lib for networks). Unlike the others, Shadow could B<not>
1178 be implemented using AuditAny, because the I<way> it captures the change data is specific and
1179 fundamentally different.
1180  
1181 Unfortunately, DBIx::Class::Shadow is unfinished and has never been released to CPAN (as of the time
1182 of this writing, in May 2015). Its current, unfinished status can be seen in GitHub:
1183  
1184 =over
1185  
1186 =item *
1187  
1188 L<https://github.com/ribasushi/preshadow>
1189  
1190 =back
1191  
1192  
1193 =head1 SUPPORT
1194
1195 IRC:
1196
1197 Join #rapidapp on irc.perl.org.
1198  
1199 =head1 AUTHOR
1200  
1201 Henry Van Styn <vanstyn@cpan.org>
1202  
1203 =head1 COPYRIGHT AND LICENSE
1204  
1205 This software is copyright (c) 2012-2015 by IntelliTree Solutions llc.
1206  
1207 This is free software; you can redistribute it and/or modify it under
1208 the same terms as the Perl 5 programming language system itself.
1209  
1210 =cut
1211  
« AuditAny/Role/Storage.pm ↑ Summary AuditAny/AuditContext/Change.pm »