--- trunk/lib/WebPAC/Normalize.pm 2005/11/20 20:13:39 74 +++ trunk/lib/WebPAC/Normalize.pm 2009/06/02 13:17:24 1216 @@ -1,683 +1,970 @@ package WebPAC::Normalize; +use Exporter 'import'; +our @EXPORT = qw/ + _set_ds _set_lookup + _set_load_row + _get_ds _clean_ds + _debug + _pack_subfields_hash + + to + search_display search display sorted + + rec1 rec2 rec + frec frec_eq frec_ne + regex prefix suffix surround + first lookup join_with + save_into_lookup + + split_rec_on + + get set + count + + row + rec_array + +/; use warnings; use strict; -use base 'WebPAC::Common'; -use Data::Dumper; -=head1 NAME +#use base qw/WebPAC::Common/; +use Data::Dump qw/dump/; +use Carp qw/confess/; + +# debugging warn(s) +my $debug = 0; +_debug( $debug ); + +# FIXME +use WebPAC::Normalize::ISBN; +push @EXPORT, ( 'isbn_10', 'isbn_13' ); + +use WebPAC::Normalize::MARC; +push @EXPORT, ( qw/ + marc marc_indicators marc_repeatable_subfield + marc_compose marc_leader marc_fixed + marc_duplicate marc_remove marc_count + marc_original_order + marc_template +/); -WebPAC::Normalize - data mungling for normalisation +use Storable qw/dclone/; -=head1 VERSION +=head1 NAME -Version 0.02 +WebPAC::Normalize - describe normalisaton rules using sets =cut -our $VERSION = '0.02'; +our $VERSION = '0.36'; =head1 SYNOPSIS -This package contains code that mungle data to produce normalized format. +This module uses C files to perform normalisation +from input records using perl functions which are specialized for set +processing. + +Sets are implemented as arrays, and normalisation file is valid perl, which +means that you check it's validity before running WebPAC using +C. + +Normalisation can generate multiple output normalized data. For now, supported output +types (on the left side of definition) are: C, C, C and +C. -It contains several assumptions: +=head1 FUNCTIONS -=over +Functions which start with C<_> are private and used by WebPAC internally. +All other functions are available for use within normalisation rules. -=item * +=head2 data_structure -format of fields is defined using C notation for repeatable fields -or C for single (or first) value, where C<123> is field number and -C is subfield. +Return data structure -=item * + my $ds = WebPAC::Normalize::data_structure( + lookup => $lookup_hash, + row => $row, + rules => $normalize_pl_config, + marc_encoding => 'utf-8', + config => $config, + load_row_coderef => sub { + my ($database,$input,$mfn) = @_; + $store->load_row( database => $database, input => $input, id => $mfn ); + }, + ); -source data records (C<$rec>) have unique identifiers in field C<000> +Options C, C and C are mandatory while all +other are optional. -=item * +C is closure only used when executing lookups, so they will +die if it's not defined. -optional C tag at B will be -perl code that is evaluated before producing output (value of field will be -interpolated before that) +This function will B if normalizastion can't be evaled. -=item * +Since this function isn't exported you have to call it with +C. -optional C at B will apply perl -code defined as code ref on format after field substitution to producing -output +=cut -=item * +my $load_row_coderef; -optional C will be then performed. See C. +sub data_structure { + my $arg = {@_}; -=item * + die "need row argument" unless ($arg->{row}); + die "need normalisation argument" unless ($arg->{rules}); -at end, optional Cs rules are resolved. Format rules are similar to -C and can also contain C which is performed after -values are inserted in format. + _set_lookup( $arg->{lookup} ) if defined($arg->{lookup}); + _set_ds( $arg->{row} ); + _set_config( $arg->{config} ) if defined($arg->{config}); + _clean_ds( %{ $arg } ); + $load_row_coderef = $arg->{load_row_coderef}; -=back + no strict 'subs'; + no warnings 'redefine'; + eval "$arg->{rules};"; + die "error evaling $arg->{rules}: $@\n" if ($@); -This also describes order in which transformations are applied (eval, -filter, lookup, format) which is important to undestand when deciding how to -solve your data mungling and normalisation process. + return _get_ds(); +} +=head2 _set_ds +Set current record hash + _set_ds( $rec ); -=head1 FUNCTIONS +=cut -=head2 new +my $rec; -Create new normalisation object +sub _set_ds { + $rec = shift or die "no record hash"; + $WebPAC::Normalize::MARC::rec = $rec; +} - my $n = new WebPAC::Normalize::Something( - filter => { - 'filter_name_1' => sub { - # filter code - return length($_); - }, ... - }, - db => $db_obj, - lookup_regex => $lookup->regex, - lookup => $lookup_obj, - ); +=head2 + + my $rec = _get_rec(); + +=cut + +sub _get_rec { $rec }; + +=head2 _set_config + +Set current config hash + + _set_config( $config ); + +Magic keys are: + +=over 4 -Parametar C defines user supplied snippets of perl code which can -be use with C notation. +=item _ -Recommended parametar C is used to enable parsing of lookups -in structures. If you pass this parametar, you must also pass C -which is C object. +Code of current database + +=item _mfn + +Current MFN + +=back =cut -sub new { - my $class = shift; - my $self = {@_}; - bless($self, $class); +my $config; - my $r = $self->{'lookup_regex'} ? 1 : 0; - my $l = $self->{'lookup'} ? 1 : 0; +sub _set_config { + $config = shift; +} - my $log = $self->_get_logger(); +=head2 _get_ds - # those two must be in pair - if ( ($r & $l) != ($r || $l) ) { - my $log = $self->_get_logger(); - $log->logdie("lookup_regex and lookup must be in pair"); - } +Return hash formatted as data structure + + my $ds = _get_ds(); - $log->logdie("lookup must be WebPAC::Lookup object") if ($self->{'lookup'} && ! $self->{'lookup'}->isa('WebPAC::Lookup')); +=cut + +my $out; - $self ? return $self : return undef; +sub _get_ds { +#warn "## out = ",dump($out); + return $out; } +=head2 _clean_ds -=head2 data_structure +Clean data structure hash for next record -Create in-memory data structure which represents normalized layout from -C. + _clean_ds(); -This structures are used to produce output. +=cut + +sub _clean_ds { + my $a = {@_}; + $out = undef; + WebPAC::Normalize::MARC::_clean(); +} - my $ds = $webpac->data_structure($rec); +=head2 _set_lookup -B +Set current lookup hash -This method will also set C<< $webpac->{'currnet_filename'} >> if there is -C<< >> tag and C<< $webpac->{'headline'} >> if there is -C<< >> tag. + _set_lookup( $lookup ); =cut -sub data_structure { - my $self = shift; +my $lookup; - my $log = $self->_get_logger(); +sub _set_lookup { + $lookup = shift; +} - my $rec = shift; - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); +=head2 _get_lookup - my $cache_file; +Get current lookup hash - if ($self->{'db'}) { - my $ds = $self->{'db'}->load_ds($rec); - $log->debug("load_ds( rec = ", sub { Dumper($rec) }, ") = ", sub { Dumper($ds) }); - return $ds if ($ds); - $log->debug("cache miss, creating"); - } + my $lookup = _get_lookup(); - undef $self->{'currnet_filename'}; - undef $self->{'headline'}; +=cut - my @sorted_tags; - if ($self->{tags_by_order}) { - @sorted_tags = @{$self->{tags_by_order}}; - } else { - @sorted_tags = sort { $self->_sort_by_order } keys %{$self->{'import_xml'}->{'indexer'}}; - $self->{tags_by_order} = \@sorted_tags; - } +sub _get_lookup { + return $lookup; +} - my $ds; +=head2 _set_load_row - $log->debug("tags: ",sub { join(", ",@sorted_tags) }); +Setup code reference which will return L from +L - foreach my $field (@sorted_tags) { + _set_load_row(sub { + my ($database,$input,$mfn) = @_; + $store->load_row( database => $database, input => $input, id => $mfn ); + }); - my $row; +=cut -#print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}); +sub _set_load_row { + my $coderef = shift; + confess "argument isn't CODE" unless ref($coderef) eq 'CODE'; - foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) { - my $format; + $load_row_coderef = $coderef; +} - $log->logdie("expected tag HASH and got $tag") unless (ref($tag) eq 'HASH'); - $format = $tag->{'value'} || $tag->{'content'}; +=head2 _debug - $log->debug("format: $format"); +Change level of debug warnings - my @v; - if ($self->{'lookup_regex'} && $format =~ $self->{'lookup_regex'}) { - @v = $self->fill_in_to_arr($rec,$format); - } else { - @v = $self->parse_to_arr($rec,$format); - } - next if (! @v); + _debug( 2 ); - if ($tag->{'sort'}) { - @v = $self->sort_arr(@v); - } +=cut - # use format? - if ($tag->{'format_name'}) { - @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v; - } +sub _debug { + my $l = shift; + return $debug unless defined($l); + warn "debug level $l",$/ if ($l > 0); + $debug = $l; + $WebPAC::Normalize::MARC::debug = $debug; +} - if ($field eq 'filename') { - $self->{'current_filename'} = join('',@v); - $log->debug("filename: ",$self->{'current_filename'}); - } elsif ($field eq 'headline') { - $self->{'headline'} .= join('',@v); - $log->debug("headline: ",$self->{'headline'}); - next; # don't return headline in data_structure! - } +=head1 Functions to create C - # delimiter will join repeatable fields - if ($tag->{'delimiter'}) { - @v = ( join($tag->{'delimiter'}, @v) ); - } +Those functions generally have to first in your normalization file. - # default types - my @types = qw(display search); - # override by type attribute - @types = ( $tag->{'type'} ) if ($tag->{'type'}); - - foreach my $type (@types) { - # append to previous line? - $log->debug("type: $type ",sub { join(" ",@v) }, $row->{'append'} || 'no append'); - if ($tag->{'append'}) { - - # I will delimit appended part with - # delimiter (or ,) - my $d = $tag->{'delimiter'}; - # default delimiter - $d ||= " "; - - my $last = pop @{$row->{$type}}; - $d = "" if (! $last); - $last .= $d . join($d, @v); - push @{$row->{$type}}, $last; +=head2 to - } else { - push @{$row->{$type}}, @v; - } - } +Generic way to set values for some name + to('field-name', 'name-value' => rec('200','a') ); - } +There are many helpers defined below which might be easier to use. - if ($row) { - $row->{'tag'} = $field; +=cut - # TODO: name_sigular, name_plural - my $name = $self->{'import_xml'}->{'indexer'}->{$field}->{'name'}; - my $row_name = $name ? $self->_x($name) : $field; - - # post-sort all values in field - if ($self->{'import_xml'}->{'indexer'}->{$field}->{'sort'}) { - $log->warn("sort at field tag not implemented"); - } +sub to { + my $type = shift or confess "need type -- BUG?"; + my $name = shift or confess "needs name as first argument"; + my @o = grep { defined($_) && $_ ne '' } @_; + return unless (@o); + $out->{$name}->{$type} = \@o; +} - $ds->{$row_name} = $row; +=head2 search_display - $log->debug("row $field: ",sub { Dumper($row) }); - } +Define output for L and L at the same time - } + search_display('Title', rec('200','a') ); - $log->logdie("there is no current_filename defined! Do you have filename tag in conf/normalize/?.xml") unless ($self->{'current_filename'}); +=cut - $self->{'db'}->save_ds( - ds => $ds, - current_filename => $self->{'current_filename'}, - headline => $self->{'headline'}, - ) if ($self->{'db'}); +sub search_display { + my $name = shift or die "search_display needs name as first argument"; + my @o = grep { defined($_) && $_ ne '' } @_; + return unless (@o); + $out->{$name}->{search} = \@o; + $out->{$name}->{display} = \@o; +} - $log->debug("ds: ", sub { Dumper($ds) }); +=head2 tag - $log->logconfess("data structure returned is not array any more!") if wantarray; +Old name for L, it will probably be removed at one point. - return $ds; +=cut +sub tag { + search_display( @_ ); } -=head2 parse +=head2 display -Perform smart parsing of string, skipping delimiters for fields which aren't -defined. It can also eval code in format starting with C and -return output or nothing depending on eval code. +Define output just for I - my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i); + @v = display('Title', rec('200','a') ); =cut -sub parse { - my $self = shift; +sub display { to( 'display', @_ ) } - my ($rec, $format_utf8, $i) = @_; +=head2 search - return if (! $format_utf8); +Prepare values just for I - my $log = $self->_get_logger(); + @v = search('Title', rec('200','a') ); - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); +=cut - $i = 0 if (! $i); +sub search { to( 'search', @_ ) } - my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'}); +=head2 sorted - my @out; +Insert into lists which will be automatically sorted + + sorted('Title', rec('200','a') ); + +=cut - $log->debug("format: $format"); +sub sorted { to( 'sorted', @_ ) } - my $eval_code; - # remove eval{...} from beginning - $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s); +=head2 row - my $filter_name; - # remove filter{...} from beginning - $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s); +Insert new row of data into output module + + row( column => 'foo', column2 => 'bar' ); + +=cut + +use Data::Dump qw/dump/; + +sub row { + die "array doesn't have odd number of elements but $#_: ",dump( @_ ) if $#_ % 2 == 1; + my $table = shift @_; + push @{ $out->{'_rows'}->{$table} }, {@_}; +} - my $prefix; - my $all_found=0; - while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) { +=head1 Functions to extract data from input - my $del = $1 || ''; - $prefix ||= $del if ($all_found == 0); +This function should be used inside functions to create C described +above. - # repeatable index - my $r = $i; - $r = 0 if (lc("$2") eq 's'); +=head2 _pack_subfields_hash - my $found = 0; - my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found); + @subfields = _pack_subfields_hash( $h ); + $subfields = _pack_subfields_hash( $h, 1 ); - if ($found) { - push @out, $del; - push @out, $tmp; - $all_found += $found; +Return each subfield value in array or pack them all together and return scalar +with subfields (denoted by C<^>) and values. + +=cut + +sub _pack_subfields_hash { + + warn "## _pack_subfields_hash( ",dump(@_), " )\n" if ($debug > 1); + + my ($hash,$include_subfields) = @_; + + # sanity and ease of use + return $hash if (ref($hash) ne 'HASH'); + + my $h = dclone( $hash ); + + if ( defined($h->{subfields}) ) { + my $sfs = delete $h->{subfields} || die "no subfields?"; + my @out; + while (@$sfs) { + my $sf = shift @$sfs; + push @out, '^' . $sf if ($include_subfields); + my $o = shift @$sfs; + if ($o == 0 && ref( $h->{$sf} ) ne 'ARRAY' ) { + # single element subfields are not arrays +#warn "====> $sf $o / $#$sfs ", dump( $sfs, $h->{$sf} ), "\n"; + + push @out, $h->{$sf}; + } else { +#warn "====> $sf $o / $#$sfs ", dump( $sfs, $h->{$sf} ), "\n"; + push @out, $h->{$sf}->[$o]; + } + } + if ($include_subfields) { + return join('', @out); + } else { + return @out; + } + } else { + if ($include_subfields) { + my $out = ''; + foreach my $sf (sort keys %$h) { + if (ref($h->{$sf}) eq 'ARRAY') { + $out .= '^' . $sf . join('^' . $sf, @{ $h->{$sf} }); + } else { + $out .= '^' . $sf . $h->{$sf}; + } + } + return $out; + } else { + # FIXME this should probably be in alphabetical order instead of hash order + values %{$h}; } } +} - return if (! $all_found); +=head2 rec1 - my $out = join('',@out); +Return all values in some field - if ($out) { - # add rest of format (suffix) - $out .= $format; + @v = rec1('200') - # add prefix if not there - $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/); +TODO: order of values is probably same as in source data, need to investigate that - $log->debug("result: $out"); - } +=cut - if ($eval_code) { - my $eval = $self->fill_in($rec,$eval_code,$i) || return; - $log->debug("about to eval{$eval} format: $out"); - return if (! $self->_eval($eval)); - } - - if ($filter_name && $self->{'filter'}->{$filter_name}) { - $log->debug("about to filter{$filter_name} format: $out"); - $out = $self->{'filter'}->{$filter_name}->($out); - return unless(defined($out)); - $log->debug("filter result: $out"); +sub rec1 { + my $f = shift; + warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1); + return unless (defined($rec) && defined($rec->{$f})); + warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1); + if (ref($rec->{$f}) eq 'ARRAY') { + my @out; + foreach my $h ( @{ $rec->{$f} } ) { + if (ref($h) eq 'HASH') { + push @out, ( _pack_subfields_hash( $h ) ); + } else { + push @out, $h; + } + } + return @out; + } elsif( defined($rec->{$f}) ) { + return $rec->{$f}; } - - return $out; } -=head2 parse_to_arr +=head2 rec2 -Similar to C, but returns array of all repeatable fields +Return all values in specific field and subfield - my @arr = $webpac->parse_to_arr($rec,'v250^a'); + @v = rec2('200','a') =cut -sub parse_to_arr { - my $self = shift; +sub rec2 { + my $f = shift; + return unless (defined($rec && $rec->{$f})); + my $sf = shift; + warn "rec2($f,$sf) = ", dump( $rec->{$f} ), $/ if ($debug > 1); + return map { + if (ref($_->{$sf}) eq 'ARRAY') { + @{ $_->{$sf} }; + } else { + $_->{$sf}; + } + } grep { ref($_) eq 'HASH' && defined $_->{$sf} } @{ $rec->{$f} }; +} + +=head2 rec - my ($rec, $format_utf8) = @_; +syntaxtic sugar for - my $log = $self->_get_logger(); + @v = rec('200') + @v = rec('200','a') - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - return if (! $format_utf8); +If rec() returns just single value, it will +return scalar, not array. - my $i = 0; - my @arr; +=cut - while (my $v = $self->parse($rec,$format_utf8,$i++)) { - push @arr, $v; +sub rec { + my @out; + if ($#_ == 0) { + @out = rec1(@_); + } elsif ($#_ == 1) { + @out = rec2(@_); + } + if ($#out == 0 && ! wantarray) { + return $out[0]; + } elsif (@out) { + return @out; + } else { + return ''; } +} - $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr); +=head2 frec - return @arr; -} +Returns first value from field + $v = frec('200'); + $v = frec('200','a'); -=head2 fill_in +=cut -Workhourse of all: takes record from in-memory structure of database and -strings with placeholders and returns string or array of with substituted -values from record. +sub frec { + my @out = rec(@_); + warn "rec(",dump(@_),") has more than one return value, ignoring\n" if $#out > 0; + return shift @out; +} - my $text = $webpac->fill_in($rec,'v250^a'); +=head2 frec_eq -Optional argument is ordinal number for repeatable fields. By default, -it's assume to be first repeatable field (fields are perl array, so first -element is 0). -Following example will read second value from repeatable field. +=head2 frec_ne - my $text = $webpac->fill_in($rec,'Title: v250^a',1); +Check if first values from two fields are same or different -This function B perform parsing of format to inteligenty skip -delimiters before fields which aren't used. + if ( frec_eq( 900 => 'a', 910 => 'c' ) ) { + # values are same + } else { + # values are different + } -This method will automatically decode UTF-8 string to local code page -if needed. +Strictly speaking C and C wouldn't be needed if you +could write something like: + + if ( frec( '900','a' ) eq frec( '910','c' ) ) { + # yada tada + } + +but you can't since our parser L will remove all whitespaces +in order to parse text and create invalid function C. =cut -sub fill_in { - my $self = shift; +sub frec_eq { + my ( $f1,$sf1, $f2, $sf2 ) = @_; + return (rec( $f1, $sf1 ))[0] eq (rec( $f2, $sf2 ))[0]; +} - my $log = $self->_get_logger(); +sub frec_ne { + return ! frec_eq( @_ ); +} - my $rec = shift || $log->logconfess("need data record"); - my $format = shift || $log->logconfess("need format to parse"); - # iteration (for repeatable fields) - my $i = shift || 0; +=head2 regex - $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999)); +Apply regex to some or all values - # FIXME remove for speedup? - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); + @v = regex( 's/foo/bar/g', @v ); - if (utf8::is_utf8($format)) { - $format = $self->_x($format); +=cut + +sub regex { + my $r = shift; + my @out; + #warn "r: $r\n", dump(\@_); + foreach my $t (@_) { + next unless ($t); + eval "\$t =~ $r"; + push @out, $t if ($t && $t ne ''); } + return @out; +} - my $found = 0; +=head2 prefix - my $eval_code; - # remove eval{...} from beginning - $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s); +Prefix all values with a string - my $filter_name; - # remove filter{...} from beginning - $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s); + @v = prefix( 'my_', @v ); - # do actual replacement of placeholders - # repeatable fields - $format =~ s/v(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,$i,\$found)/ges; - # non-repeatable fields - $format =~ s/s(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,0,\$found)/ges; +=cut - if ($found) { - $log->debug("format: $format"); - if ($eval_code) { - my $eval = $self->fill_in($rec,$eval_code,$i); - return if (! $self->_eval($eval)); - } - if ($filter_name && $self->{'filter'}->{$filter_name}) { - $log->debug("filter '$filter_name' for $format"); - $format = $self->{'filter'}->{$filter_name}->($format); - return unless(defined($format)); - $log->debug("filter result: $format"); - } - # do we have lookups? - if ($self->{'lookup'}) { - if ($self->{'lookup'}->can('lookup')) { - return $self->{'lookup'}->lookup($format); - } else { - $log->warn("Have lookup object but can't invoke lookup method"); - } - } else { - return $format; - } - } else { - return; - } +sub prefix { + my $p = shift; + return @_ unless defined( $p ); + return map { $p . $_ } grep { defined($_) } @_; } +=head2 suffix -=head2 fill_in_to_arr +suffix all values with a string -Similar to C, but returns array of all repeatable fields. Usable -for fields which have lookups, so they shouldn't be parsed but rather -Ced. - - my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]'); + @v = suffix( '_my', @v ); =cut -sub fill_in_to_arr { - my $self = shift; +sub suffix { + my $s = shift; + return @_ unless defined( $s ); + return map { $_ . $s } grep { defined($_) } @_; +} + +=head2 surround - my ($rec, $format_utf8) = @_; +surround all values with a two strings - my $log = $self->_get_logger(); + @v = surround( 'prefix_', '_suffix', @v ); - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - return if (! $format_utf8); +=cut + +sub surround { + my $p = shift; + my $s = shift; + $p = '' unless defined( $p ); + $s = '' unless defined( $s ); + return map { $p . $_ . $s } grep { defined($_) } @_; +} - my $i = 0; - my @arr; +=head2 first - while (my @v = $self->fill_in($rec,$format_utf8,$i++)) { - push @arr, @v; - } +Return first element - $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr); + $v = first( @v ); - return @arr; +=cut + +sub first { + my $r = shift; + return $r; } +=head2 lookup -=head2 get_data +Consult lookup hashes for some value -Returns value from record. + @v = lookup( + sub { + 'ffkk/peri/mfn'.rec('000') + }, + 'ffkk','peri','200-a-200-e', + sub { + first(rec(200,'a')).' '.first(rec('200','e')) + } + ); - my $text = $self->get_data(\$rec,$f,$sf,$i,\$found); +Code like above will be B using L from +normal lookup definition in C which looks like: -Arguments are: -record reference C<$rec>, -field C<$f>, -optional subfiled C<$sf>, -index for repeatable values C<$i>. + lookup( + # which results to return from record recorded in lookup + sub { 'ffkk/peri/mfn' . rec('000') }, + # from which database and input + 'ffkk','peri', + # such that following values match + sub { first(rec(200,'a')) . ' ' . first(rec('200','e')) }, + # if this part is missing, we will try to match same fields + # from lookup record and current one, or you can override + # which records to use from current record using + sub { rec('900','x') . ' ' . rec('900','y') }, + ) -Optinal variable C<$found> will be incremeted if there -is field. +You can think about this lookup as SQL (if that helps): -Returns value or empty string. + select + sub { what } + from + database, input + where + sub { filter from lookuped record } + having + sub { optional filter on current record } + +Easy as pie, right? =cut -sub get_data { - my $self = shift; +sub lookup { + my ($what, $database, $input, $key, $having) = @_; - my ($rec,$f,$sf,$i,$found) = @_; + confess "lookup needs 5 arguments: what, database, input, key, having\n" unless ($#_ == 4); - if ($$rec->{$f}) { - return '' if (! $$rec->{$f}->[$i]); - no strict 'refs'; - if ($sf && $$rec->{$f}->[$i]->{$sf}) { - $$found++ if (defined($$found)); - return $$rec->{$f}->[$i]->{$sf}; - } elsif (! $sf && $$rec->{$f}->[$i]) { - $$found++ if (defined($$found)); - # it still might have subfield, just - # not specified, so we'll dump all - if ($$rec->{$f}->[$i] =~ /HASH/o) { - my $out; - foreach my $k (keys %{$$rec->{$f}->[$i]}) { - $out .= $$rec->{$f}->[$i]->{$k}." "; - } - return $out; - } else { - return $$rec->{$f}->[$i]; - } - } else { - return ''; + warn "## lookup ($database, $input, $key)", $/ if ($debug > 1); + return unless (defined($lookup->{$database}->{$input}->{$key})); + + confess "lookup really need load_row_coderef added to data_structure\n" unless ($load_row_coderef); + + my $mfns; + my @having = $having->(); + + warn "## having = ", dump( @having ) if ($debug > 2); + + foreach my $h ( @having ) { + if (defined($lookup->{$database}->{$input}->{$key}->{$h})) { + warn "lookup for $database/$input/$key/$h return ",dump($lookup->{$database}->{$input}->{$key}->{$h}),"\n" if ($debug); + $mfns->{$_}++ foreach keys %{ $lookup->{$database}->{$input}->{$key}->{$h} }; } + } + + return unless ($mfns); + + my @mfns = sort keys %$mfns; + + warn "# lookup loading $database/$input/$key mfn ", join(",",@mfns)," having ",dump(@having),"\n" if ($debug); + + my $old_rec = $rec; + my @out; + + foreach my $mfn (@mfns) { + $rec = $load_row_coderef->( $database, $input, $mfn ); + + warn "got $database/$input/$mfn = ", dump($rec), $/ if ($debug); + + my @vals = $what->(); + + push @out, ( @vals ); + + warn "lookup for mfn $mfn returned ", dump(@vals), $/ if ($debug); + } + +# if (ref($lookup->{$k}) eq 'ARRAY') { +# return @{ $lookup->{$k} }; +# } else { +# return $lookup->{$k}; +# } + + $rec = $old_rec; + + warn "## lookup returns = ", dump(@out), $/ if ($debug); + + if ($#out == 0) { + return $out[0]; } else { - return ''; + return @out; } } +=head2 save_into_lookup + +Save value into lookup. It associates current database, input +and specific keys with one or more values which will be +associated over MFN. -=head2 apply_format +MFN will be extracted from first occurence current of field 000 +in current record, or if it doesn't exist from L<_set_config> C<_mfn>. -Apply format specified in tag with C and -C. + my $nr = save_into_lookup($database,$input,$key,sub { + # code which produce one or more values + }); - my $text = $webpac->apply_format($format_name,$format_delimiter,$data); +It returns number of items saved. -Formats can contain C if you need them. +This function shouldn't be called directly, it's called from code created by +L. =cut -sub apply_format { - my $self = shift; +sub save_into_lookup { + my ($database,$input,$key,$coderef) = @_; + die "save_into_lookup needs database" unless defined($database); + die "save_into_lookup needs input" unless defined($input); + die "save_into_lookup needs key" unless defined($key); + die "save_into_lookup needs CODE" unless ( defined($coderef) && ref($coderef) eq 'CODE' ); - my ($name,$delimiter,$data) = @_; + warn "## save_into_lookup rec = ", dump($rec), " config = ", dump($config), $/ if ($debug > 2); - my $log = $self->_get_logger(); + my $mfn = + defined($rec->{'000'}->[0]) ? $rec->{'000'}->[0] : + defined($config->{_mfn}) ? $config->{_mfn} : + die "mfn not defined or zero"; - if (! $self->{'import_xml'}->{'format'}->{$name}) { - $log->warn(" is not defined in ",$self->{'import_xml_file'}); - return $data; + my $nr = 0; + + foreach my $v ( $coderef->() ) { + $lookup->{$database}->{$input}->{$key}->{$v}->{$mfn}++; + warn "# saved lookup $database/$input/$key [$v] $mfn\n" if ($debug > 1); + $nr++; } - $log->warn("no delimiter for format $name") if (! $delimiter); + return $nr; +} - my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'"); +=head2 config - my @data = split(/\Q$delimiter\E/, $data); +Consult config values stored in C - my $out = sprintf($format, @data); - $log->debug("using format $name [$format] on $data to produce: $out"); + # return database code (key under databases in yaml) + $database_code = config(); # use _ from hash + $database_name = config('name'); + $database_input_name = config('input name'); + +Up to three levels are supported. + +=cut - if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) { - return $self->{'lookup'}->lookup($out); +sub config { + return unless ($config); + + my $p = shift; + + $p ||= ''; + + my $v; + + warn "### getting config($p)\n" if ($debug > 1); + + my @p = split(/\s+/,$p); + if ($#p < 0) { + $v = $config->{ '_' }; # special, database code } else { - return $out; + + my $c = dclone( $config ); + + foreach my $k (@p) { + warn "### k: $k c = ",dump($c),$/ if ($debug > 1); + if (ref($c) eq 'ARRAY') { + $c = shift @$c; + warn "config($p) taking first occurence of '$k', probably not what you wanted!\n"; + last; + } + + if (! defined($c->{$k}) ) { + $c = undef; + last; + } else { + $c = $c->{$k}; + } + } + $v = $c if ($c); + } + warn "## config( '$p' ) = ",dump( $v ),$/ if ($v && $debug); + warn "config( '$p' ) is empty\n" if (! $v); + + return $v; } -=head2 sort_arr +=head2 id + +Returns unique id of this record -Sort array ignoring case and html in data + $id = id(); - my @sorted = $webpac->sort_arr(@unsorted); +Returns C<42/2> for 2nd occurence of MFN 42. =cut -sub sort_arr { - my $self = shift; +sub id { + my $mfn = $config->{_mfn} || die "no _mfn in config data"; + return $mfn . ( WebPAC::Normalize::MARC::_created_marc_records() || '' ); +} + +=head2 join_with - my $log = $self->_get_logger(); +Joins walues with some delimiter - # FIXME add Schwartzian Transformation? + $v = join_with(", ", @v); - my @sorted = sort { - $a =~ s#<[^>]+/*>##; - $b =~ s#<[^>]+/*>##; - lc($b) cmp lc($a) - } @_; - $log->debug("sorted values: ",sub { join(", ",@sorted) }); +=cut - return @sorted; +sub join_with { + my $d = shift; + warn "### join_with('$d',",dump(@_),")\n" if ($debug > 2); + my $v = join($d, grep { defined($_) && $_ ne '' } @_); + return '' unless defined($v); + return $v; } +=head2 split_rec_on + +Split record subfield on some regex and take one of parts out -=head1 INTERNAL METHODS + $a_before_semi_column = + split_rec_on('200','a', /\s*;\s*/, $part); -=head2 _sort_by_order +C<$part> is optional number of element. First element is +B<1>, not 0! -Sort xml tags data structure accoding to C attribute. +If there is no C<$part> parameter or C<$part> is 0, this function will +return all values produced by splitting. =cut -sub _sort_by_order { - my $self = shift; +sub split_rec_on { + die "split_rec_on need (fld,sf,regex[,part]" if ($#_ < 2); - my $va = $self->{'import_xml'}->{'indexer'}->{$a}->{'order'} || - $self->{'import_xml'}->{'indexer'}->{$a}; - my $vb = $self->{'import_xml'}->{'indexer'}->{$b}->{'order'} || - $self->{'import_xml'}->{'indexer'}->{$b}; + my ($fld, $sf, $regex, $part) = @_; + warn "### regex ", ref($regex), $regex, $/ if ($debug > 2); - return $va <=> $vb; + my @r = rec( $fld, $sf ); + my $v = shift @r; + warn "### first rec($fld,$sf) = ",dump($v),$/ if ($debug > 2); + + return '' if ( ! defined($v) || $v =~ /^\s*$/); + + my @s = split( $regex, $v ); + warn "## split_rec_on($fld,$sf,$regex,$part) = ",dump(@s),$/ if ($debug > 1); + if ($part && $part > 0) { + return $s[ $part - 1 ]; + } else { + return @s; + } } -=head2 _x +my $hash; -Convert strings from C encoding into application -specific encoding (optinally specified using C to C -constructor). +=head2 set + + set( key => 'value' ); + +=cut - my $text = $n->_x('normalize text string'); +sub set { + my ($k,$v) = @_; + warn "## set ( $k => ", dump($v), " )", $/ if ( $debug ); + $hash->{$k} = $v; +}; -This is a stub so that other modules doesn't have to implement it. +=head2 get + + get( 'key' ); =cut -sub _x { - my $self = shift; - return shift; +sub get { + my $k = shift || return; + my $v = $hash->{$k}; + warn "## get $k = ", dump( $v ), $/ if ( $debug ); + return $v; } +=head2 count + + if ( count( @result ) == 1 ) { + # do something if only 1 result is there + } -=head1 AUTHOR +=cut -Dobrica Pavlinusic, C<< >> +sub count { + warn "## count ",dump(@_),$/ if ( $debug ); + return @_ . ''; +} -=head1 COPYRIGHT & LICENSE +=head2 rec_array -Copyright 2005 Dobrica Pavlinusic, All Rights Reserved. +Always return field as array -This program is free software; you can redistribute it and/or modify it -under the same terms as Perl itself. + foreach my $d ( rec_array('field') ) { + warn $d; + } =cut -1; # End of WebPAC::DB +sub rec_array { + my $d = $rec->{ $_[0] }; + return @$d if ref($d) eq 'ARRAY'; + return ($d); +} + +# END +1;