blib/lib/Tree/Numbered/DB.pm untested

filter: Statementstmt 0.0% 0 / 197 Branchbran 0.0% 0 / 48 Conditioncond 0.0% 0 / 41 MC/DCmcdc 0.0% 0 / 24 Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 22 totaltotal 0.0% 0 / 357 CC 25 SCAR 33.3
CC
25
Cov
0%
new
110.0
setMapping
12.0
setFields
12.0
CRAP 27.9
1 package Tree::Numbered::DB;
2  
3 use strict;
4  
5 use Tree::Numbered;
6  
7 use DBI;
8  
9 our $VERSION = '1.02.2';
10 our @ISA = qw(Tree::Numbered);
11  
12 my %collumn_names = (_Serial => 'serial',
13 _Parent => 'parent',
14 Value => 'name');
15  
16 sub _addMapping; # predeclared method.
17  
18 # Internal group of subs to determine whether we should write each change
19 # or do batch operations. 1 = every change.
20 {
21 my $write_mode = 1;
22 sub _turnOnWrite {
23 $write_mode = 1;
24 }
25 sub _turnOffWrite {
26 $write_mode = 0;
27 }
28 sub _WriteMode {return $write_mode};
29 }
30  
31 # <getFieldsStr> returns a string of fields in the order they are returned
32 # from getFieldNames
33 # Arguments: $cols - a hash of column mappings.
34 # Returns: See above,,,
35  
36 sub _getFieldsStr {
37 my $self = shift;
38 return join ', ', map {$self->getMapping($_) . "=?"}
39 @{$self->getFieldNames} if $self->getFieldNames;
40 }
41  
42 # <getStatements> a service method that prepares SQL statements used in the
43 # module.
44 # Arguments: $colnames - names of the columns that make up the table (see
45 # %collumn_names above).
46 # Returns: a hash with the statements.
47  
48 sub getStatements {
49 my $self = shift;
50 my $serial = $self->getMapping('_Serial');
51 my $parent = $self->getMapping('_Parent');
52  
53 my $extra = $self->_getFieldsStr || '';
54 my $dbh = $self->{Source};
55 my $table = $self->{SourceName};
56  
57 my %statements;
58 $statements{add} = "insert into $table set " .
59 "$parent=$self->{_Parent}, " . $extra;
60 $statements{who} = "select max($serial) from $table";
61 $statements{delete} = "delete from $table where $serial=?";
62 $statements{update} = "update $table set " . $extra .
63 " where $serial=?"; # We don't have a number yet...
64 $statements{truncate} = "truncate $table";
65  
66 $self->{Statements} = {map {$_ => $dbh->prepare($statements{$_}) }
67 keys %statements};
68 }
69  
70 # <new> constructs a new tree or node.
71 # Arguments: By name:
72 # parent - the node's parent (for internal use).
73 # source_name - table name.
74 # source - DB handle.
75 # *_col - column mapping.
76 # * - column value.
77 # serial_col - collumn name for serial numbers
78 # parent_col - column name for parent numbers.
79 # NoWrite - create the node without writing it to the DB (internal use).
80 # Returns: The tree object.
81  
82 sub new {
83 my %reserved = map {$_ => 1} ('parent_col', 'serial_col',
84 'parent', 'serial', 'NoWrite',
85 'source', 'source_name');
86  
87 my $parent = shift;
88 my %args = @_;
89  
90 my ($parent_serial, $class);
91 _turnOffWrite; # turn off writing for a while.
92  
93 # Create the bloody thing. addField will search the parent for mappings.
94 my $properties = $parent->SUPER::new;
95  
96 # Find out which mappings and fields
97 my @colnames = grep(/_col$/, keys %args);
98 my %colmaps = map {$_ => $args{$_}} @colnames;
99 my %fields = %args;
100 delete @fields{@colnames, keys %reserved};
101  
102 # Auto create fields with undefind value if a mapping exists for them.
103 foreach (@colnames) {
104 next if (exists $reserved{$_});
105 s/_col$//;
106 $fields{$_} = undef unless (exists $fields{$_}); # Auto vivification.
107 }
108  
109 # Create the Value field if no other field was requested:
110 unless (scalar keys %fields) {
111 #default field and map.
112 $properties->_addMapping('Value', $collumn_names{Value});
113 $fields{Value} = undef;
114 }
115  
116 if ($class = ref($parent)) {
117 # We're adding to an existing tree.
118 $properties->{Source} = $parent->{Source};
119 $properties->{SourceName} = $parent->{SourceName};
120 $properties->{_Parent} = $parent->{_Serial};
121  
122 # Inherit mappings:
123 foreach my $field ($parent->getFieldNames) {
124 # Won't do anything if mapping is already there:
125 $properties->_addMapping($field, $parent->getMapping($field));
126 }
127 $properties->_addMapping('_Serial', $parent->getMapping('_Serial'));
128 $properties->_addMapping('_Parent', $parent->getMapping('_Parent'));
129 } else {
130 # New tree. Check that args are correct:
131 unless ($args{source_name} && $args{source}){
132 warn "No source or name, failed to create a tree.";
133 return undef;
134 }
135  
136 $class = $parent;
137 $properties->{_Parent} = $args{parent} ||= 0;
138 $properties->{Source} = $args{source} ||= '';
139 $properties->{SourceName} = $args{source_name} ||= '';
140  
141 # Use default mapping for mandatory fields::
142 $properties->_addMapping('_Serial', $collumn_names{_Serial});
143 $properties->_addMapping('_Parent', $collumn_names{_Parent});
144  
145 }
146  
147 # Use arguments for mappings for mandatory serial and parent.
148 $properties->setMapping('_Serial', $colmaps{"serial_col"})
149 if ($colmaps{"serial_col"});
150 $properties->setMapping('_Parent', $colmaps{"parent_col"})
151 if ($colmaps{"parent_col"});
152
153 # add mappings and fields.
154 foreach (keys %fields) {
155 # Fail if there's a field with no mapping.
156 unless($colmaps{"${_}_col"} or $properties->getMapping($_)) {
157 warn "No mapping for field $_, unable to create a tree.";
158 return undef;
159 }
160 $properties->_addMapping($_, $colmaps{"${_}_col"});
161 $properties->addField($_, $fields{$_}) or
162 $properties->setField($_, $fields{$_});
163 }
164
165 _turnOnWrite; # Ok, let's make it real:
166 # Create SQL statements:
167 $properties->getStatements;
168 $properties->{_Serial} = addNodeDB($properties) unless $args{NoWrite};
169  
170 return $properties;
171 }
172  
173 # <addNodeDB> adds a record to a table containing a tree.
174 # Arguments: $self - the node's hash. This is not a class method because the
175 # object we're operating on is not yet blessed.
176 # Returns: The new Serial number of the Item added.
177  
178 sub addNodeDB {
179 my $self = shift;
180 my $parent = $self->{_Parent};
181 # Preserve order of fields:
182 my @values = map { $self->getField($_) } @{ $self->getFieldNames };
183  
184 $self->{Statements}->{add}->execute(@values) or return undef;
185 $self->{Statements}->{who}->execute;
186 return ($self->{Statements}->{who}->fetchrow_array)[0];
187 }
188  
189 # <readDB> constructs a new tree from a pre-existing table.
190 # Arguments: $table - table name.
191 # $dbh - database handle to operate on.
192 # $cols - a hash giving alternative collumn names.
193 # Returns: The tree object.
194  
195 sub read {
196 my ($self, $table, $dbh, $cols) = @_;
197 return undef if (ref $self); # Class method only, dude.
198  
199 # Some defaults:
200 $cols ||= {Value_col => $collumn_names{Value}};
201 $cols->{serial_col} ||= $collumn_names{_Serial};
202 $cols->{parent_col} ||= $collumn_names{_Parent};
203  
204 my %fcols = %$cols; # field columns.
205 delete @fcols{'serial_col', 'parent_col'};
206  
207 # Start construction of root element:
208 my $tree = Tree::Numbered::DB->new(source => $dbh,
209 source_name => $table,
210 parent => 0,
211 NoWrite => 1,
212 %$cols);
213  
214 my $extra = join '', map {', '.$tree->getMapping($_)} $tree->getFieldNames;
215 $extra ||= '';
216  
217 my @parents = @{
218 $dbh->selectall_arrayref("select $cols->{parent_col} from $table " .
219 "group by $cols->{parent_col}")
220 };
221 # The prntnums hash is used to save calls to the DB.
222 # if a row is not a parent,
223 # there's no need to query the database about its children.
224 my %prntnums = map {$_->[0] => 1} @parents;
225 delete $prntnums{0}; # or endless recursion...
226  
227 # TO DO: make order-by a user choice instead of hard-coded.
228 my $sth = $dbh->prepare("select $cols->{serial_col}" . $extra .
229 " from $table where $cols->{parent_col}=?" .
230 " order by $cols->{serial_col}");
231 $sth->execute(0);
232 my $root = $sth->fetchrow_hashref;
233  
234 $tree->{_Serial} = $root->{$tree->getMapping('_Serial')};
235 foreach my $field ($tree->getFieldNames) {
236 $tree->setField($field, $root->{$tree->getMapping($field)});
237 }
238 $tree->recursiveTreeBuild($sth, $cols, %prntnums);
239  
240 return $tree;
241 }
242  
243 sub recursiveTreeBuild {
244 my ($self, $sth, $cols, %prntnums) = @_;
245 my $serial = $self->{_Serial};
246  
247 $sth->execute(($serial));
248 my %rows = %{$sth->fetchall_hashref($self->getMapping('_Serial'))};
249
250 foreach my $row (sort {$a <=> $b} keys %rows) {
251 # Note that the mappings for #self are the same as those of $newNode.
252 my %values = map { $_, $rows{$row}->{$self->getMapping($_)} }
253 $self->getFieldNames;
254 $values{NoWrite} = 1;
255  
256 my $newNode = $self->append(%values);
257 $newNode->{_Serial} = $row;
258  
259 next unless (delete $prntnums{$row});
260 $newNode->recursiveTreeBuild($sth, $cols, %prntnums);
261 }
262 }
263  
264 # <delete> deletes the item pointed to by the cursor.
265 # The curser is not changed, which means it effectively moves to the next item.
266 # However it does change to be just after the end if it is already there,
267 # so you won't get an overflow.
268 # Arguments: None.
269 # Returns: The deleted item or undef if none was deleted.
270 # Note that the returned item is invalid since it's deleted from its
271 # table.
272  
273 sub delete {
274 my $self = shift;
275 my $deleted = $self->SUPER::delete;
276  
277 if ($deleted) {
278 $deleted->{Statements}->{delete}->execute($deleted->{_Serial});
279 }
280 return $deleted;
281 }
282  
283 # <update> updates the database when something changes.
284 sub update {
285 my $self = shift;
286 my @values = (map { $self->getField($_) }
287 @{ $self->getFieldNames } );
288 $self->{Statements}->{update}->execute(@values, $self->getNumber);
289 }
290  
291 # <truncate> removes the entire table tied to the tree. Kills the
292 # data structure.
293 # Arguments: None.
294 # Returns: Nothing.
295  
296 sub truncate {
297 my $self = shift;
298 $self->{Statements}->{truncate}->execute;
299 delete $self->{keys %$self}; # Suicide.
300 }
301  
302 # <revert> re-blesses the tree into the parent class, losing DB Tie.
303 # Arguments: None.
304 # Returns: Nothing.
305  
306 sub revert {
307 my $self = shift;
308 my $keep_data = shift;
309  
310 # Remove data specific to this class:
311 unless ($keep_data) {
312 delete $self->{Source};
313 delete $self->{SourceName};
314 delete $self->{Statements};
315 delete $self->{Map};
316 }
317 $_->revert foreach (@{ $self->{Items} });
318  
319 return bless $self, $ISA[0];
320 }
321  
322 #*******************************************************************
323 # Field <-> DB mappings
324  
325 # <_addMapping> adds a mapping to a field if there isn't one already.
326 # You are allowed to add mappings to nonexistent fields.
327 # Arguments: $field - field name.
328 # $map - collumn name to be mapped to the field.
329 # Returns: map name on success, undef otherwise.
330  
331 sub _addMapping {
332 my $self = shift;
333 my ($field, $map) = @_;
334  
335 return $self->{Map}->{$field} = $map unless ($self->{Map}->{$field});
336 return undef;
337 }
338  
339 sub _removeMapping {
340 my $self = shift;
341 my $field = shift;
342 delete $self->{Map}->{$field};
343 }
344  
345 sub getMapping {
346 my $self = shift;
347 my $field = shift;
348 return $self->{Map}->{$field} if (exists $self->{Map}->{$field});
349 return undef;
350 }
351  
352 # <setMapping> changes the collumn mapping for a field.
353 # Arguments: $field - field name.
354 # $value - new column name.
355 # Returns: the new map value (undef if set failed).
356  
357 sub setMapping {
358 my $self = shift;
359 my ($field, $value) = @_;
360  
361 return undef unless (exists $self->{Map}->{$field});
362 $self->{Map}->{$field} = $value;
363 $self->getStatements if _WriteMode;
364 return $self->{Map}->{$field};
365 }
366  
367 #*******************************************************************
368 # Overloaded setters:
369  
370 sub setField {
371 my $self = shift;
372 $self->SUPER::setField(@_);
373 $self->update if (_WriteMode);
374 }
375  
376 sub setFields {
377 my $self = shift;
378 return undef unless ($self->{Fields});
379  
380 my (%fields) = @_;
381 $self->SUPER::setField($_, $fields{$_}) foreach (keys %fields);
382 $self->update if (_WriteMode);
383 }
384  
385 # <addField> adds a field and a mapping if necessary. Fails if can't find
386 # mapping.
387 # Order of search for a mapping:
388 # Argument -> Existing -> Parent -> Fail.
389 # Arguments: $field - field name to add.
390 # $arg - field value.
391 # $map - a mapping for the field.
392 # Returns: undef on failure, true on success.
393  
394 sub addField {
395 my $self = shift;
396 my ($field, $arg, $map) = @_;
397  
398 $map ||= $self->getMapping($field) ||
399 $self->getParentRef->getMapping($field);
400 return undef unless ((defined $field) && $map);
401  
402 $self->_addMapping($field, $map) or $self->setMapping($field, $map);
403 my $rv = $self->SUPER::addField($field, $arg);
404  
405 if (_WriteMode) {
406 $self->getStatements;
407 $self->update;
408 }
409 return $rv;
410 }
411  
412 # <removeField> removes a field and its mapping.
413 # Arguments: $field - name of field to be removed.
414 # $keep_map - wil not delete mapping if true.
415 # Returns: undef on failure, true on success.
416  
417 sub removeField {
418 my $self = shift;
419 my ($field, $keep_map) = @_;
420  
421 my $rv = $self->SUPER::removeField($field);
422 $self->_removeMapping($field) unless ($keep_map);
423 return $rv;
424 }
425  
426 1;
427  
428 =head1 NAME
429  
430 Tree::Numbered::DB - a tree that is stored in / tied to a DB table.
431  
432 =head1 SYNOPSIS
433  
434 use NumberedTree::DBTree;
435 my $dbh = DBI->connect(...);
436  
437 # The easy way:
438 my $tree = NumberedTree::DBTree->read($table, $dbh);
439  
440 # The hard way:
441 my $tree = NumberedTree::DBTree->new(source_name => 'a_table',
442 source => $dbh);
443 while (I aint sick of it) {
444 $tree->append(Value => $newValue);
445 }
446
447 etc.
448
449 =head1 DESCRIPTION
450  
451 Tree::Numbered::DB is a child class of Tree::Numbered that supplies database tying (every change is immediately reflected in the database) and reading using tables that are built to store a tree (the structure is described below). It's basically the same as Tree::Numbered except for some methods. These, and arguments changes for inherited methods, are also described below. For the rest, please refer to the documentation for Tree::Numbered.
452  
453 Tree::Numbered::DB allows you to change the relations between the table and the tree, by adding and deleting fields on runtime, thus giving you a lot of flexibility in working with big tables. The mechanism for that is described below in short. A lot about dealing with fields can be found in the docs for Tree::Numbered.
454  
455 To see a working example, see example.pl in the distribution directory.
456  
457 =head1 CREATING A TABLE FOR THE TREE
458  
459 A table used by this module must have at least 2 columns: the serial number column (by default 'serial') and the parent column (default - 'parent'). There is also a default field column for the field Value ('name') if you want this field to be created. If the default names don't suit you, don't worry - you can supply different names to the constructors.
460  
461 Serial numbers start from any number greater than zero and must be in an auto-incrementing field. Parent numbers of course are the serial numbers of the parent for each node - the root node B<always> takes parent number 0.
462  
463 Example SQL statement to build the table (tested on MySQL):
464 create table places (serial int auto_increment primary key,
465 parent int not null,
466 name varchar(20));
467  
468 =head1 MAPPING FIELDS TO DATA ATTRIBUTES
469  
470 To create a simple menu with one field as value, the defaults will do. However, if you are looking for something more complex, or if you have an existing table and you can't (or won't) change its collumn names, you'll have to tell the module which fields you want, and which column maps to what field. There are two ways of doing this:
471  
472 =over 4
473  
474 =item *
475  
476 Supplying the field name and field value to the constructor (see below).
477  
478 =item *
479  
480 Using the method I<addField>.
481  
482 =back
483  
484 Whenever a field is added in any way, the module tries to resolve its mapping in the following order (low precedence first):
485  
486 Existing mapping (e.g. from a deleted field, or default) -->
487 Mapping for the same field found in the parent of the node -->
488 Mapping suplied as an argument.
489  
490 If no proper mapping can be found, the method that attempted to create the field will fail.
491  
492 When deleting a field, you have the option of keeping its mapping in memory, allowing you to remount that field easily.
493  
494 =head1 METHODS
495  
496 This section only describes methods that are not the same as in Tree::Numbered. Mandatory arguments are marked.
497  
498 =head2 Constructors
499  
500 There are two of them:
501  
502 =over 4
503  
504 =item new (source => I<source>, source_name => I<source_name>, somefield => value, somefield_col => mapping, ...)
505  
506 creates a new tree object that uses an empty table named E<lt>I<source_name>E<gt> using a DBI database handle supplied via the I<source> argument. for each field you want to create, you must give a mapping key in the arguments hash. The key is the name of the field postfixed with B<_col>. The value is the name of the collumn to map to that field.
507  
508 For each mapping key specified, a field will be created, even if you don't specify a starting value.
509  
510 There are also two special mapping keys you can give to replace module defaults: 'serial_col' will change the mapping for the serial number column from the default to whatever you give it, and 'parent_col' will do the same for the collumn that holds the parent numbers.
511  
512 Note that you should not add nodes to an existing tree using this method. Instead, use I<append>.
513  
514 =item read (I<SOURCE_NAME>, I<SOURCE>, MAP)
515  
516 creates a new tree object from a table named I<SOURCE_NAME> that contains tree data as specified above, using a DB handle given in I<SOURCE>. The optional MAP argument takes a reference to a hash of mappings, as described in new. If you do not supply this, the defaults will be used (including the creation of the Value field). As in I<new>, you can use this argument to replace module default mappings.
517  
518 The data read from the DB will be ordered by the serial numbers.
519  
520 =back
521  
522 =head2 Overriden and new methods in this class.
523  
524 Four methods are added to this class:
525  
526 =over 4
527  
528 =item truncate
529  
530 Activates the truncate SQL command, effectively deleting all data in a table, but not the table itself. This also disposes of the tree object, so you'll have to build a new one after using this method.
531  
532 =item revert
533  
534 Removes information that is specific to this class and re-blesses the entire tree into the parent class. Does not lose fields! Use this method if you just want to read the tree, then do stuff that's not related to the DB.
535  
536 =item get/setMapping (I<field>, I<map>)
537  
538 Either sets the mapping of a field to whatever you give it or gets the current value of the mapping for a field (in that case ther's only one argument, the field name).
539  
540 =back
541  
542 Overriden methods that changed arguments:
543  
544 =over 4
545  
546 =item addField(I<name>, value, mapping)
547  
548 Adds a field to its node B<only>. New child nodes will inherit it, but old child nodes will not automatically add that field to themselves. The mapping argument is optional if the module can find the mapping using the search order described above, in 'Mapping fields to data attributes.
549  
550 =back
551  
552 =head1 METHOD SUMMARY (NEW + INHERITED)
553  
554 The following is a categorized list of all available meyhods, for quick reference. Methods that do not appear in the source of this module are marked:
555  
556 =over 4
557  
558 =item Object lifecycle:
559  
560 new, read, delete, *append, truncate, revert.
561  
562 =item Iterating and managing children:
563  
564 *nextNode, *reset, *savePlace, *restorePlace, *childCount, *getSubTree, *follow
565  
566 =item Fields and mappings
567  
568 addField, removeField, setField, setFields, *getField, *getFields, *hasField, addMapping, removeMapping
569  
570 =back
571  
572 =head1 BUGS AND OTHER ISSUES
573  
574 Please report through CPAN:
575 < http://rt.cpan.org/NoAuth/Bugs.html?Dist=Tree-Numbered-DB >
576 or send mail to <bug-Tree-Numbered-DB#rt.cpan.org>
577
578 For sugestions, questions and such, email me directly.
579  
580 =head1 SEE ALSO
581  
582 =over 4
583  
584 =item Tree::Numbered
585  
586 The base class.
587  
588 =item Tree::Numbered::Tools (by Johan Kuuse)
589  
590 Tools for easy handling of the tree.
591  
592 =item Javascript::Menu, HTML::Widget::SideBar
593  
594 Hierarchical widgets for web pages that are Tree::Numbered and use Tree::Numbered::DB optionally.
595  
596 =back
597  
598 =head1 AUTHOR
599  
600 Yosef Meller, E<lt>mellerf@netvision.net.ilE<gt>
601  
602 =head1 COPYRIGHT AND LICENSE
603  
604 Copyright 2003 by Yosef Meller
605  
606 This module is free software; you can redistribute it and/or modify
607 it under the same terms as Perl itself.
608  
609 =cut