release 0.900101
[dbsrgits/DBIx-Class-Journal.git] / lib / DBIx / Class / Journal.pm
index d2fb599..05c6798 100644 (file)
@@ -5,261 +5,352 @@ use base qw/DBIx::Class/;
 use strict;
 use warnings;
 
-our $VERSION = '0.02';
+our $VERSION = '0.900101';
+$VERSION = eval $VERSION; # no errors in dev versions
 
-## On create/insert, add new entry to AuditLog
+## On create/insert, add new entry to AuditLog and new content to AuditHistory
 
-# sub new
-# {
-#     my ($class, $attrs, @rest) = @_;
+sub _journal_schema {
+    my $self = shift;
+    $self->result_source->schema->_journal_schema;
+}
+
+sub insert {
+    my ($self, @args) = @_;
+    return if $self->in_storage;
 
-#     $class->result_source->schema->_journal_schema->current_user(delete $attrs->{user_id});
+    my $res = $self->next::method(@args);
+    $self->journal_log_insert;
 
-#     $class->next::method($attrs, @rest);
-# }
+    return $res;
+}
 
-sub insert
-{
+sub journal_log_insert {
     my ($self) = @_;
 
-    return if($self->in_storage);
-    ## create new transaction here?
-    my $res = $self->next::method();
-    if($self->in_storage)
-    {
-        my $s_name = $self->result_source->source_name();
-        my $al = $self->result_source->schema->_journal_schema->resultset("${s_name}AuditLog");
-        $al->update_or_create({
-            ( map { $_ => $self->get_column($_)} $self->primary_columns ),
-            created => { changeset_id => $al->result_source->schema->current_changeset },
-        });
+    if ( $self->in_storage ) {
+        my $j = $self->_journal_schema;
+        my $change_id = $j->journal_create_change()->id;
+        $j->journal_update_or_create_log_entry( $self, create_id => $change_id );
+        $j->journal_record_in_history( $self, audit_change_id => $change_id );
     }
-
-    return $res;
 }
 
 ## On delete, update delete_id of AuditLog
 
-sub delete
-{
-    my ($self, @rest) = @_;
-    $self->next::method(@rest);
-
-    if(!$self->in_storage)
-    {
-        my $s_name = $self->result_source->source_name();
-        my $al = $self->result_source->schema->_journal_schema->resultset("${s_name}AuditLog");
-        my $alentry = $al->find_or_create({ map { $_ => $self->get_column($_)} $self->primary_columns });
-         
-        ## bulk_update doesnt do "create new item on update of rel-accessor with hashref, yet
-        my $change = $self->result_source->schema->_journal_schema->resultset('ChangeLog')->create({ changeset_id => $self->result_source->schema->_journal_schema->current_changeset });
-        $alentry->delete_id($change->id);
-        $alentry->update();
+sub delete {
+    my $self = shift;
+    my $ret = $self->next::method(@_);
+    $self->journal_log_delete(@_);
+    return $ret
+}
+
+sub journal_log_delete {
+    my ($self) = @_;
+
+    unless ($self->in_storage) {
+        my $j = $self->_journal_schema;
+        $j->journal_update_or_create_log_entry( $self, delete_id => $j->journal_create_change->id );
     }
-    
 }
 
-## On update, copy previous row's contents to AuditHistory
+## On update, copy row's new contents to AuditHistory
 
-sub update 
-{
-    my ($self, $upd, @rest) = @_;
+sub update {
+    my $self = shift;
+    my $ret = $self->next::method(@_);
+    $self->journal_log_update(@_);
+    return $ret
+}
 
-    if($self->in_storage)
-    {
-        my $s_name = $self->result_source->source_name();
-        my $ah = $self->result_source->schema->_journal_schema->resultset("${s_name}AuditHistory");
+sub journal_log_update {
+    my $self = shift;
 
-        my $obj = $self->result_source->resultset->find( $self->ident_condition );
-        $ah->create({
-            $obj->get_columns,
-            change => { changeset_id => $ah->result_source->schema->current_changeset },
-        });
+    if ($self->in_storage) {
+        my $j = $self->_journal_schema;
+        my $change_id = $j->journal_create_change->id;
+        $j->journal_record_in_history( $self, audit_change_id => $change_id );
     }
-
-    $self->next::method($upd, @rest);
 }
 
 =head1 NAME
 
-DBIx::Class::Journal - auditing for tables managed by DBIx::Class
+DBIx::Class::Journal - Auditing for tables managed by DBIx::Class
 
 =head1 SYNOPSIS
 
-  package My::Schema;
-  use base 'DBIx::Class::Schema';
+Load the module into your L<DBIx::Class> Schema Class:
+
+ package My::Schema;
+ use base 'DBIx::Class::Schema';
 
-  __PACKAGE__->load_components(qw/+DBIx::Class::Schema::Journal/);
+ __PACKAGE__->load_components(qw/Schema::Journal/);
 
-  __PACKAGE__->journal_connection(['dbi:SQLite:t/var/Audit.db']);
-  __PACKAGE__->journal_user(['My::Schema::User', {'foreign.userid' => 'self.user_id'}]);
+Optionally set where the journal is stored:
 
+ __PACKAGE__->journal_connection(['dbi:SQLite:t/var/Audit.db']);
 
- ########
+And then call C<< $schema->bootstrap_journal >> (I<once only>) to create all
+the tables necessary for the journal, in your database.
 
-  $schema->changeset_user($user->id);
-  my $new_artist = $schema->txn_do( sub {
-   return = $schema->resultset('Artist')->create({ name => 'Fred' });
-  });
+Later on, in your application, wrap operations in transactions, and optionally
+associate a user with the changeset:
 
+ $schema->changeset_user($user->id);
+ my $new_artist = $schema->txn_do( sub {
+    return $schema->resultset('Artist')->create({ name => 'Fred' });
+ });
 
 =head1 DESCRIPTION
 
 The purpose of this L<DBIx::Class> component module is to create an
 audit-trail for all changes made to the data in your database (via a
-DBIx::Class schema). It creates changesets and assigns each
-create/update/delete operation an id. The creation and deletion date
-of each row is stored, as well as the previous contents of any row
-that gets changed.
+DBIx::Class schema). It creates I<changesets> and assigns each
+create/update/delete operation an I<id>. The creation and deletion date of
+each row is stored, as well as the historical contents of any row that gets
+changed.
 
-All queries which want auditing should be called using
-L<DBIx::Class::Schema/txn_do>, which is used to create changesets for
-each transaction.
+All queries which need auditing B<must> be called using
+L<DBIx::Class::Schema/txn_do>, which is used to create changesets for each
+transaction.
 
-To track who did which changes, the user_id (an integer) of the
-current user can be set, a session_id can also be set, both are
-optional.
+To track who did which changes, the C<user_id> (an integer) of the current
+user can be set, and a C<session_id> can also be set; both are optional. To
+access the auditing schema to look at the auditdata or revert a change, use
+C<< $schema->_journal_schema >>.
 
-To access the auditing schema to look at the auditdata or revert a
-change, use C<< $schema->_journal_schema >>.
+=head1 DEPLOYMENT
 
-=head2 TABLES
+Currently the module expects to be deployed alongside a new database schema,
+and track all changes from first entry. To do that you need to create some
+tables in which to store the journal, and you can opitonally configure which
+data sources (tables) have their operations journalled by the module.
 
-The journal schema contains a number of tables. 
+Connect to your schema and deploy the journal tables as below. The module
+automatically scans your schema and sets up storage for journal entries.
 
-=over
+ # optional - defaults to all sources
+ My::Schema->journal_sources([qw/ table1 table2 /]);
 
-=item ChangeSet
+ $schema = My::Schema->connect(...);
+ $schema->journal_schema_deploy;
+
+Note that if you are retrofitting journalling to an existing database, then as
+well as creating the journal you will need to populate it with a history so
+that when rows are deleted they can be mapped back to a (fake) creation.
+
+If you ever update your original schema, remember that you must then also
+update the journal's schema to match, so that the AuditHistory has the
+corresponding new columns in which to save data.
+
+=head1 TABLES
 
-Each changeset row has an auto-incremented ID, optional user_id and
-session_id, and a set_date which defaults to the current datetime.
+The journal schema contains a number of tables. These track row creation,
+update and deletion, and also are aware of multiple operations taking place
+within one transaction.
+
+=over 4
+
+=item ChangeSet
 
-A ChangeSet has_many Changes.
+Each changeset row has an auto-incremented C<ID>, optional C<user_id> and
+C<session_id>, and a C<set_date> which defaults to the current datetime. This
+is the authoritative log of one discrete change to your database, which may
+possible consist of a number of ChangeLog operations within a single
+transaction.
 
 =item ChangeLog
 
-Each change/operation done in the transaction is recorded as a row in
-the ChangeLog table. It contains an auto-incrementing ID, the
-changeset_id and an order column for the ordering of each change in
-the changeset.
+Each operation done within the transaction is recorded as a row in the
+ChangeLog table. It contains an auto-incrementing C<ID>, the C<changeset_id>
+and an C<order> column to establish the order in which changes took place.
 
 =item AuditLog
 
-For every table in the original database that is to be audited, an
-AuditLog table is created. Each auditlog row has an id which will
-contain the primary key of the table it is associated with. (NB:
-currently only supports integer-based single column PKs). The
-create_id and delete_id fields contain the IDs of the Changes that
-created or deleted this row.
+For every table in the original database that is to be audited, an AuditLog
+table is created. When a row appears in the original database a corresponding
+row is added here with a ChangeLog ID in the C<create_id> column, and when
+that original row is deleted the AuditLog is updated to add another ChangeLog
+ID this time into the C<delete_id> column. A third id column contains the
+primary key of the original row, so you can find it in the AuditHistory.
+
+Note that currently only integer-based single column primary keys are
+supported in your original database tables.
 
 =item AuditHistory
 
-For every table in the original database to be audited, an
-AuditHistory table is created. Each row has a change_id field
-containing the ID of the ChangeLog row. The other fields correspond to
-all the fields from the original table. Each time a column value in
-the original table is changed, the entire row contents before the
-change are added as a new row in this table.
+For every table in the original database to be audited, an AuditHistory table
+is created. This is where the actual field data from your original table rows
+are stored on creation and on each update.
+
+Each row in the AuditHistory has a C<change_id> field containing the ID of the
+ChangeLog row. The other fields correspond to all the fields from the original
+table (with any constraints removed). Each time a column value in the original
+table is changed, the entire row contents after the change are added as a new
+row in this table.
 
 =back
 
-=head2 METHODS
+=head1 CLASS METHODS
 
-=over
+Call these in your Schema Class such as the C<My::Schema> package file, as in
+the SYNOPSIS, above.
 
-=item journal_connection
+=over 4
 
-=item Arguments: \@connect_info
+=item journal_connection \@connect_info
 
-=back
+Set the connection information for the database to save your audit information
+to.
 
-Set the connection information for the database to save your audit
-information to. Leaving this blank assumes you want to store the audit
-data into your current database.
+Leaving this blank assumes you want to store the audit data into your current
+database. The storage object will be shared by the regular schema and the
+journalling schema.
 
-=over
+=item journal_components @components
 
-=item journal_sources
+If you want to add components to your journal
+(L<DBIx::Class::Schema::Versioned> for example) pass them here.
 
-=item Arguments: \@source_names
+=item journal_sources \@source_names
 
-=back
+Set a list of source names you would like to audit. If unset, all sources are
+used.
+
+NOTE: Currently only sources with a single-column integer PK are supported, so
+use this method if you have sources which don't comply with that limitation.
 
-Set a list of source names you would like to audit, if unset, all
-sources are used.
+=item journal_storage_type $type
 
-NOTE: Currently only sources with a single-column PK are supported, so
-use this method if you have sources with multi-column PKs.
+Enter the special storage type of your journal schema if needed. See
+L<DBIx::Class::Storage::DBI> for more information on storage types.
 
-=over
+=item journal_user \@rel
 
-=item journal_storage_type
+The user_id column in the L</ChangeSet> will be linked to your user id with a
+C<belongs_to> relation, if this is set with the appropriate arguments. For
+example:
 
-=item Arguments: $storage_type
+ __PACKAGE__->journal_user(['My::Schema::User', {'foreign.userid' => 'self.user_id'}]);
 
 =back
 
-Enter the special storage type of your journal schema if needed. See
-L<DBIx::Class::Storage::DBI> for more information on storage types.
+=head1 OBJECT METHODS
 
-=over
+Once you have a connection to your database, call these methods to manage the
+journalling.
 
-=item journal_user
+=over 4
 
-=item Arguments: \@relation_args
+=item bootstrap_journal
 
-=back
+This calls C<journal_schema_deploy> followed by C<prepopulate_journal> to
+create your journal tables and if necessary populate them with a snapshot of
+your current original schema data.
 
-The user_id column in the L</ChangeSet> will be linked to your user id
-with a belongs_to relation, if this is set with the appropriate
-arguments.
+Do not run this method more than once on your database, as redeploying the
+journal schema is not supported.
 
-=over
+=item journal_schema_deploy
 
-=item changeset_user
+Will use L<DBIx::Class::Schema/deploy> to set up the tables for journalling in
+your schema. Use this method to set up your journal.
 
-=item Arguments: $user_id
+Note that if you are retrofitting journalling to an existing database, then as
+well as creating the journal you will need to populate it with a history so
+that when rows are deleted they can be mapped back to a (fake) creation.
 
-=back
+Do not run this method more than once on your database, as redeploying the
+journal schema is not supported.
+
+=item prepopulate_journal
+
+Will load the current state of your original source tables into the audit
+history as fake inserts in a single initial changeset. The advantage to this
+is that later deletetions of the row will be consistent in the journal with an
+initial state.
+
+Note that this can be an intensive and time consuming task, depending on how
+much data you have in your original sources; all of it will be copied to the
+journal history. However this step is essential if you are retrofitting
+Journalling to a schema with existing data, otherwise when you delete a row
+the Journal will die because it cannot relate that to an initial row insert.
+
+=item changeset_user $user_id
+
+Set the C<user_id> for the following changeset(s). This must be an integer.
+
+=item changeset_session $session_id
+
+Set the C<session_id> for the following changeset(s). This must be an integer.
+
+=item deploy
 
-Set the user_id for the following changeset(s). This must be an integer.
+Overloaded L<DBIx::Class::Schema/deploy> which will deploy your original
+database schema and following that will deploy the journal schema.
 
-=over
+=item txn_do $code_ref, @args
 
-=item changeset_session
+Overloaded L<DBIx::Class::Schema/txn_do>, this must be used to start a new
+ChangeSet to cover a group of changes. Each subsequent change to an audited
+table will use the C<changeset_id> created in the most recent C<txn_do> call.
 
-=item Arguments: $user_id
+Currently nested C<txn_do> calls cause a single ChangeSet object to be created.
 
 =back
 
-Set the session_id for the following changeset(s). This must be an integer.
+=head2 Deprecated Methods
 
-=over
+=over 4
 
-=item txn_do
+=item journal_deploy_on_connect $bool
 
-=iitem Arguments: $code_ref
+If set to a true value will cause C<journal_schema_deploy> to be called on
+C<connect>. Not recommended (because re-deploy of a schema is not supported),
+but present for backwards compatibility.
 
 =back
 
-Overloaded L<DBIx::Class::Schema/txn_do>, this must be used to start a
-new changeset to cover a group of changes. Each subsequent change to
-an audited table will use the changeset_id created in the most recent
-txn_do call.
+=head1 TROUBLESHOOTING
+
+For PostgreSQL databases you must enable quoting on SQL command generation by
+passing C<< { quote_char => q{`}, name_sep => q{.} } >> when connecting to the
+database.
 
 =head1 SEE ALSO
 
+=over 4
+
+=item *
+
 L<DBIx::Class> - You'll need it to use this.
 
-=head1 NOTES
+=back
+
+=head1 LIMITATIONS
+
+=over 4
+
+=item *
 
-Only single-column integer primary key'd tables are supported for auditing so far.
+Only single-column integer primary key'd tables are supported for auditing.
+
+=item *
+
+Rows changed as a result of C<CASCADE> settings on your database will not be
+detected by the module and hence not journalled.
+
+=item *
 
 Updates made via L<DBIx::Class::ResultSet/update> are not yet supported.
 
+=item *
+
 No API for viewing or restoring changes yet.
 
-Patches for the above welcome ;)
+=back
+
+Patches for the above are welcome ;-)
 
 =head1 AUTHOR