in reply to data historization with DBIx::Class
My previous example was the easy one. It is a bit more complicated if you want to historize multiple rows with as little SQL statement as possible. Here DBIx::Class is missing a construct to build something like INSERT...SELECT... I am not deep enough into DBIx::Class, so my solution might not be the optimum, but works pretty well. So improvements are welcome.
my @colnames = $result_source->columns; my $upd_code_with_history = sub { # Step 1: make a copy of all active rows, but set them inactive # these become the history rows # Now build the "insert ... select" statement # First, build column list for INSERT my $insert_cols = join ',',@colnames; # build SELECT col-list with 'is_active' = 0 as not active foreach my $col (@colnames) { if ($col =~ /is_active$/) { # replace column name with constant $col = '0'; # is reference, change in-place last; } } # create the SQL Select part $key{is_active} = 1; # select all active rows my $rsi = $resultset->search(\%key, {select => \@colnames }); # as_query returns the generated SQL-Statemant and @params # in correct order. my ($select_sql,@params) = @{ ${$rsi->as_query} }; my $table = $rsi->result_source->from; # now put all tohether my $insert_sql = "INSERT INTO $table ($insert_cols) $select_sql"; # This insert copies all '1' and replaces them with '0' my @stuff = $db_schema->storage->dbh_do( sub { my ($storage, $dbh, $sql, @bndval) = @_; if ($self->config->{debug_sql}) { print STDERR $sql, ": '", join("', '", @bndval), "'\n"; } $dbh->do($sql, undef, @bndval); }, # see above for @param structure $insert_sql, map { $_->[1] } @params ); # Step 2: Update all '1' elements with current timestamp and values # This will be the current rows # $key{elt_aktiv_mm} = 1; # still set $values->{timestamp_col} = \['CURRENT TIMESTAMP']; # now update all '1'-rows with the values my $rss = $resultset->search(\%key)->update($values); }; # end Coderef $upd_code
As said, I am not very perfect with DBIx::Clas, so there might be better solutions. This gives two SQL statement and is that way more performant than updating every row by itself. Hope it helps
And it came to pass that in time the Great God Om spake unto Brutha, the Chosen One: "Psst!"
(Terry Pratchett, Small Gods)
|
|---|