blib/lib/DBIx/Path.pm untested

filter: Statementstmt 0.0% 0 / 168 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 43 MC/DCmcdc 0.0% 0 / 25 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 309 CC 19 SCAR 22.2
CC
19
Cov
0%
_reverse
20.0
_unlock
20.0
new
12.0
CRAP 9.2
1 package DBIx::Path;
2  
3 use strict;
4 use warnings;
5 use DBI;
6 use Carp qw(croak);
7  
8 our $VERSION=0.03;
9  
10 =head1 NAME
11  
12 DBIx::Path - resolve a path in an in-database tree or directed graph
13  
14 =head1 SYNOPSIS
15  
16 use DBIx::Path;
17 my $root=DBIx::Path->new(dbh => $dbh, table => 'treetable');
18 my $node=$root->resolve(split '/', 'one/two/three')
19 or die "Can't resolve path: $! at $DBIx::Path::FAILED[0]";
20 print $_->name, "\t", $_->id, "\n" for $node->list;
21  
22 =head1 DESCRIPTION
23  
24 DBIx::Path is used to navigate through trees or directed graphs described by
25 self-referential SQL database tables. It can be used to browse most trees where
26 each row contains a unique ID and the ID of its parent, as well as graphs structured
27 similarly but with multiple parents for a given node (presumably with the actual data
28 for a given ID stored in a different table).
29  
30 The module is designed to work with tables with at least three columns. One
31 is called the parent ID (pid); one is called the name; and one is the ID. The
32 combination of a particular pid and name must be unique in the entire table.
33 The three columns can be of any type, but pid and id should probably be of the
34 same type. The columns can have any name you want--you're not confined to
35 "id", "pid", and "name". It is possible to have the id and name be the same
36 column.
37  
38 An example layout:
39  
40 CREATE TABLE tree (
41 pid INTEGER NOT NULL,
42 name VARCHAR(16) NOT NULL,
43 id INTEGER NOT NULL,
44 PRIMARY KEY (pid, name)
45 )
46  
47 In MySQL, you might want to use a layout with a TIMESTAMP column:
48  
49 CREATE TABLE tree (
50 pid INTEGER NOT NULL,
51 name VARCHAR(16) NOT NULL,
52 id INTEGER NOT NULL,
53 mtime TIMESTAMP,
54 PRIMARY KEY (pid, name)
55 )
56  
57 In this table, name and ID are one:
58  
59 CREATE TABLE folders (
60 parent VARCHAR(16) NOT NULL,
61 name VARCHAR(16) NOT NULL,
62 PRIMARY KEY (pid, name)
63 )
64  
65 The parent/child relationship is expressed through the pid field--each node contains
66 its parent's ID in its pid field. DBIx::Path's primary purpose is to retrieve the ID
67 for a particular pid/name combination, with the ability to descend through the tree
68 via the C<resolve> method.
69  
70 An object of type DBIx::Path represents a node, and in this document it will always
71 be referred to as a node.
72  
73 =head2 Constructor
74  
75 =head3 new
76  
77 $root_node = DBIx::Path->new( %config );
78 $node = $root_node->new( id => $id ); # If the ID is known
79  
80 Manually creates an object to represent the tree's root node. Note that there doesn't
81 actually need to be an ID in the table for this node, although it doesn't hurt! The
82 C<pid> and C<name> methods will always return C<undef> for a node created through C<new>,
83 but nodes created through C<new> otherwise behave identically to those created with
84 C<get>, C<set>, C<add>, or C<resolve>.
85  
86 C<new> can also be used as a copy constructor. This can be used to create a DBIx::Path
87 object from a known ID.
88  
89 The arguments comprise a hash (not a hash reference) with the following keys:
90  
91 =over 4
92  
93 =item * C<dbh>
94  
95 An already-opened DBI database handle. Required.
96  
97 =item * C<table>
98  
99 The name of the table containing the tree/graph being traversed.
100 Required.
101  
102 =item * C<id_column>
103  
104 The name of the ID field. Optional; defaults to "id".
105  
106 =item * C<pid_column>
107  
108 The name of the pid field. Optional; defaults to "pid".
109  
110 =item * C<name_column>
111  
112 The name of the name field. Optional; defaults to "name".
113  
114 =item * C<id>
115  
116 The ID of the root. Optional; defaults to 0. Note that C<id>
117 cannot be C<undef> (C<NULL>), due to the SQL used to retrieve nodes.
118  
119 =item * C<hooks>
120  
121 A hashref of sub references which C<DBIx::Path> will call at appropriate
122 time. Optional; current hooks include:
123  
124 =over 4
125  
126 =item C<lock>
127  
128 Called at the beginning of any operation involving a database query. The first
129 parameter is the database handle; the second is 'r' for a read operation (which
130 recommends a shared lock) or 'w' for a write operation (which recommends an
131 exclusive lock).
132  
133 =item C<unlock>
134  
135 Called after the operation which needed a lock is complete. Parameters are the
136 same as C<lock>.
137  
138 =back 4
139  
140 =back 4
141  
142 The return value is a DBIx::Path object, which can then be used normally.
143  
144 =cut
145  
146 sub new {
147 my($me, %config)=@_;
148
149 # This is NOT cargo culting, dammit.
150 %config=(%$me, %config) if ref $me;
151
152 $config{dbh} or croak "Invalid or missing database handle";
153 $config{table} or croak "Invalid or missing table name";
154 my $dbh=$config{dbh};
155
156 $config{id_column} ||= 'id';
157 $config{pid_column} ||= 'pid';
158 $config{name_column} ||= 'name';
159 $config{id} ||= 0;
160
161 unless($config{sth}) {
162 #These statement handles will be needed later.
163 $config{sth}{get}=$dbh->prepare(<<"END") or die "DBIx::Path->new: couldn't prepare 'get' statement: $DBI::errstr";
164 SELECT $config{id_column}, $config{pid_column}, $config{name_column}
165 FROM $config{table}
166 WHERE $config{pid_column} = ?
167 AND $config{name_column} = ?
168 END
169 $config{sth}{add}=$dbh->prepare(<<"END") or die "DBIx::Path->new: couldn't prepare 'add' statement: $DBI::errstr";
170 INSERT INTO $config{table}
171 ($config{id_column}, $config{pid_column}, $config{name_column})
172 VALUES (?, ?, ?)
173 END
174 $config{sth}{del}=$dbh->prepare(<<"END") or die "DBIx::Path->new: couldn't prepare 'del' statement: $DBI::errstr";
175 DELETE FROM $config{table}
176 WHERE $config{pid_column} = ?
177 AND $config{name_column} = ?
178 END
179 $config{sth}{list}=$dbh->prepare(<<"END") or die "DBIx::Path->new: couldn't prepare 'list' statement: $DBI::errstr";
180 SELECT $config{id_column}, $config{pid_column}, $config{name_column}
181 FROM $config{table}
182 WHERE $config{pid_column} = ?
183 END
184 $config{sth}{parents}=$dbh->prepare(<<"END") or die "DBIx::Path->new: couldn't prepare 'parents' statement: $DBI::errstr";
185 SELECT $config{id_column}, $config{pid_column}, $config{name_column}
186 FROM $config{table}
187 WHERE $config{id_column} = ?
188 END
189 }
190  
191 #Once again, no cargo-culting here. You can go about your business. Move along!
192 return bless \%config, ref $me || $me;
193 }
194  
195 =head2 Methods
196  
197 =head3 get
198  
199 $node = $node->get( $name )
200  
201 The C<get> method retrieves the immediate child of $node named $name.
202 It returns C<undef> and sets $! to ENOENT if no child by that name
203 exists.
204  
205 =cut
206  
207 sub get {
208 my($me, $name)=@_;
209 $me->_lock('r');
210 $me->{sth}{get}->execute($me->{id}, $name);
211 $me->_unlock('r');
212 my $r=$me->{sth}{get}->fetchrow_arrayref() or do {
213 require POSIX;
214 $!=POSIX::ENOENT();
215 return;
216 };
217 $me->{sth}{get}->finish();
218 return $me->_row_to_obj($r);
219 }
220  
221 =head3 add
222  
223 $node = $node->add( $name, $id )
224  
225 Adds $id as a child of $node named $name, then returns the newly-added node.
226 This is done with a SQL INSERT statement. If the statement failed (because,
227 for example, C<(pid, name)> is a primary key and that particular combination
228 already exists), returns C<undef> and sets $! to EEXIST.
229  
230 =cut
231  
232 sub add {
233 my($me, $name, $id)=@_;
234 $id = $id->id if ref $id; #Be nice to the poor, dumb hacker.
235  
236 $me->_lock('w');
237 #Make sure such a row doesn't exist first.
238 my $affected=(
239 ! $me->get($name) &&
240 $me->{sth}{add}->execute($id, $me->{id}, $name)
241 );
242
243 if(!defined $affected or $affected == 0) {
244 $me->_unlock('w');
245 require POSIX;
246 $!=POSIX::EEXIST();
247 return;
248 }
249 else {
250 my $ret=$me->get($name);
251 $me->_unlock('w');
252 return $ret;
253 }
254 }
255  
256 =head3 del
257  
258 $ok = $node->del( $name )
259  
260 Deletes the relation between $node and $name. Returns 1 if successful.
261 If the SQL statement failed, returns C<undef> and sets $! to ENOENT.
262  
263 =cut
264  
265 sub del {
266 my($me, $name)=@_;
267
268 $me->_lock('w');
269 my $affected=$me->{sth}{del}->execute($me->{id}, $name);
270 $me->_unlock('w');
271  
272 if(!defined $affected or $affected == 0) {
273 require POSIX;
274 $!=POSIX::ENOENT();
275 return;
276 }
277 else {
278 return 1;
279 }
280 }
281  
282 =head3 set
283  
284 $node = $node->set( $name, $id )
285  
286 Deletes the old relation between $node and $name, then creates a new one
287 making $id the child of $node named $name. A simple wrapper around
288 C<del> and C<add>. Return values are the same as C<add>, but note that
289 $! may still be set due to the result of C<del>.
290  
291 This method may be subject to race conditions unless the C<lock> and
292 C<unlock> hooks are specified.
293  
294 =cut
295  
296 sub set {
297 my($me, $name, $id)=@_;
298 $me->_lock('w');
299 $me->del($name);
300 my $ret=$me->add($name, $id);
301 $me->_unlock('w');
302 return $ret;
303 }
304  
305 =head3 parents
306  
307 @list = $node->parents()
308  
309 Finds all references to the current node--in other words, all parents which count this
310 node as their child. In scalar context, returns the number of parents; in list context,
311 returns a hash whose keys are the IDs of the parents and whose values are an arrayref of
312 names the current node is found under.
313  
314 =cut
315  
316 sub parents {
317 my($me)=@_;
318 my %ret;
319  
320 $me->_lock('r');
321 $me->{sth}{parents}->execute($me->id);
322 $me->_unlock('r');
323 while(my $r=$me->{sth}{parents}->fetchrow_arrayref) {
324 push @{$ret{$r->[1]}}, $r->[2];
325 }
326  
327 return wantarray ? %ret : scalar keys %ret;
328 }
329  
330  
331 =head3 resolve
332  
333 $node = $node->resolve( @components )
334  
335 The C<resolve> method traverses the provided path; that is, it looks
336 up the child of $node named $components[0], then looks up the child of
337 the just-retrieved node named $components[1], and so on. Components
338 which are undefined or consist of the empty string will be ignored.
339  
340 Return value is the same as C<get> when a name anywhere in @components
341 does not resolve.
342  
343 After it is run, @DBIx::Path::RESOLVED will contain all components it
344 resolved, and $DBIx::Path::PARENT will contain the node resolved from
345 $RESOLVED[-1]. That is, after a successful run, @RESOLVED will be a
346 copy of the @components list, and $PARENT will contain the parent of
347 the returned node.
348  
349 After a failed attempt to resolve, @RESOLVED will contain all components
350 that resolved successfully. An additional variable, @DBIx::Path::FAILED,
351 will contain the remaining components. $PARENT will contain the node which
352 didn't have a child named $FAILED[0]. These variables are intended to augment
353 the simple ENOENT placed in $! by C<get>.
354  
355 =cut
356  
357 sub resolve {
358 my($me, @components)=@_;
359 my $cursor=$me;
360 local $_;
361
362 our @RESOLVED=();
363 our @FAILED=@components;
364 our $PARENT=$me;
365
366 $me->_lock('r');
367 for(@components) {
368 next unless defined $_ and $_ ne '';
369 $PARENT=$cursor;
370 $cursor=$cursor->get($_);
371 last unless defined $cursor;
372 push @RESOLVED, $_;
373 shift @FAILED;
374 }
375 $me->_unlock('r');
376
377 return $cursor;
378 }
379  
380 =head3 reverse
381  
382 @list=$node->reverse()
383  
384 Returns all paths from the root to the current node. The return value is an
385 arrayref of names. (If called on the root node, it returns a single empty
386 arrayref, which is probably the most accurate depiction of the situation.)
387 If called in scalar context, it will return the number of paths from the root to
388 the current node.
389  
390 If reverse() encounters a circular reference while attempting to find the parents,
391 it will return an empty list and set $! to ELOOP.
392  
393 The results of this function are undefined if the relevant parts of the tree are
394 modified while it's being executed. It is an exceedingly good idea to specify the
395 C<lock> and C<unlock> hooks if you intend to use this method.
396  
397 Note: This function disregards the contents of the C<id> parameter given to C<new>;
398 it considers the root to simply be the parentless node at the top of the tree.
399 Thus, it may "break out" of a particular subtree.
400  
401 =cut
402  
403 {
404 our %seen;
405 my %memo;
406 sub reverse {
407 %seen=();
408 %memo=();
409 $_[0]->_lock('r');
410 my @ret;
411 eval {
412 @ret=&_reverse;
413 };
414 $_[0]->_unlock('r');
415 if($@) {
416 if($@ =~ /Circular reference encountered during DBIx::Path->reverse()/) {
417 require POSIX;
418 $!=POSIX::ELOOP();
419 return;
420 }
421 else {
422 die;
423 }
424 }
425 return @ret;
426 }
427  
428 sub _reverse {
429 my($me)=@_;
430 my @ret;
431  
432 local %seen=%seen;
433 die "Circular reference encountered during DBIx::Path->reverse()" if $seen{$me->id};
434 $seen{$me->id}++;
435  
436 return @{$memo{$me->id}} if $memo{$me->id};
437  
438 my %parents=$me->parents;
439 return [] unless %parents;
440  
441 for my $pid(keys %parents) {
442 my $parent=$me->new(%$me, id => $pid);
443 my @parent_ret=$parent->_reverse();
444 for my $name(@{ $parents{$pid} }) {
445 for my $ancestors(@parent_ret) {
446 push @ret, [@$ancestors, $name];
447 }
448 }
449 }
450 $memo{$me->id}=\@ret;
451 return @ret;
452 }
453 }
454  
455  
456 =head3 list
457  
458 @nodes=$node->list()
459  
460 Returns an unordered list of nodes which are children of the current node.
461  
462 This method does not operate recursively; the DBIx::Tree module would be more
463 appropriate for that purpose.
464  
465 =cut
466  
467 sub list {
468 my($me)=@_;
469 my @ret;
470 local $_;
471
472 $me->_lock('r');
473 $me->{sth}{list}->execute($me->{id});
474 $me->_unlock('r');
475 push @ret, $me->_row_to_obj($_) while $_ = $me->{sth}{list}->fetchrow_arrayref;
476 return @ret;
477 }
478  
479 =head2 Accessors
480  
481 =head3 id
482  
483 $id = $node->id()
484  
485 Returns the ID of the current node.
486  
487 =head3 pid
488  
489 $pid = $node->pid()
490  
491 Returns the parent ID used to resolve the current node. Returns C<undef> for
492 the root node.
493  
494 =head3 name
495  
496 $name = $node->name()
497  
498 Returns the name used to resolve the current node. Returns C<undef> for the
499 root node.
500  
501 =cut
502  
503 for my $field qw(id pid name) {
504 no strict 'refs';
505 *{$field}=sub { $_[0]->{$field} }
506 }
507  
508 {
509 my $locked=0;
510 sub _lock {
511 my($me, $type)=@_;
512 $locked++;
513 if($locked == 1 and $me->{hooks}{lock}) {
514 $me->{hooks}{lock}->($me->{dbh}, $type);
515 }
516 }
517 sub _unlock {
518 my($me, $type)=@_;
519 if($locked == 1) {
520 $me->{hooks}{unlock}->($me->{dbh}, $type) if $me->{hooks}{unlock};
521 }
522 elsif($locked == 0) {
523 croak "DBIx::Path: PANIC: Key won't fit in lock";
524 }
525 $locked--;
526 }
527 END {
528 if($locked) {
529 warn "DBIx::Path: WARNING: Program may have exited with lock(s) still held";
530 }
531 }
532 }
533  
534 sub _row_to_obj {
535 my($id, $pid, $name)=@{$_[1]};
536 (ref $_[0])->new(%{$_[0]}, id => $id, pid => $pid, name => $name);
537 }
538  
539 =head2 Diagnostics
540  
541 DBIx::Path primarily communicates errors to the caller by returning C<undef>
542 and setting $! to an appropriate value. However, it does throw a few
543 exceptions.
544  
545 =over 4
546  
547 =item C<Invalid or missing %s>
548  
549 One of the required parameters to C<new> (either the database handle
550 or the table name) was omitted, or something that clearly wasn't a handle or
551 table name (such as an C<undef> value) was passed. Please check your code.
552  
553 =item C<< DBIx::Path->new: Couldn't prepare '%s' statement: %s >>
554  
555 C<new> prepares several SQL statements which are used by the other
556 methods. This message indicates that the indicated statement was invalid.
557 This could indicate a bad table name or invalid I<whatever>_column settings;
558 it could also mean that the SQL used by DBIx::Path isn't recognized by your
559 DBD.
560  
561 Check the parameters you're passing to DBIx::Path->new, then make sure the
562 SQL at the indicated line number is valid for your server. The text after
563 the second colon is the DBI error message.
564  
565 =item C<DBIx::Path: PANIC: Key won't fit in lock>
566  
567 Internal error indicating that DBIx::Path wanted to call your unlock hook,
568 but somehow forgot to call your lock hook in the first place. This shouldn't
569 happen.
570  
571 =item C<DBIx::Path: WARNING: Program may have exited with lock(s) still held>
572  
573 DBIx::Path has an internal variable tracking how deeply nested locks currently
574 are; it uses this to ensure that your lock/unlock hooks are only called once
575 per method. This message will be printed to STDERR if that variable has a
576 non-zero value when Perl exits; it indicates that you should check to make sure
577 your database hasn't become wedged.
578  
579 This message is most often seen when an error occurs within DBIx::Path itself;
580 it may also be displayed for particularly nasty sorts of bugs within DBIx::Path
581 or if your process is hit by a signal while DBIx::Path is querying your
582 database. It's never good news.
583  
584 =back 4
585  
586 =head1 BUGS AND ENHANCEMENTS
587  
588 There are no known bugs at this time; however, I'm not that experienced
589 with the DBI, so God only knows if I've missed something important.
590  
591 The following methods may be vulneurable to race conditions or other time-sensitive
592 bugs unless locking hooks are provided:
593  
594 =over 4
595  
596 =item * C<set>
597  
598 =item * C<resolve>
599  
600 =item * C<reverse>
601  
602 =back 4
603  
604 Some enhancements I'm considering are:
605  
606 =over 4
607  
608 =item * Hooks on the basic operations (C<get>, C<add>, C<del>, possibly C<set>
609 and C<list>). Subclassing may make this unnecessary, however.
610  
611 =item * Methods that select all descendents of the current node and return them
612 in various useful forms. (These would have to not curl up into a ball and cry
613 in the face of circular references.)
614  
615 =back 4
616  
617 Patches to implement these, or to fix bugs, are much appreciated; send them to
618 <brentdax@cpan.org> and start the subject line with something like
619 "[PATCH DBIx::Path]".
620  
621 =head1 SEE ALSO
622  
623 L<DBI>, DBD::*, L<DBIx::Tree>, L<File::Path>
624  
625 =head1 AUTHOR
626  
627 Brent 'Dax' Royal-Gordon, <brentdax@cpan.org>
628  
629 =head1 COPYRIGHT
630  
631 Copyright 2005 Brent 'Dax' Royal-Gordon. All rights reserved.
632  
633 This library is free software; it may be used, redistributed, and/or modified
634 under the same terms as Perl itself.
635  
636 =cut
637  
638 1;