DBIx-Class-BatchUpdate

 view release on metacpan or  search on metacpan

lib/DBIx/Class/BatchUpdate/Update.pm  view on Meta::CPAN

}

has pk_column => ( is => "lazy" );
sub _build_pk_column {
    my $self = shift;
    my $result_source = $self->result_source or return undef;

    my $result_source_name = ref($result_source);
    my @columns = $result_source->primary_columns;
    @columns > 1 and croak("DBIx::Class::BatchUpdate::Update does not work on result sources ($result_source_name) with multi-column PKs\n");

    return $columns[0];
}

has batches => ( is => "lazy");
sub _build_batches {
    my $self = shift;
    my $pk_column = $self->pk_column or return [];
    my $result_source = $self->result_source;
    my $result_source_name = ref($result_source);

    my $key_batch = {};
    for my $row ($self->rows->elements) {
        my $key_value = { $row->get_dirty_columns };
        my $batch_key = $self->batch_key($key_value) or next;

        exists $key_value->{$pk_column} and croak("Primary key ($key_value->{$pk_column}) for ResultSource ($result_source_name) is dirty, can't BatchUpdate");

        my $batch = $key_batch->{ $batch_key } //= DBIx::Class::BatchUpdate::Batch->new({
            key_value => $key_value,
            resultset => $self->resultset,
            key       => $batch_key,
            pk_column => $pk_column,
        });
        $batch->ids->push( $row->id );
    };

    # Sort to get some semblance of determinism wrt insert ordering
    return [ sort { $a->key cmp $b->key } $key_batch->values ];
}

sub batch_key {
    my $self = shift;
    my ($key_value) = @_;
    keys %$key_value or return undef;

    # sort hash keys for a stable representation
    local $Storable::canonical = 1;
    return nfreeze(
        {
            # Assume the pk isn't dirty
            map {
                my $value = $key_value->{$_};
                $_ => defined($value) ? "$value" : undef;
            }
            keys %$key_value,
        },
    );
}

sub update {
    my $self = shift;
    for my $batch ( $self->batches->elements ) {
        $batch->update();
    }
}



( run in 0.632 second using v1.01-cache-2.11-cpan-39bf76dae61 )