DBIx-Class-RandomColumns
view release on metacpan or search on metacpan
lib/DBIx/Class/RandomColumns.pm view on Meta::CPAN
=head2 insert
Hooks into L<DBIx::Class::Row/insert> to create a random value for each
L<random column|/random_columns> that is not defined.
=cut
sub insert {
my $self = shift;
my $accessor;
for (keys %{$self->random_columns}) {
next if defined $self->get_column($_); # skip if defined
$accessor = $self->column_info($_)->{accessor} || $_;
$self->$accessor($self->get_random_value($_));
}
return $self->next::method;
}
=head2 get_random_value
$value = $instance->get_random_value($column_name);
Compute a random value for the given C<$column_name>.
Throws an exception if the concerning column has not been declared
as a random column.
=cut
sub get_random_value {
my $self = shift;
my $column = shift;
my $conf = $self->random_columns->{$column}
or $self->throw_exception(qq{column "$column" is not a random column});
my $check = $conf->{check};
my $tries = $self->max_dup_checks;
my $id;
if ($conf->{max}) {
# it's an integer column
do { # check uniqueness if check => 1 for this column
$id = int(rand($conf->{max} - $conf->{min} + 1)) + $conf->{min}
} while $check and
$tries-- and
$self->result_source->resultset->search({$column => $id})->count;
}
else {
my $set = $conf->{set};
do { # check uniqueness if check => 1 for this column
$id = '';
# random id is as good as Perl's rand()
$id .= $set->[int(rand(@$set))] for (1 .. $conf->{size});
} while $check and
$tries-- and
$self->result_source->resultset->search({$column => $id})->count;
}
$self->throw_exception("escaped from busy loop in DBIx::Class::RandomColumns::get_random_column_id()")
unless $tries;
return $id;
}
1;
__END__
=head1 OPTIONS
=head2 is_random
is_random => 1
is_random => {size => 16, set => ['0'..'9','A'..'F']}
Instead of calling L</random_columns> it is also possible to specify option
C<is_random> in L<add_columns|DBIx::Class::ResultSource/add_columns>.
The value is either a true scalar value, indicating that this in fact is a
random column, or a hash reference, that has the same meaning as described
under L</random_columns>.
=head1 SEE ALSO
L<DBIx::Class>
=head1 AUTHOR
Bernhard Graf C<< <graf(a)cpan.org> >>
=head1 BUGS
Please report any bugs or feature requests to
C<bug-dbix-class-randomclumns at rt.cpan.org>, or through the web interface
at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=DBIx-Class-RandomColumns>.
I will be notified, and then you'll automatically be notified of progress
on your bug as I make changes.
=head1 COPYRIGHT & LICENSE
Copyright 2008 - 2011 Bernhard Graf.
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=cut
# vim: set tabstop=4 shiftwidth=4 expandtab shiftround:
( run in 1.393 second using v1.01-cache-2.11-cpan-39bf76dae61 )