--- trunk/lib/WebPAC/Normalize.pm 2005/07/17 22:48:25 22 +++ trunk/lib/WebPAC/Normalize.pm 2009/05/30 15:26:25 1210 @@ -1,650 +1,960 @@ 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 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.01 +WebPAC::Normalize - describe normalisaton rules using sets =cut -our $VERSION = '0.01'; +our $VERSION = '0.36'; =head1 SYNOPSIS -This package contains code that mungle data to produce normalized format. - -It contains several assumptions: +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. -=over +=head1 FUNCTIONS -=item * +Functions which start with C<_> are private and used by WebPAC internally. +All other functions are available for use within normalisation rules. -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. +=head2 data_structure -=item * +Return data structure -source data records (C<$rec>) have unique identifiers in field C<000> + 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 ); + }, + ); -=item * +Options C, C and C are mandatory while all +other are optional. -optional C tag at B will be -perl code that is evaluated before producing output (value of field will be -interpolated before that) +C is closure only used when executing lookups, so they will +die if it's not defined. -=item * +This function will B if normalizastion can't be evaled. -optional C at B will apply perl -code defined as code ref on format after field substitution to producing -output +Since this function isn't exported you have to call it with +C. -=item * +=cut -optional C will be then performed. See C. +my $load_row_coderef; -=item * +sub data_structure { + my $arg = {@_}; -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. + die "need row argument" unless ($arg->{row}); + die "need normalisation argument" unless ($arg->{rules}); -=back + _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}; -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. + no strict 'subs'; + no warnings 'redefine'; + eval "$arg->{rules};"; + die "error evaling $arg->{rules}: $@\n" if ($@); + return _get_ds(); +} +=head2 _set_ds +Set current record hash -=head1 FUNCTIONS + _set_ds( $rec ); -=head2 new +=cut -Create new normalisation object +my $rec; - my $n = new WebPAC::Normalize::Something( - filter => { - 'filter_name_1' => sub { - # filter code - return length($_); - }, ... - }, - db => $webpac_db_obj, - lookup_regex => $lookup->regex, - ); +sub _set_ds { + $rec = shift or die "no record hash"; + $WebPAC::Normalize::MARC::rec = $rec; +} -Parametar C defines user supplied snippets of perl code which can -be use with C notation. +=head2 -Recommended parametar C is used to enable parsing of lookups -in structures. + my $rec = _get_rec(); =cut -sub new { - my $class = shift; - my $self = {@_}; - bless($self, $class); +sub _get_rec { $rec }; - $self ? return $self : return undef; +sub rec_array { + my $d = $rec->{ $_[0] }; + return @$d if ref($d) eq 'ARRAY'; + die "field $_[0] not array: ",dump( $d ); } +=head2 _set_config -=head2 data_structure +Set current config hash -Create in-memory data structure which represents normalized layout from -C. + _set_config( $config ); -This structures are used to produce output. +Magic keys are: - my @ds = $webpac->data_structure($rec); +=over 4 -B +=item _ -This method will also set C<< $webpac->{'currnet_filename'} >> if there is -C<< >> tag and C<< $webpac->{'headline'} >> if there is -C<< >> tag. +Code of current database -=cut +=item _mfn -sub data_structure { - my $self = shift; +Current MFN - my $log = $self->_get_logger(); +=back - my $rec = shift; - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); +=cut - my $cache_file; +my $config; - if ($self->{'db'}) { - my @ds = $self->{'db'}->load_ds($rec); - return @ds if (@ds); - } +sub _set_config { + $config = shift; +} - undef $self->{'currnet_filename'}; - undef $self->{'headline'}; +=head2 _get_ds - 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; - } +Return hash formatted as data structure - my @ds; + my $ds = _get_ds(); - $log->debug("tags: ",sub { join(", ",@sorted_tags) }); +=cut - foreach my $field (@sorted_tags) { +my $out; - my $row; +sub _get_ds { +#warn "## out = ",dump($out); + return $out; +} -#print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}); +=head2 _clean_ds - foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) { - my $format = $tag->{'value'} || $tag->{'content'}; +Clean data structure hash for next record - $log->debug("format: $format"); + _clean_ds(); - 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); +=cut - if ($tag->{'sort'}) { - @v = $self->sort_arr(@v); - } +sub _clean_ds { + my $a = {@_}; + $out = undef; + WebPAC::Normalize::MARC::_clean(); +} - # use format? - if ($tag->{'format_name'}) { - @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v; - } +=head2 _set_lookup - 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! - } +Set current lookup hash - # delimiter will join repeatable fields - if ($tag->{'delimiter'}) { - @v = ( join($tag->{'delimiter'}, @v) ); - } + _set_lookup( $lookup ); - # default types - my @types = qw(display swish); - # 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; +=cut - } else { - push @{$row->{$type}}, @v; - } - } +my $lookup; +sub _set_lookup { + $lookup = shift; +} - } +=head2 _get_lookup - if ($row) { - $row->{'tag'} = $field; +Get current lookup hash - # TODO: name_sigular, name_plural - my $name = $self->{'import_xml'}->{'indexer'}->{$field}->{'name'}; - $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"); - } + my $lookup = _get_lookup(); - push @ds, $row; +=cut - $log->debug("row $field: ",sub { Dumper($row) }); - } +sub _get_lookup { + return $lookup; +} - } +=head2 _set_load_row + +Setup code reference which will return L from +L + + _set_load_row(sub { + my ($database,$input,$mfn) = @_; + $store->load_row( database => $database, input => $input, id => $mfn ); + }); - $self->{'db'}->save_ds( - ds => \@ds, - current_filename => $self->{'current_filename'}, - headline => $self->{'headline'}, - ) if ($self->{'db'}); +=cut - return @ds; +sub _set_load_row { + my $coderef = shift; + confess "argument isn't CODE" unless ref($coderef) eq 'CODE'; + $load_row_coderef = $coderef; } -=head2 parse +=head2 _debug -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. +Change level of debug warnings - my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i); + _debug( 2 ); =cut -sub parse { - my $self = shift; +sub _debug { + my $l = shift; + return $debug unless defined($l); + warn "debug level $l",$/ if ($l > 0); + $debug = $l; + $WebPAC::Normalize::MARC::debug = $debug; +} - my ($rec, $format_utf8, $i) = @_; +=head1 Functions to create C - return if (! $format_utf8); +Those functions generally have to first in your normalization file. - my $log = $self->_get_logger(); +=head2 to - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); +Generic way to set values for some name - $i = 0 if (! $i); + to('field-name', 'name-value' => rec('200','a') ); - my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'}); +There are many helpers defined below which might be easier to use. - my @out; +=cut - $log->debug("format: $format"); +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; +} - my $eval_code; - # remove eval{...} from beginning - $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s); +=head2 search_display - my $filter_name; - # remove filter{...} from beginning - $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s); +Define output for L and L at the same time - my $prefix; - my $all_found=0; + search_display('Title', rec('200','a') ); - while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) { +=cut - my $del = $1 || ''; - $prefix ||= $del if ($all_found == 0); +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; +} - # repeatable index - my $r = $i; - $r = 0 if (lc("$2") eq 's'); +=head2 tag - my $found = 0; - my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found); +Old name for L, it will probably be removed at one point. - if ($found) { - push @out, $del; - push @out, $tmp; - $all_found += $found; - } - } +=cut - return if (! $all_found); +sub tag { + search_display( @_ ); +} - my $out = join('',@out); +=head2 display - if ($out) { - # add rest of format (suffix) - $out .= $format; +Define output just for I - # add prefix if not there - $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/); + @v = display('Title', rec('200','a') ); - $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 display { to( 'display', @_ ) } - return $out; -} +=head2 search -=head2 parse_to_arr +Prepare values just for I -Similar to C, but returns array of all repeatable fields - - my @arr = $webpac->parse_to_arr($rec,'v250^a'); + @v = search('Title', rec('200','a') ); =cut -sub parse_to_arr { - my $self = shift; +sub search { to( 'search', @_ ) } - my ($rec, $format_utf8) = @_; +=head2 sorted - my $log = $self->_get_logger(); +Insert into lists which will be automatically sorted - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - return if (! $format_utf8); + sorted('Title', rec('200','a') ); - my $i = 0; - my @arr; +=cut - while (my $v = $self->parse($rec,$format_utf8,$i++)) { - push @arr, $v; - } +sub sorted { to( 'sorted', @_ ) } - $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr); +=head2 row - return @arr; -} +Insert new row of data into output module + row( column => 'foo', column2 => 'bar' ); -=head2 fill_in +=cut + +use Data::Dump qw/dump/; -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 row { + die "array doesn't have odd number of elements but $#_: ",dump( @_ ) if $#_ % 2 == 1; + my $table = shift @_; + push @{ $out->{'_rows'}->{$table} }, {@_}; +} - my $text = $webpac->fill_in($rec,'v250^a'); -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. +=head1 Functions to extract data from input - my $text = $webpac->fill_in($rec,'Title: v250^a',1); +This function should be used inside functions to create C described +above. -This function B perform parsing of format to inteligenty skip -delimiters before fields which aren't used. +=head2 _pack_subfields_hash -This method will automatically decode UTF-8 string to local code page -if needed. + @subfields = _pack_subfields_hash( $h ); + $subfields = _pack_subfields_hash( $h, 1 ); + +Return each subfield value in array or pack them all together and return scalar +with subfields (denoted by C<^>) and values. =cut -sub fill_in { - my $self = shift; +sub _pack_subfields_hash { + + warn "## _pack_subfields_hash( ",dump(@_), " )\n" if ($debug > 1); - my $log = $self->_get_logger(); + my ($hash,$include_subfields) = @_; - 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; + # sanity and ease of use + return $hash if (ref($hash) ne 'HASH'); - $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999)); + my $h = dclone( $hash ); - # FIXME remove for speedup? - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); + 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"; - if (utf8::is_utf8($format)) { - $format = $self->_x($format); + 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}; + } } +} - my $found = 0; +=head2 rec1 - my $eval_code; - # remove eval{...} from beginning - $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s); +Return all values in some field - my $filter_name; - # remove filter{...} from beginning - $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s); + @v = rec1('200') - # 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; +TODO: order of values is probably same as in source data, need to investigate that - 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"); +=cut + +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; + } } - # do we have lookups? - if ($self->{'lookup'}) { - return $self->lookup($format); + return @out; + } elsif( defined($rec->{$f}) ) { + return $rec->{$f}; + } +} + +=head2 rec2 + +Return all values in specific field and subfield + + @v = rec2('200','a') + +=cut + +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 { - return $format; + $_->{$sf}; } + } grep { ref($_) eq 'HASH' && defined $_->{$sf} } @{ $rec->{$f} }; +} + +=head2 rec + +syntaxtic sugar for + + @v = rec('200') + @v = rec('200','a') + +If rec() returns just single value, it will +return scalar, not array. + +=cut + +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; + return ''; } } +=head2 frec + +Returns first value from field + + $v = frec('200'); + $v = frec('200','a'); + +=cut + +sub frec { + my @out = rec(@_); + warn "rec(",dump(@_),") has more than one return value, ignoring\n" if $#out > 0; + return shift @out; +} + +=head2 frec_eq + +=head2 frec_ne + +Check if first values from two fields are same or different + + if ( frec_eq( 900 => 'a', 910 => 'c' ) ) { + # values are same + } else { + # values are different + } -=head2 fill_in_to_arr +Strictly speaking C and C wouldn't be needed if you +could write something like: -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. + if ( frec( '900','a' ) eq frec( '910','c' ) ) { + # yada tada + } - my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]'); +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_to_arr { - my $self = shift; +sub frec_eq { + my ( $f1,$sf1, $f2, $sf2 ) = @_; + return (rec( $f1, $sf1 ))[0] eq (rec( $f2, $sf2 ))[0]; +} + +sub frec_ne { + return ! frec_eq( @_ ); +} - my ($rec, $format_utf8) = @_; +=head2 regex - my $log = $self->_get_logger(); +Apply regex to some or all values - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - return if (! $format_utf8); + @v = regex( 's/foo/bar/g', @v ); - my $i = 0; - my @arr; +=cut - while (my @v = $self->fill_in($rec,$format_utf8,$i++)) { - push @arr, @v; +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; +} + +=head2 prefix + +Prefix all values with a string + + @v = prefix( 'my_', @v ); + +=cut + +sub prefix { + my $p = shift; + return @_ unless defined( $p ); + return map { $p . $_ } grep { defined($_) } @_; +} - $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr); +=head2 suffix - return @arr; +suffix all values with a string + + @v = suffix( '_my', @v ); + +=cut + +sub suffix { + my $s = shift; + return @_ unless defined( $s ); + return map { $_ . $s } grep { defined($_) } @_; } +=head2 surround -=head2 get_data +surround all values with a two strings -Returns value from record. + @v = surround( 'prefix_', '_suffix', @v ); - my $text = $self->get_data(\$rec,$f,$sf,$i,\$found); +=cut + +sub surround { + my $p = shift; + my $s = shift; + $p = '' unless defined( $p ); + $s = '' unless defined( $s ); + return map { $p . $_ . $s } grep { defined($_) } @_; +} -Arguments are: -record reference C<$rec>, -field C<$f>, -optional subfiled C<$sf>, -index for repeatable values C<$i>. +=head2 first -Optinal variable C<$found> will be incremeted if there -is field. +Return first element -Returns value or empty string. + $v = first( @v ); =cut -sub get_data { - my $self = shift; +sub first { + my $r = shift; + return $r; +} - my ($rec,$f,$sf,$i,$found) = @_; +=head2 lookup - 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 ($$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]; - } +Consult lookup hashes for some value + + @v = lookup( + sub { + 'ffkk/peri/mfn'.rec('000') + }, + 'ffkk','peri','200-a-200-e', + sub { + first(rec(200,'a')).' '.first(rec('200','e')) + } + ); + +Code like above will be B using L from +normal lookup definition in C which looks like: + + 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') }, + ) + +You can think about this lookup as SQL (if that helps): + + 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 lookup { + my ($what, $database, $input, $key, $having) = @_; + + confess "lookup needs 5 arguments: what, database, input, key, having\n" unless ($#_ == 4); + + 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' ); + + warn "## save_into_lookup rec = ", dump($rec), " config = ", dump($config), $/ if ($debug > 2); - my ($name,$delimiter,$data) = @_; + my $mfn = + defined($rec->{'000'}->[0]) ? $rec->{'000'}->[0] : + defined($config->{_mfn}) ? $config->{_mfn} : + die "mfn not defined or zero"; - my $log = $self->_get_logger(); + my $nr = 0; - if (! $self->{'import_xml'}->{'format'}->{$name}) { - $log->warn(" is not defined in ",$self->{'import_xml_file'}); - return $data; + 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; +} + +=head2 config + +Consult config values stored in C + + # 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 + +sub config { + return unless ($config); - my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'"); + my $p = shift; - my @data = split(/\Q$delimiter\E/, $data); + $p ||= ''; - my $out = sprintf($format, @data); - $log->debug("using format $name [$format] on $data to produce: $out"); + my $v; - if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) { - return $self->lookup($out); + 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() || '' ); +} - my $log = $self->_get_logger(); +=head2 join_with - # FIXME add Schwartzian Transformation? +Joins walues with some delimiter - my @sorted = sort { - $a =~ s#<[^>]+/*>##; - $b =~ s#<[^>]+/*>##; - lc($b) cmp lc($a) - } @_; - $log->debug("sorted values: ",sub { join(", ",@sorted) }); + $v = join_with(", ", @v); - return @sorted; +=cut + +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 -=head1 INTERNAL METHODS +Split record subfield on some regex and take one of parts out -=head2 _sort_by_order + $a_before_semi_column = + split_rec_on('200','a', /\s*;\s*/, $part); -Sort xml tags data structure accoding to C attribute. +C<$part> is optional number of element. First element is +B<1>, not 0! + +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); -=head2 _x + return '' if ( ! defined($v) || $v =~ /^\s*$/); -Convert strings from C encoding into application -specific encoding (optinally specified using C to C -constructor). + 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; + } +} - my $text = $n->_x('normalize text string'); +my $hash; -This is a stub so that other modules doesn't have to implement it. +=head2 set + + set( key => 'value' ); =cut -sub _x { - my $self = shift; - return shift; -} +sub set { + my ($k,$v) = @_; + warn "## set ( $k => ", dump($v), " )", $/ if ( $debug ); + $hash->{$k} = $v; +}; +=head2 get -=head1 AUTHOR + get( 'key' ); -Dobrica Pavlinusic, C<< >> +=cut -=head1 COPYRIGHT & LICENSE +sub get { + my $k = shift || return; + my $v = $hash->{$k}; + warn "## get $k = ", dump( $v ), $/ if ( $debug ); + return $v; +} -Copyright 2005 Dobrica Pavlinusic, All Rights Reserved. +=head2 count -This program is free software; you can redistribute it and/or modify it -under the same terms as Perl itself. + if ( count( @result ) == 1 ) { + # do something if only 1 result is there + } =cut -1; # End of WebPAC::DB +sub count { + warn "## count ",dump(@_),$/ if ( $debug ); + return @_ . ''; +} + +# END +1;