46f69634eb7aec96671533dc3c14c5190994151d
[dbsrgits/DBIx-Class-Journal.git] / lib / DBIx / Class / Schema / Journal.pm
1 package DBIx::Class::Schema::Journal;
2
3 use base qw/DBIx::Class/;
4
5 use Scalar::Util 'blessed';
6
7 __PACKAGE__->mk_classdata('journal_storage_type');
8 __PACKAGE__->mk_classdata('journal_connection');
9 __PACKAGE__->mk_classdata('journal_sources'); ## [ source names ]
10 __PACKAGE__->mk_classdata('journal_user'); ## [ class, field for user id ]
11 __PACKAGE__->mk_classdata('_journal_schema');
12
13 sub load_classes
14 {
15     my $self = shift;
16     $self->next::method(@_);
17
18     my $journal_schema = (__PACKAGE__ . '::DB')->connect($self->journal_connection || $self->storage->connect_info);
19     if($self->journal_storage_type)
20     {
21         $journal_schema->storage_type($self->journal_storage_type);
22     }
23
24     ## get our own private version of the journaling sources
25     $self->_journal_schema($journal_schema->compose_namespace(blessed($self) . '::Journal'));
26
27     my %j_sources = @{$self->journal_sources} ? map { $_ => 1 } @{$self->journal_sources} : map { $_ => 1 } $self->sources;
28     foreach my $s_name ($self->sources)
29     {
30         next unless($j_sources{$s_name});
31         $self->create_journal_for($s_name);
32     }
33
34     ## Set up relationship between changeset->user_id and this schema's user
35     if(!@{$self->journal_user})
36     {
37         warn "No Journal User set!";
38         return;
39     }
40
41     ## get our own private version of the journaling sources
42     $self->_journal_schema->compose_namespace(blessed($self) . '::Journal');
43     DBIx::Class::Schema::Journal::DB::ChangeSet->belongs_to('user', @{$self->journal_user});
44 }
45
46 sub get_audit_log_class_name
47 {
48     my ($self, $sourcename) = @_;
49
50     return blessed($self->_journal_schema) . "::${sourcename}AuditLog";
51 }
52
53 sub get_audit_history_class_name
54 {
55     my ($self, $sourcename) = @_;
56
57     return blessed($self->_journal_schema) . "::${sourcename}AuditHistory";
58 }
59
60 sub create_journal_for
61 {
62     my ($self, $s_name) = @_;
63
64     my $source = $self->source($s_name);
65     my $newclass = $self->get_audit_log_class_name($s_name);
66     DBIx::Class::Componentised->inject_base($newclass, 'DBIx::Class::Schema::Journal::DB::AuditLog');
67     $newclass->table(lc($s_name) . "_audit_log");
68                            
69
70     my $histclass = $self->get_audit_hisory_class_name($s_name);
71     DBIx::Class::Componentised->inject_base($histclass, 'DBIx::Class::Schema::Journal::DB::AuditHistory');
72     $histclass->table(lc($s_name) . "_audit_hisory");
73     $histclass->add_columns(
74                             map { $_ => $source->column_info($_) } $source->columns
75                            );
76                            
77 }
78
79 1;