release v0.900201
[dbsrgits/DBIx-Class-Journal.git] / lib / DBIx / Class / Schema / Journal / DB.pm
CommitLineData
f0f14c64 1package DBIx::Class::Schema::Journal::DB;
2
3use base 'DBIx::Class::Schema';
4
aba93491 5__PACKAGE__->mk_classdata('nested_changesets');
6__PACKAGE__->mk_group_accessors( simple => 'current_user' );
7__PACKAGE__->mk_group_accessors( simple => 'current_session' );
8__PACKAGE__->mk_group_accessors( simple => '_current_changeset_container' );
9
30a4f241 10require DBIx::Class::Schema::Journal::DB::AuditLog;
59c8adb5 11require DBIx::Class::Schema::Journal::DB::AuditHistory;
5b64dcdc 12require DBIx::Class::Schema::Journal::DB::ChangeLog;
13require DBIx::Class::Schema::Journal::DB::ChangeSet;
fd45c476 14
15sub _current_changeset {
16 my $self = shift;
17 my $ref = $self->_current_changeset_container;
18 $ref && $ref->{changeset};
19}
20
aba93491 21# this is for localization of the current changeset
22sub current_changeset {
23 my ( $self, @args ) = @_;
24
548cc9f7 25 $self->throw_exception(
26 'setting current_changeset is not supported, use txn_do to create a new changeset'
27 ) if @args;
aba93491 28
fd45c476 29 my $id = $self->_current_changeset;
aba93491 30
548cc9f7 31 $self->throw_exception(
32 q{Can't call current_changeset outside of a transaction}
33 ) unless $id;
74f04ccc 34
fd45c476 35 return $id;
36}
f0f14c64 37
aba93491 38sub journal_create_changeset {
39 my ( $self, @args ) = @_;
40
b34c6936 41 my %changesetdata = ( @args );
aba93491 42
43 delete $changesetdata{parent_id} unless $self->nested_changesets;
44
548cc9f7 45 if( defined( my $user = $self->current_user() ) ) {
aba93491 46 $changesetdata{user_id} = $user;
47 }
548cc9f7 48 if( defined( my $session = $self->current_session() ) ) {
aba93491 49 $changesetdata{session_id} = $session;
50 }
51
52 ## Create a new changeset, then run $code as a transaction
53 my $cs = $self->resultset('ChangeSet');
54
55 $cs->create({ %changesetdata });
56}
57
6bfb7a1d 58sub journal_create_change {
59 my $self = shift;
548cc9f7 60 $self->resultset('ChangeLog')->create({
61 changeset_id => $self->current_changeset
62 });
6bfb7a1d 63}
64
548cc9f7 65sub journal_update_or_create_log_entry {
7adb876c 66 my ($self, $row, @cols) = @_;
67
68 my $s_name = $row->result_source->source_name;
69
70 my %id = map { $_ => $row->get_column($_)} $row->primary_columns;
71
72 $self->resultset("${s_name}AuditLog")->update_or_create({ @cols, %id });
73}
74
548cc9f7 75sub journal_record_in_history {
7adb876c 76 my ($self, $row, @cols) = @_;
77
78 my $s_name = $row->result_source->source_name;
79
80 $self->resultset("${s_name}AuditHistory")->create({ $row->get_columns, @cols });
81}
82
83
f0f14c64 841;