1 package SL::DB::Helper::ActsAsList;
5 use parent qw(Exporter);
6 our @EXPORT = qw(move_position_up move_position_down add_to_list remove_from_list reorder_list configure_acts_as_list);
13 my ($class, @params) = @_;
14 my $importing = caller();
16 $importing->before_save( sub { SL::DB::Helper::ActsAsList::set_position(@_) });
17 $importing->before_delete(sub { SL::DB::Helper::ActsAsList::remove_position(@_) });
19 # Use 'goto' so that Exporter knows which module to import into via
21 goto &Exporter::import;
28 sub move_position_up {
33 sub move_position_down {
35 do_move($self, 'down');
38 sub remove_from_list {
42 remove_position($self);
44 # Set to NULL manually because $self->update_attributes() would
45 # trigger the before_save() hook from this very plugin assigning a
46 # number at the end of the list again.
47 my $table = $self->meta->table;
48 my $column = column_name($self);
49 my $primary_key_col = ($self->meta->primary_key)[0];
53 WHERE ${primary_key_col} = ?
55 $self->db->dbh->do($sql, undef, $self->$primary_key_col);
56 $self->$column(undef);
59 return $self->db->in_transaction ? $worker->() : $self->db->do_transaction($worker);
63 my ($self, %params) = @_;
65 croak "Invalid parameter 'position'" unless ($params{position} || '') =~ m/^ (?: before | after | first | last ) $/x;
67 if ($params{position} eq 'last') {
73 my $table = $self->meta->table;
74 my $primary_key_col = ($self->meta->primary_key)[0];
75 my $column = column_name($self);
76 my ($group_by, @values) = get_group_by_where($self);
77 $group_by = " AND ${group_by}" if $group_by;
80 if ($params{position} eq 'first') {
84 # Can only be 'before' or 'after' -- 'last' has been checked above
87 my $reference = $params{reference};
88 croak "Missing parameter 'reference'" if !$reference;
92 $reference_pos = $reference->$column;
94 ($reference_pos) = $self->db->dbh->selectrow_array(qq|SELECT ${column} FROM ${table} WHERE ${primary_key_col} = ?|, undef, $reference);
97 $new_position = $params{position} eq 'before' ? $reference_pos : $reference_pos + 1;
102 SET ${column} = ${column} + 1
103 WHERE (${column} > ?)
108 $self->db->dbh->do($query, undef, $new_position - 1, @values);
109 $self->update_attributes($column => $new_position);
112 return $self->db->in_transaction ? $worker->() : $self->db->do_transaction($worker);
116 my ($class_or_self, @ids) = @_;
118 return 1 unless @ids;
120 my $self = ref($class_or_self) ? $class_or_self : $class_or_self->new;
121 my $column = column_name($self);
122 my $result = $self->db->do_transaction(sub {
123 my $query = qq|UPDATE | . $self->meta->table . qq| SET ${column} = ? WHERE id = ?|;
124 my $sth = $self->db->dbh->prepare($query) || die $self->db->dbh->errstr;
126 foreach my $new_position (1 .. scalar(@ids)) {
127 $sth->execute($new_position, $ids[$new_position - 1]) || die $sth->errstr;
136 sub configure_acts_as_list {
137 my ($class, %params) = @_;
139 $list_spec{$class} = {
140 group_by => $params{group_by},
141 column_name => $params{column_name},
149 sub get_group_by_where {
152 my $group_by = get_spec(ref $self, 'group_by') || [];
153 $group_by = [ $group_by ] if $group_by && !ref $group_by;
155 my (@where, @values);
156 foreach my $column (@{ $group_by }) {
157 my $value = $self->$column;
158 push @values, $value if defined $value;
159 push @where, defined($value) ? "(${column} = ?)" : "(${column} IS NULL)";
162 return (join(' AND ', @where), @values);
167 my $column = column_name($self);
169 return 1 if defined $self->$column;
171 my $table = $self->meta->table;
172 my ($group_by, @values) = get_group_by_where($self);
173 my $where = $group_by ? " WHERE ${group_by}" : '';
175 SELECT COALESCE(MAX(${column}), 0)
180 my $max_position = $self->db->dbh->selectrow_arrayref($sql, undef, @values)->[0];
181 $self->$column($max_position + 1);
186 sub remove_position {
188 my $column = column_name($self);
191 return 1 unless defined $self->$column;
193 my $table = $self->meta->table;
194 my $value = $self->$column;
195 my ($group_by, @values) = get_group_by_where($self);
196 $group_by = ' AND ' . $group_by if $group_by;
199 SET ${column} = ${column} - 1
200 WHERE (${column} > ?)
204 $self->db->dbh->do($sql, undef, $value, @values);
210 my ($self, $direction) = @_;
211 my $column = column_name($self);
213 croak "Object has not been saved yet" unless $self->id;
214 croak "No position set yet" unless defined $self->$column;
216 my $table = $self->meta->table;
217 my $old_position = $self->$column;
218 my ($comp_sel, $comp_upd, $min_max, $plus_minus) = $direction eq 'up' ? ('<', '>=', 'MAX', '+') : ('>', '<=', 'MIN', '-');
219 my ($group_by, @values) = get_group_by_where($self);
220 $group_by = ' AND ' . $group_by if $group_by;
222 SELECT ${min_max}(${column})
224 WHERE (${column} ${comp_sel} ?)
228 my $new_position = $self->db->dbh->selectrow_arrayref($sql, undef, $old_position, @values)->[0];
230 return undef unless defined $new_position;
235 WHERE (${column} = ?)
239 $self->db->dbh->do($sql, undef, $old_position, $new_position, @values);
241 $self->update_attributes($column => $new_position);
246 my $column = get_spec(ref $self, 'column_name');
247 return $column if $column;
248 return $self->can('sortkey') ? 'sortkey' : 'position';
252 my ($class, $key) = @_;
254 return undef unless $list_spec{$class};
255 return $list_spec{$class}->{$key};
267 SL::DB::Helper::ActsAsList - Mixin for managing ordered items by a
272 package SL::DB::SomeObject;
273 use SL::DB::Helper::ActsAsList;
275 package SL::Controller::SomeController;
277 # Assign a position automatically
278 $obj = SL::DB::SomeObject->new(description => 'bla');
281 # Move items up and down
282 $obj = SL::DB::SomeOBject->new(id => 1)->load;
283 $obj->move_position_up;
284 $obj->move_position_down;
286 # Adjust all remaining positions automatically
289 This mixin assumes that the mixing package's table contains a column
290 called C<position> or C<sortkey> (for legacy tables). This column is
291 set automatically upon saving the object if it hasn't been set
292 already. If it hasn't then it will be set to the maximum position used
293 in the table plus one.
295 When the object is deleted all positions greater than the object's old
296 position are decreased by one.
298 The column name to use can be configured via L<configure_acts_as_list>.
300 =head1 CLASS FUNCTIONS
304 =item C<configure_acts_as_list %params>
306 Configures the mixin's behaviour. C<%params> can contain the following
313 The name of the column containing the position. If not set explicitly
314 then the mixin will use C<sortkey> if the model contains such a column
315 (only for legacy tables) and C<position> otherwise.
319 An optional column name (or array reference of column names) by which
320 to group. If a table contains items for several distinct sets and each
321 set has its own sorting then this can be used.
323 An example would be requirement spec text blocks. They have a column
324 called C<output_position> that selects where to output the text blocks
325 (either before or after the sections). Furthermore these text blocks
326 each belong to a single requirement spec document. So each combination
327 of C<requirement_spec_id> and C<output_position> should have its own
328 set of C<position> values, which can be achieved by configuring this
329 mixin with C<group_by = [qw(requirement_spec_id output_position)]>.
335 =head1 INSTANCE FUNCTIONS
339 =item C<move_position_up>
341 Swaps the object with the object one step above the current one
342 regarding their sort order by exchanging their C<position> values.
344 =item C<move_position_down>
346 Swaps the object with the object one step below the current one
347 regarding their sort order by exchanging their C<position> values.
349 =item C<add_to_list %params>
351 Adds this item to the list. The parameter C<position> is required and
352 can be one of C<first>, C<last>, C<before> and C<after>. With C<first>
353 the item is inserted as the first item in the list and all other
354 item's positions are shifted up by one. For C<position = last> the
355 item is inserted at the end of the list.
357 For C<before> and C<after> an additional parameter C<reference> is
358 required. This is either a Rose model instance or the primary key of
359 one. The current item will then be inserted either before or after the
360 referenced item by shifting all the appropriate item positions up by
363 After this function C<$self>'s positional column has been set and
364 saved to the database.
366 =item C<remove_from_list>
368 Sets this items positional column to C<undef>, saves it and moves all
369 following items up by 1.
371 =item C<reorder_list @ids>
373 Re-orders the objects given in C<@ids> by their position in C<@ids> by
374 updating all of their positional columns. Each element in
375 C<@positions> must be the ID of an object. The new position is the
376 ID's index inside C<@ids> plus one (meaning the first element's new
377 position will be 1 and not 0).
379 This works by executing SQL "UPDATE" statements directly.
381 Returns the result of the whole transaction (trueish in case of
384 This method can be called both as a class method or an instance
395 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>