--- trunk/lib/WebPAC/Normalize.pm 2005/07/24 11:17:44 29 +++ trunk/lib/WebPAC/Normalize.pm 2007/11/19 16:33:09 1048 @@ -1,655 +1,922 @@ package WebPAC::Normalize; +use Exporter 'import'; +our @EXPORT = qw/ + _set_ds _set_lookup + _set_load_row + _get_ds _clean_ds + _debug + _pack_subfields_hash + + 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 + +/; use warnings; use strict; -use base 'WebPAC::Common'; -use Data::Dumper; + +#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 +/); =head1 NAME -WebPAC::Normalize - data mungling for normalisation +WebPAC::Normalize - describe normalisaton rules using sets -=head1 VERSION +=cut + +our $VERSION = '0.35'; -Version 0.01 +=head1 SYNOPSIS + +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. + +=head1 FUNCTIONS + +Functions which start with C<_> are private and used by WebPAC internally. +All other functions are available for use within normalisation rules. + +=head2 data_structure + +Return data structure + + 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 ); + }, + ); + +Options C, C and C are mandatory while all +other are optional. + +C is closure only used when executing lookups, so they will +die if it's not defined. + +This function will B if normalizastion can't be evaled. + +Since this function isn't exported you have to call it with +C. =cut -our $VERSION = '0.01'; +my $load_row_coderef; -=head1 SYNOPSIS +sub data_structure { + my $arg = {@_}; + + die "need row argument" unless ($arg->{row}); + die "need normalisation argument" unless ($arg->{rules}); + + _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 package contains code that mungle data to produce normalized format. + no strict 'subs'; + no warnings 'redefine'; + eval "$arg->{rules};"; + die "error evaling $arg->{rules}: $@\n" if ($@); -It contains several assumptions: + return _get_ds(); +} -=over +=head2 _set_ds -=item * +Set current record hash -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. + _set_ds( $rec ); -=item * +=cut -source data records (C<$rec>) have unique identifiers in field C<000> +my $rec; -=item * +sub _set_ds { + $rec = shift or die "no record hash"; + $WebPAC::Normalize::MARC::rec = $rec; +} -optional C tag at B will be -perl code that is evaluated before producing output (value of field will be -interpolated before that) +=head2 -=item * + my $rec = _get_rec(); -optional C at B will apply perl -code defined as code ref on format after field substitution to producing -output +=cut -=item * +sub _get_rec { $rec }; -optional C will be then performed. See C. +=head2 _set_config -=item * +Set current config hash -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_config( $config ); -=back +Magic keys are: -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. +=over 4 +=item _ +Code of current database +=item _mfn -=head1 FUNCTIONS +Current MFN -=head2 new +=back -Create new normalisation object +=cut - my $n = new WebPAC::Normalize::Something( - filter => { - 'filter_name_1' => sub { - # filter code - return length($_); - }, ... - }, - db => $db_obj, - lookup_regex => $lookup->regex, - ); +my $config; + +sub _set_config { + $config = shift; +} + +=head2 _get_ds -Parametar C defines user supplied snippets of perl code which can -be use with C notation. +Return hash formatted as data structure -Recommended parametar C is used to enable parsing of lookups -in structures. + my $ds = _get_ds(); =cut -sub new { - my $class = shift; - my $self = {@_}; - bless($self, $class); +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 + + _clean_ds(); -Create in-memory data structure which represents normalized layout from -C. +=cut -This structures are used to produce output. +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 > 0); - $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 = $tag->{'value'} || $tag->{'content'}; + $load_row_coderef = $coderef; +} - $log->debug("format: $format"); +=head2 _debug - 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); +Change level of debug warnings - if ($tag->{'sort'}) { - @v = $self->sort_arr(@v); - } + _debug( 2 ); - # use format? - if ($tag->{'format_name'}) { - @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v; - } +=cut - 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! - } +sub _debug { + my $l = shift; + return $debug unless defined($l); + warn "debug level $l",$/ if ($l > 0); + $debug = $l; + $WebPAC::Normalize::MARC::debug = $debug; +} - # delimiter will join repeatable fields - if ($tag->{'delimiter'}) { - @v = ( join($tag->{'delimiter'}, @v) ); - } +=head1 Functions to create C - # 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; +Those functions generally have to first in your normalization file. - } else { - push @{$row->{$type}}, @v; - } - } +=head2 search_display +Define output for L and L at the same time - } + search_display('Title', rec('200','a') ); - if ($row) { - $row->{'tag'} = $field; - # 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"); - } +=cut - push @ds, $row; +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("row $field: ",sub { Dumper($row) }); - } +=head2 tag - } +Old name for L, but supported - $self->{'db'}->save_ds( - ds => \@ds, - current_filename => $self->{'current_filename'}, - headline => $self->{'headline'}, - ) if ($self->{'db'}); +=cut + +sub tag { + search_display( @_ ); +} - $log->debug("ds: ", sub { Dumper(@ds) }); +=head2 display - return @ds; +Define output just for I + + @v = display('Title', rec('200','a') ); + +=cut +sub _field { + 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; } -=head2 parse +sub display { _field( '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. +=head2 search - my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i); +Prepare values just for I + + @v = search('Title', rec('200','a') ); =cut -sub parse { - my $self = shift; +sub search { _field( 'search', @_ ) } + +=head2 sorted - my ($rec, $format_utf8, $i) = @_; +Insert into lists which will be automatically sorted - return if (! $format_utf8); + sorted('Title', rec('200','a') ); - my $log = $self->_get_logger(); +=cut - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); +sub sorted { _field( 'sorted', @_ ) } - $i = 0 if (! $i); - my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'}); - my @out; +=head1 Functions to extract data from input - $log->debug("format: $format"); +This function should be used inside functions to create C described +above. - my $eval_code; - # remove eval{...} from beginning - $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s); +=head2 _pack_subfields_hash - my $filter_name; - # remove filter{...} from beginning - $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s); + @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 - my $prefix; - my $all_found=0; +sub _pack_subfields_hash { - while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) { + warn "## _pack_subfields_hash( ",dump(@_), " )\n" if ($debug > 1); - my $del = $1 || ''; - $prefix ||= $del if ($all_found == 0); + my ($h,$include_subfields) = @_; - # repeatable index - my $r = $i; - $r = 0 if (lc("$2") eq 's'); + # sanity and ease of use + return $h if (ref($h) ne 'HASH'); - my $found = 0; - my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found); + 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 ($found) { - push @out, $del; - push @out, $tmp; - $all_found += $found; + 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} }; +} - my ($rec, $format_utf8) = @_; +=head2 rec - my $log = $self->_get_logger(); +syntaxtic sugar for - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - return if (! $format_utf8); + @v = rec('200') + @v = rec('200','a') - my $i = 0; - my @arr; +If rec() returns just single value, it will +return scalar, not array. - while (my $v = $self->parse($rec,$format_utf8,$i++)) { - push @arr, $v; +=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 ''; } +} - $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]; +} + +sub frec_ne { + return ! frec_eq( @_ ); +} - my $log = $self->_get_logger(); +=head2 regex - 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; +Apply regex to some or all values - $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999)); + @v = regex( 's/foo/bar/g', @v ); - # FIXME remove for speedup? - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); +=cut - if (utf8::is_utf8($format)) { - $format = $self->_x($format); +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'}) { - return $self->lookup($format); - } 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 - -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. +suffix all values with a string - 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($_) } @_; +} - my ($rec, $format_utf8) = @_; +=head2 surround - my $log = $self->_get_logger(); +surround all values with a two strings - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - return if (! $format_utf8); + @v = surround( 'prefix_', '_suffix', @v ); - my $i = 0; - my @arr; +=cut - while (my @v = $self->fill_in($rec,$format_utf8,$i++)) { - push @arr, @v; - } +sub surround { + my $p = shift; + my $s = shift; + $p = '' unless defined( $p ); + $s = '' unless defined( $s ); + return map { $p . $_ . $s } grep { defined($_) } @_; +} + +=head2 first + +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')) + } + ); + +Code like above will be B using L from +normal lookup definition in C which looks like: - my $text = $self->get_data(\$rec,$f,$sf,$i,\$found); + 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') }, + ) -Arguments are: -record reference C<$rec>, -field C<$f>, -optional subfiled C<$sf>, -index for repeatable values C<$i>. +You can think about this lookup as SQL (if that helps): -Optinal variable C<$found> will be incremeted if there -is field. + select + sub { what } + from + database, input + where + sub { filter from lookuped record } + having + sub { optional filter on current record } -Returns value or empty string. +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 ($$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]; - } + 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; +} + +=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 -Sort array ignoring case and html in data +Returns unique id of this record - my @sorted = $webpac->sort_arr(@unsorted); + $id = id(); + +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 + +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); -=head2 _x + 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; + } +} -Convert strings from C encoding into application -specific encoding (optinally specified using C to C -constructor). +my $hash; - my $text = $n->_x('normalize text string'); +=head2 set -This is a stub so that other modules doesn't have to implement it. + 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;