blib/lib/UR/DataSource/Filesystem.pm untested

filter: Statementstmt 0.0% 0 / 1044 Branchbran 0.0% 0 / 388 Conditioncond 0.0% 0 / 143 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 46 Podpod 0.0% 0 / 32 totaltotal 0.0% 0 / 1653 SCAR 105.5
CC
195
Cov
0%
_comparator_for_operator_and_property
5852.0
_sync_database
1332.0
create_iterator_closure_for_rule
1190.0
CRAP 38220.0
1 package UR::DataSource::Filesystem;
2  
3 use UR;
4 use strict;
5 use warnings;
6 our $VERSION = "0.46"; # UR $VERSION;
7  
8 use File::Basename;
9 use File::Path;
10 use List::Util;
11 use Scalar::Util;
12 use Errno qw(EINTR EAGAIN EOPNOTSUPP);
13  
14 # lets you specify the server in several ways:
15 # path => '/path/name'
16 # means there is one file storing the data
17 # path => [ '/path1/name', '/path2/name' ]
18 # means the first tile we need to open the file, pick one (for load balancing)
19 # path => '/path/to/directory/'
20 # means that directory contains one or more files, and the classes using
21 # this datasource can have table_name metadata to pick the file
22 # path => '/path/$param1/${param2}.ext'
23 # means the values for $param1 and $param2 should come from the input rule.
24 # If the rule doesn't specify the param, then it should glob for the possible
25 # names at that point in the filesystem
26 # path => '/path/&method/filename'
27 # means the value for that part of the path should come from a method call
28 # run as $subject_class_name->$method($rule)
29 # path => '/path/*/path/$name/
30 # means it should glob at the appropriate time for the '*', but no use the
31 # paths found matching the glob to infer any values
32  
33 # maybe suppert a URI scheme like
34 # file:/path/$to/File.ext?columns=[a,b,c]&sorted_columns=[a,b]
35  
36 # TODO
37 # * Support non-equality operators for properties that are part of the path spec
38  
39  
40 class UR::DataSource::Filesystem {
41 is => 'UR::DataSource',
42 has => [
43 path => { doc => 'Path spec for the path on the filesystem containing the data' },
44 delimiter => { is => 'String', default_value => '\s*,\s*', doc => 'Delimiter between columns on the same line' },
45 record_separator => { is => 'String', default_value => "\n", doc => 'Delimiter between lines in the file' },
46 header_lines => { is => 'Integer', default_value => 0, doc => 'Number of lines at the start of the file to skip' },
47 columns_from_header => { is => 'Boolean', default_value => 0, doc => 'The column names are in the first line of the file' },
48 handle_class => { is => 'String', default_value => 'IO::File', doc => 'Class to use for new file handles' },
49 ],
50 has_optional => [
51 columns => { is => 'ARRAY', doc => 'Names of the columns in the file, in order' },
52 sorted_columns => { is => 'ARRAY', doc => 'Names of the columns by which the data file is sorted' },
53 ],
54 doc => 'A data source for treating files as relational data',
55 };
56  
57 sub can_savepoint { 0;} # Doesn't support savepoints
58  
59 # Filesystem datasources don't have a "default_handle"
60 sub create_default_handle { undef }
61  
62 sub _regex {
63 my $self = shift;
64  
65 unless ($self->{'_regex'}) {
66 my $delimiter = $self->delimiter;
67 my $r = eval { qr($delimiter) };
68 if ($@ || !$r) {
69 $self->error_message("Unable to interepret delimiter '".$self->delimiter.": $@");
70 return;
71 }
72 $self->{'_regex'} = $r;
73 }
74 return $self->{'_regex'};
75 }
76  
77  
78 sub _logger {
79 my $self = shift;
80 my $varname = shift;
81 if ($ENV{$varname}) {
82 my $log_fh = UR::DBI->sql_fh;
83 return sub {
84 my $msg = shift;
85 my $time = time();
86 $msg =~ s/\b\$time\b/$time/g;
87 my $localtime = scalar(localtime $time);
88 $msg =~ s/\b\$localtime\b/$localtime/;
89  
90 $log_fh->print($msg);
91 };
92 } else {
93 return \&UR::Util::null_sub;
94 }
95 }
96  
97 # The behavior for handling the filehandles after fork is contained in
98 # the read_record_from_file closure. There's nothing special for the
99 # data source to do
100 sub prepare_for_fork {
101 return 1;
102 }
103 sub finish_up_after_fork {
104 return 1;
105 }
106  
107 # Like UR::BoolExpr::specifies_value_for, but works on either a BoolExpr
108 # or another object. In the latter case, it returns true if the object's
109 # class has the given property
110 sub __specifies_value_for {
111 my($self, $thing, $property_name) = @_;
112  
113 return $thing->isa('UR::BoolExpr')
114 ? $thing->specifies_value_for($property_name)
115 : $thing->__meta__->property_meta_for_name($property_name);
116 }
117  
118 # Like UR::BoolExpr::value_for, but works on either a BoolExpr
119 # or another object.
120 sub __value_for {
121 my($self, $thing, $property_name) = @_;
122  
123 return $thing->isa('UR::BoolExpr')
124 ? $thing->value_for($property_name)
125 : $thing->$property_name;
126 }
127  
128 # Like UR::BoolExpr::subject_class_name, but works on either a BoolExpr
129 # or another object.
130 sub __subject_class_name {
131 my($self, $thing) = @_;
132  
133 return $thing->isa('UR::BoolExpr')
134 ? $thing->subject_class_name()
135 : $thing->class;
136 }
137  
138  
139 sub _replace_vars_with_values_in_pathname {
140 my($self, $rule_or_obj, $string, $prop_values_hash) = @_;
141  
142 $prop_values_hash ||= {};
143  
144 # Match something like /some/path/$var/name or /some/path${var}.ext/name
145 if ($string =~ m/\$\{?(\w+)\}?/) {
146 my $varname = $1;
147 my $subject_class_name = $self->__subject_class_name($rule_or_obj);
148 unless ($subject_class_name->__meta__->property_meta_for_name($varname)) {
149 Carp::croak("Invalid 'server' for data source ".$self->id
150 . ": Path spec $string requires a value for property $varname "
151 . " which is not a property of class $subject_class_name");
152 }
153 my @string_replacement_values;
154  
155 if ($self->__specifies_value_for($rule_or_obj, $varname)) {
156 my @property_values = $self->__value_for($rule_or_obj, $varname);
157 if (@property_values == 1 and ref($property_values[0]) eq 'ARRAY') {
158 @property_values = @{$property_values[0]};
159 }
160 # Make a listref that has one element per value for that property in the rule (in-clause
161 # rules may have more than one value)
162 # Each element has 2 parts, first is the value, second is the accumulated prop_values_hash
163 # where we've added the occurance of this property havine one of the values
164 @property_values = map { [ $_, { %$prop_values_hash, $varname => $_ } ] } @property_values;
165  
166 # Escape any shell glob characters in the values: [ ] { } ~ ? * and \
167 # we don't want a property with value '?' to be a glob wildcard
168 @string_replacement_values = map { $_->[0] =~ s/([[\]{}~?*\\])/\\$1/; $_ } @property_values;
169  
170 } else {
171 # The rule doesn't have a value for this property.
172 # Put a shell wildcard in here, and a later glob will match things
173 # The '.__glob_positions__' key holds a list of places we've inserted shell globs.
174 # Each element is a 2-element list: index 0 is the string position, element 1 if the variable name.
175 # This is needed so the later glob expansion can tell the difference between globs
176 # that are part of the original path spec, and globs put in here
177 my @glob_positions = @{ $prop_values_hash->{'.__glob_positions__'} || [] };
178  
179 my $glob_pos = $-[0];
180 push @glob_positions, [$glob_pos, $varname];
181 @string_replacement_values = ([ '*', { %$prop_values_hash, '.__glob_positions__' => \@glob_positions} ]);
182 }
183  
184 my @return = map {
185 my $s = $string;
186 substr($s, $-[0], $+[0] - $-[0], $_->[0]);
187 [ $s, $_->[1] ];
188 }
189 @string_replacement_values;
190  
191 # recursion to process the next variable replacement
192 return map { $self->_replace_vars_with_values_in_pathname($rule_or_obj, @$_) } @return;
193  
194 } else {
195 return [ $string, $prop_values_hash ];
196 }
197 }
198  
199 sub _replace_subs_with_values_in_pathname {
200 my($self, $rule_or_obj, $string, $prop_values_hash) = @_;
201  
202 $prop_values_hash ||= {};
203 my $subject_class_name = $self->__subject_class_name($rule_or_obj);
204  
205 # Match something like /some/path/&sub/name or /some/path&{sub}.ext/name
206 if ($string =~ m/\&\{?(\w+)\}?/) {
207 my $subname = $1;
208 unless ($subject_class_name->can($subname)) {
209 Carp::croak("Invalid 'server' for data source ".$self->id
210 . ": Path spec $string requires a value for method $subname "
211 . " which is not a method of class " . $self->__subject_class_name($rule_or_obj));
212 }
213
214 my @property_values = eval { $subject_class_name->$subname($rule_or_obj) };
215 if ($@) {
216 Carp::croak("Can't resolve final path for 'server' for data source ".$self->id
217 . ": Method call to ${subject_class_name}::${subname} died with: $@");
218 }
219 if (@property_values == 1 and ref($property_values[0]) eq 'ARRAY') {
220 @property_values = @{$property_values[0]};
221 }
222 # Make a listref that has one element per value for that property in the rule (in-clause
223 # rules may have more than one value)
224 # Each element has 2 parts, first is the value, second is the accumulated prop_values_hash
225 # where we've added the occurance of this property havine one of the values
226 @property_values = map { [ $_, { %$prop_values_hash } ] } @property_values;
227  
228 # Escape any shell glob characters in the values: [ ] { } ~ ? * and \
229 # we don't want a return value '?' or '*' to be a glob wildcard
230 my @string_replacement_values = map { $_->[0] =~ s/([[\]{}~?*\\])/\\$1/; $_ } @property_values;
231  
232 # Given a pathname returned from the glob, return a new glob_position_list
233 # that has fixed up the position information accounting for the fact that
234 # the globbed pathname is a different length than the original spec
235 my $original_path_length = length($string);
236 my $glob_position_list = $prop_values_hash->{'.__glob_positions__'};
237 my $subname_replacement_position = $-[0];
238 my $fix_offsets_in_glob_list = sub {
239 my $pathname = shift;
240 # alter the position only if it is greater than the position of
241 # the subname we're replacing
242 return map { [ $_->[0] < $subname_replacement_position
243 ? $_->[0]
244 : $_->[0] + length($pathname) - $original_path_length,
245 $_->[1] ]
246 }
247 @$glob_position_list;
248 };
249  
250 my @return = map {
251 my $s = $string;
252 substr($s, $-[0], $+[0] - $-[0], $_->[0]);
253 $_->[1]->{'.__glob_positions__'} = [ $fix_offsets_in_glob_list->($s) ];
254 [ $s, $_->[1] ];
255 }
256 @string_replacement_values;
257  
258 # recursion to process the next method call
259 return map { $self->_replace_subs_with_values_in_pathname($rule_or_obj, @$_) } @return;
260  
261 } else {
262 return [ $string, $prop_values_hash ];
263 }
264 }
265  
266 sub _replace_glob_with_values_in_pathname {
267 my($self, $string, $prop_values_hash) = @_;
268  
269 # a * not preceeded by a backslash, delimited by /
270 if ($string =~ m#([^/]*?[^\\/]?(\*)[^/]*)#) {
271 my $glob_pos = $-[2];
272  
273 my $path_segment_including_glob = substr($string, 0, $+[0]);
274 my $remaining_path = substr($string, $+[0]);
275 my @glob_matches = map { $_ . $remaining_path }
276 glob($path_segment_including_glob);
277  
278 my $resolve_glob_values_for_each_result;
279 my $glob_position_list = $prop_values_hash->{'.__glob_positions__'};
280  
281 # Given a pathname returned from the glob, return a new glob_position_list
282 # that has fixed up the position information accounting for the fact that
283 # the globbed pathname is a different length than the original spec
284 my $original_path_length = length($string);
285 my $fix_offsets_in_glob_list = sub {
286 my $pathname = shift;
287 return map { [ $_->[0] + length($pathname) - $original_path_length, $_->[1] ] } @$glob_position_list;
288 };
289  
290 if ($glob_position_list->[0]->[0] == $glob_pos) {
291 # This * was put in previously by a $propname in the spec that wasn't mentioned in the rule
292  
293 my $path_delim_pos = index($path_segment_including_glob, '/', $glob_pos);
294 $path_delim_pos = length($path_segment_including_glob) if ($path_delim_pos == -1); # No more /s
295  
296 my $regex_as_str = $path_segment_including_glob;
297 # Find out just how many *s we're dealing with and where they are, up to the next /
298 # remove them from the glob_position_list because we're going to resolve their values
299 my(@glob_positions, @property_names);
300 while (@$glob_position_list
301 and
302 $glob_position_list->[0]->[0] < $path_delim_pos
303 ) {
304 my $this_glob_info = shift @{$glob_position_list};
305 push @glob_positions, $this_glob_info->[0];
306 push @property_names, $this_glob_info->[1];
307 }
308 # Replace the *s found with regex captures
309 my $glob_replacement = '([^/]*)';
310 my $glob_rpl_offset = 0;
311 my $offset_inc = length($glob_replacement) - 1; # replacing a 1-char string '*' with a 7-char string '([^/]*)'
312 $regex_as_str = List::Util::reduce( sub {
313 substr($a, $b + $glob_rpl_offset, 1, $glob_replacement);
314 $glob_rpl_offset += $offset_inc;
315 $a;
316 },
317 ($regex_as_str, @glob_positions) );
318  
319 my $regex = qr{$regex_as_str};
320 my @property_values_for_each_glob_match = map { [ $_, [ $_ =~ $regex] ] } @glob_matches;
321  
322 # Fill in the property names into .__glob_positions__
323 # we've resolved in this iteration, and apply offset fixups for the
324 # difference in string length between the pre- and post-glob pathnames
325  
326 $resolve_glob_values_for_each_result = sub {
327 return map {
328 my %h = %$prop_values_hash;
329 @h{@property_names} = @{$_->[1]};
330 $h{'.__glob_positions__'} = [ $fix_offsets_in_glob_list->($_->[0]) ];
331 [$_->[0], \%h];
332 }
333 @property_values_for_each_glob_match;
334 };
335  
336 } else {
337 # This is a glob put in the original path spec
338 # The new path comes from the @glob_matches list.
339 # Apply offset fixups for the difference in string length between the
340 # pre- and post-glob pathnames
341 $resolve_glob_values_for_each_result = sub {
342 return map { [
343 $_,
344 { %$prop_values_hash,
345 '.__glob_positions__' => [ $fix_offsets_in_glob_list->($_) ]
346 }
347 ]
348 }
349 @glob_matches;
350 };
351 }
352  
353 my @resolved_paths_and_property_values = $resolve_glob_values_for_each_result->();
354  
355 # Recursion to process the next glob
356 return map { $self->_replace_glob_with_values_in_pathname( @$_ ) }
357 @resolved_paths_and_property_values;
358  
359 } else {
360 delete $prop_values_hash->{'.__glob_positions__'};
361 return [ $string, $prop_values_hash ];
362 }
363 }
364  
365  
366 sub resolve_file_info_for_rule_and_path_spec {
367 my($self, $rule, $path_spec) = @_;
368  
369 $path_spec ||= $self->path;
370  
371 return map { $self->_replace_glob_with_values_in_pathname(@$_) }
372 map { $self->_replace_subs_with_values_in_pathname($rule, @$_) }
373 $self->_replace_vars_with_values_in_pathname($rule, $path_spec);
374 }
375  
376  
377 # We're overriding path() so the first time it's called, it will
378 # pick one from the list and then stay with that one for the life
379 # of the program
380 sub path {
381 my $self = shift;
382  
383 unless ($self->{'__cached_path'}) {
384 my $path = $self->__path();
385 if (ref($path) and ref($path) eq 'ARRAY') {
386 my $count = @$path;
387 my $idx = $$ % $count;
388 $self->{'_cached_path'} = $path->[$idx];
389 } else {
390 $self->{'_cached_path'} = $path;
391 }
392 }
393 return $self->{'_cached_path'};
394 }
395  
396 # Names of creation params that we should force to be listrefs
397 our %creation_param_is_list = map { $_ => 1 } qw( columns sorted_columns );
398 sub create_from_inline_class_data {
399 my($class, $class_data, $ds_data) = @_;
400  
401 #unless (exists $ds_data->{'columns'}) {
402 # User didn't specify columns in the file. Assumme every property is a column, and in the same order
403 # We'll have to ask the class object for the column list the first time there's a query
404 #}
405  
406 my %ds_creation_params;
407 foreach my $param ( qw( path delimiter record_separator columns header_lines
408 columns_from_header handle_class sorted_columns )
409 ) {
410 if (exists $ds_data->{$param}) {
411 if ($creation_param_is_list{$param} and ref($ds_data->{$param}) ne 'ARRAY') {
412 $ds_creation_params{$param} = \( $ds_data->{$param} );
413 } else {
414 $ds_creation_params{$param} = $ds_data->{$param};
415 }
416 }
417 }
418  
419 my $ds_id = UR::Object::Type->autogenerate_new_object_id_uuid();
420 my $ds_type = delete $ds_data->{'is'} || __PACKAGE__;
421 my $ds = $ds_type->create( %ds_creation_params, id => $ds_id );
422 return $ds;
423 }
424  
425  
426  
427 sub _things_in_list_are_numeric {
428 my $self = shift;
429  
430 foreach ( @{$_[0]} ) {
431 return 0 if (! Scalar::Util::looks_like_number($_));
432 }
433 return 1;
434 }
435  
436 # Construct a closure to perform an operator test against the given value
437 # The closures return 0 is the test is successful, -1 if unsuccessful but
438 # the file's value was less than $value, and 1 if unsuccessful and greater.
439 # The iterator that churns through the file knows that if it's comparing an
440 # ID/sorted column, and the comparator returns 1 then we've gone past the
441 # point where we can expect to ever find another successful match and we
442 # should stop looking
443 my $ALWAYS_FALSE = sub { -1 };
444 sub _comparator_for_operator_and_property {
445 my($self,$property,$operator,$value) = @_;
446  
447 no warnings 'uninitialized'; # we're handling ''/undef/null specially below where it matters
448  
449 if ($operator eq 'between') {
450 if ($value->[0] eq '' or $value->[1] eq '') {
451 return $ALWAYS_FALSE;
452 }
453  
454 if ($property->is_numeric and $self->_things_in_list_are_numeric($value)) {
455 if ($value->[0] > $value->[1]) {
456 # Will never be true
457 Carp::carp "'between' comparison will never be true with values ".$value->[0]," and ".$value->[1];
458 return $ALWAYS_FALSE;
459 }
460  
461 # numeric 'between' comparison
462 return sub {
463 return -1 if (${$_[0]} eq '');
464 if (${$_[0]} < $value->[0]) {
465 return -1;
466 } elsif (${$_[0]} > $value->[1]) {
467 return 1;
468 } else {
469 return 0;
470 }
471 };
472 } else {
473 if ($value->[0] gt $value->[1]) {
474 Carp::carp "'between' comparison will never be true with values ".$value->[0]," and ".$value->[1];
475 return $ALWAYS_FALSE;
476 }
477  
478 # A string 'between' comparison
479 return sub {
480 return -1 if (${$_[0]} eq '');
481 if (${$_[0]} lt $value->[0]) {
482 return -1;
483 } elsif (${$_[0]} gt $value->[1]) {
484 return 1;
485 } else {
486 return 0;
487 }
488 };
489 }
490  
491 } elsif ($operator eq 'in') {
492 if (! @$value) {
493 return $ALWAYS_FALSE;
494 }
495  
496 if ($property->is_numeric and $self->_things_in_list_are_numeric($value)) {
497 # Numeric 'in' comparison returns undef if we're within the range of the list
498 # but don't actually match any of the items in the list
499 @$value = sort { $a <=> $b } @$value; # sort the values first
500 return sub {
501 return -1 if (${$_[0]} eq '');
502 if (${$_[0]} < $value->[0]) {
503 return -1;
504 } elsif (${$_[0]} > $value->[-1]) {
505 return 1;
506 } else {
507 foreach ( @$value ) {
508 return 0 if ${$_[0]} == $_;
509 }
510 return -1;
511 }
512 };
513  
514 } else {
515 # A string 'in' comparison
516 @$value = sort { $a cmp $b } @$value;
517 return sub {
518 if (${$_[0]} lt $value->[0]) {
519 return -1;
520 } elsif (${$_[0]} gt $value->[-1]) {
521 return 1;
522 } else {
523 foreach ( @$value ) {
524 return 0 if ${$_[0]} eq $_;
525 }
526 return -1;
527 }
528 };
529  
530 }
531  
532 } elsif ($operator eq 'not in') {
533 if (! @$value) {
534 return $ALWAYS_FALSE;
535 }
536  
537 if ($property->is_numeric and $self->_things_in_list_are_numeric($value)) {
538 return sub {
539 return -1 if (${$_[0]} eq '');
540 foreach ( @$value ) {
541 return -1 if ${$_[0]} == $_;
542 }
543 return 0;
544 }
545  
546 } else {
547 return sub {
548 foreach ( @$value ) {
549 return -1 if ${$_[0]} eq $_;
550 }
551 return 0;
552 }
553 }
554  
555 } elsif ($operator eq 'like') {
556 # 'like' is always a string comparison. In addition, we can't know if we're ahead
557 # or behind in the file's ID columns, so the only two return values are 0 and 1
558  
559 return $ALWAYS_FALSE if ($value eq ''); # property like NULL is always false
560  
561 # Convert SQL-type wildcards to Perl-type wildcards
562 # Convert a % to a *, and _ to ., unless they're preceeded by \ to escape them.
563 # Not that this isn't precisely correct, as \\% should really mean a literal \
564 # followed by a wildcard, but we can't be correct in all cases without including
565 # a real parser. This will catch most cases.
566  
567 $value =~ s/(?<!\\)%/.*/g;
568 $value =~ s/(?<!\\)_/./g;
569 my $regex = qr($value);
570 return sub {
571 return -1 if (${$_[0]} eq '');
572 if (${$_[0]} =~ $regex) {
573 return 0;
574 } else {
575 return 1;
576 }
577 };
578  
579 } elsif ($operator eq 'not like') {
580 return $ALWAYS_FALSE if ($value eq ''); # property like NULL is always false
581 $value =~ s/(?<!\\)%/.*/;
582 $value =~ s/(?<!\\)_/./;
583 my $regex = qr($value);
584 return sub {
585 return -1 if (${$_[0]} eq '');
586 if (${$_[0]} =~ $regex) {
587 return 1;
588 } else {
589 return 0;
590 }
591 };
592  
593  
594 # FIXME - should we only be testing the numericness of the property?
595 } elsif ($property->is_numeric and $self->_things_in_list_are_numeric([$value])) {
596 # Basic numeric comparisons
597 if ($operator eq '=') {
598 return sub {
599 return -1 if (${$_[0]} eq ''); # null always != a number
600 return ${$_[0]} <=> $value;
601 };
602 } elsif ($operator eq '<') {
603 return sub {
604 return -1 if (${$_[0]} eq ''); # null always != a number
605 ${$_[0]} < $value ? 0 : 1;
606 };
607 } elsif ($operator eq '<=') {
608 return sub {
609 return -1 if (${$_[0]} eq ''); # null always != a number
610 ${$_[0]} <= $value ? 0 : 1;
611 };
612 } elsif ($operator eq '>') {
613 return sub {
614 return -1 if (${$_[0]} eq ''); # null always != a number
615 ${$_[0]} > $value ? 0 : -1;
616 };
617 } elsif ($operator eq '>=') {
618 return sub {
619 return -1 if (${$_[0]} eq ''); # null always != a number
620 ${$_[0]} >= $value ? 0 : -1;
621 };
622 } elsif ($operator eq 'true') {
623 return sub {
624 ${$_[0]} ? 0 : -1;
625 };
626 } elsif ($operator eq 'false') {
627 return sub {
628 ${$_[0]} ? -1 : 0;
629 };
630 } elsif ($operator eq '!=' or $operator eq 'ne') {
631 return sub {
632 return 0 if (${$_[0]} eq ''); # null always != a number
633 ${$_[0]} != $value ? 0 : -1;
634 }
635 }
636  
637 } else {
638 # Basic string comparisons
639 if ($operator eq '=') {
640 return sub {
641 return -1 if (${$_[0]} eq '' xor $value eq '');
642 return ${$_[0]} cmp $value;
643 };
644 } elsif ($operator eq '<') {
645 return sub {
646 ${$_[0]} lt $value ? 0 : 1;
647 };
648 } elsif ($operator eq '<=') {
649 return sub {
650 return -1 if (${$_[0]} eq '' or $value eq '');
651 ${$_[0]} le $value ? 0 : 1;
652 };
653 } elsif ($operator eq '>') {
654 return sub {
655 ${$_[0]} gt $value ? 0 : -1;
656 };
657 } elsif ($operator eq '>=') {
658 return sub {
659 return -1 if (${$_[0]} eq '' or $value eq '');
660 ${$_[0]} ge $value ? 0 : -1;
661 };
662 } elsif ($operator eq 'true') {
663 return sub {
664 ${$_[0]} ? 0 : -1;
665 };
666 } elsif ($operator eq 'false') {
667 return sub {
668 ${$_[0]} ? -1 : 0;
669 };
670 } elsif ($operator eq '!=' or $operator eq 'ne') {
671 return sub {
672 ${$_[0]} ne $value ? 0 : -1;
673 }
674 }
675 }
676 }
677  
678  
679  
680 sub _properties_from_path_spec {
681 my($self) = @_;
682  
683 unless (exists $self->{'__properties_from_path_spec'}) {
684 my $path = $self->path;
685 $path = $path->[0] if ref($path);
686  
687 my @property_names;
688 while($path =~ m/\G\$\{?(\w+)\}?/) {
689 push @property_names, $1;
690 }
691 $self->{'__properties_from_path_spec'} = \@property_names;
692 }
693 return @{ $self->{'__properties_from_path_spec'} };
694 }
695  
696  
697 sub _generate_loading_templates_arrayref {
698 my($self, $old_sql_cols) = @_;
699  
700 # Each elt in @$column_data is a quad:
701 # [ $class_meta, $property_meta, $table_name, $object_num ]
702 # Keep only the properties with columns (mostly just to remove UR::Object::id
703 my @sql_cols = grep { $_->[1]->column_name }
704 @$old_sql_cols;
705  
706 my $template_data = $self->SUPER::_generate_loading_templates_arrayref(\@sql_cols);
707 return $template_data;
708 }
709  
710  
711  
712 sub _resolve_column_names_from_pathname {
713 my($self,$pathname,$fh) = @_;
714  
715 unless (exists($self->{'__column_names_from_pathname'}->{$pathname})) {
716 if (my $column_names_in_order = $self->columns) {
717 $self->{'__column_names_from_pathname'}->{$pathname} = $column_names_in_order;
718  
719 } else {
720 my $record_separator = $self->record_separator();
721 my $line = $fh->getline();
722 $line =~ s/$record_separator$//; # chomp, but for any value
723 # FIXME - to support record-oriented files, we need some replacement for this...
724 my $split_regex = $self->_regex();
725 my @headers = split($split_regex, $line);
726 $self->{'__column_names_from_pathname'}->{$pathname} = \@headers;
727 }
728 }
729 return $self->{'__column_names_from_pathname'}->{$pathname};
730 }
731  
732  
733 sub file_is_sorted_as_requested {
734 my($self, $query_plan) = @_;
735  
736 my $sorted_columns = $self->sorted_columns || [];
737  
738 my $order_by_columns = $query_plan->order_by_columns();
739 for (my $i = 0; $i < @$order_by_columns; $i++) {
740 next if ($order_by_columns->[$i] eq '$.'); # input line number is always sorted
741 next if ($order_by_columns->[$i] eq '__FILE__');
742  
743 return 0 if $i > $#$sorted_columns;
744 if ($sorted_columns->[$i] ne $order_by_columns->[$i]) {
745 return 0;
746 }
747 }
748 return 1;
749 }
750  
751  
752 # FIXME - this is a copy of parts of _generate_class_data_for_loading from UR::DS::RDBMS
753 sub _generate_class_data_for_loading {
754 my ($self, $class_meta) = @_;
755  
756 my $parent_class_data = $self->SUPER::_generate_class_data_for_loading($class_meta);
757  
758 my @class_hierarchy = ($class_meta->class_name,$class_meta->ancestry_class_names);
759 my $order_by_columns;
760 do {
761 my @id_column_names;
762 for my $inheritance_class_name (@class_hierarchy) {
763 my $inheritance_class_object = UR::Object::Type->get($inheritance_class_name);
764 unless ($inheritance_class_object->table_name) {
765 next;
766 }
767 @id_column_names =
768 #map {
769 # my $t = $inheritance_class_object->table_name;
770 # ($t) = ($t =~ /(\S+)\s*$/);
771 # $t . '.' . $_
772 #}
773 grep { defined }
774 map {
775 my $p = $inheritance_class_object->property_meta_for_name($_);
776 die ("No property $_ found for " . $inheritance_class_object->class_name . "?") unless $p;
777 $p->column_name;
778 }
779 map { $_->property_name }
780 grep { $_->column_name }
781 $inheritance_class_object->direct_id_property_metas;
782  
783 last if (@id_column_names);
784 }
785 $order_by_columns = \@id_column_names;
786 };
787  
788 my(@all_table_properties, @direct_table_properties, $first_table_name, $subclassify_by);
789 for my $co ( $class_meta, @{ $parent_class_data->{parent_class_objects} } ) {
790 my $table_name = $co->table_name;
791 next unless $table_name;
792  
793 $first_table_name ||= $co->table_name;
794 # $sub_classification_method_name ||= $co->sub_classification_method_name;
795 # $sub_classification_meta_class_name ||= $co->sub_classification_meta_class_name;
796 $subclassify_by ||= $co->subclassify_by;
797  
798 my $sort_sub = sub ($$) { return $_[0]->property_name cmp $_[1]->property_name };
799 push @all_table_properties,
800 map { [$co, $_, $table_name, 0 ] }
801 sort $sort_sub
802 grep { defined $_->column_name && $_->column_name ne '' }
803 UR::Object::Property->get( class_name => $co->class_name );
804  
805 @direct_table_properties = @all_table_properties if $class_meta eq $co;
806 }
807  
808  
809 my $class_data = {
810 %$parent_class_data,
811  
812 order_by_columns => $order_by_columns,
813 direct_table_properties => \@direct_table_properties,
814 all_table_properties => \@all_table_properties,
815 };
816 return $class_data;
817 }
818  
819  
820 # Needed for the QueryPlan's processing of order-by params
821 # Params are a list of the 4-tuples [class-meta, prop-meta, table-name, object-num]
822 sub _select_clause_columns_for_table_property_data {
823 my $self = shift;
824  
825  
826 return [ map { $_->[1]->column_name } @_ ];
827 }
828  
829 # Used to populate the %value_extractor_for_column_name hash
830 # It should return a sub that, when given a row of data from the source,
831 # returns the proper data from that row.
832 #
833 # It's expected to return a sub that accepts ($self, $row, $fh, $filename)
834 # and return a reference to the right data. In most cases, it'll just pluck
835 # out the $column_idx'th element from $@row, but we're using it
836 # to attach special meaning to the $. token
837 sub _create_value_extractor_for_column_name {
838 my($self, $rule, $column_name, $column_idx) = @_;
839  
840 if ($column_name eq '$.') {
841 return sub {
842 my($self, $row, $fh, $filename) = @_;
843 my $line_no = $fh->input_line_number();
844 return \$line_no;
845 };
846 } elsif ($column_name eq '__FILE__') {
847 return sub {
848 my($self,$row,$fh,$filename) = @_;
849 return \$filename;
850 };
851 } else {
852 return sub {
853 my($self, $row, $fh, $filename) = @_;
854 return \$row->[$column_idx];
855 };
856 }
857 }
858  
859  
860 sub create_iterator_closure_for_rule {
861 my($self,$rule) = @_;
862  
863 my $class_name = $rule->subject_class_name;
864 my $class_meta = $class_name->__meta__;
865 my $rule_template = $rule->template;
866  
867 # We're defering to the class metadata here because we don't yet know the
868 # pathnames of the files we'll be reading from. If the columns_from_header flag
869 # is set, then there's no way of knowing what the columns are until then
870 my @column_names = grep { defined }
871 map { $class_meta->column_for_property($_) }
872 $class_meta->all_property_names;
873  
874 # FIXME - leaning on the sorted_columns property here means:
875 # 1) It's useless when used where the path spec is a directory and
876 # classes have table_names, since each file is likely to have different
877 # columns
878 # 2) If we ultimately end up reading from more than one file, all the files
879 # must be sorted in the same way. It's possible the user has sorted each
880 # file differently, though in practice it would make for a lot of trouble
881 my %column_is_sorted_descending;
882 my @sorted_column_names = map { if (index($_, '-') == 0) {
883 my $col = $_;
884 substr($col, 0, 1, '');
885 $column_is_sorted_descending{$col} = 1;
886 $col;
887 } else {
888 $_;
889 }
890 }
891 @{ $self->sorted_columns || [] };
892 my %sorted_column_names = map { $_ => 1 } @sorted_column_names;
893 my @unsorted_column_names = grep { ! exists $sorted_column_names{$_} } @column_names;
894  
895 my @rule_column_names_in_order; # The order we should perform rule matches on - value is the name of the column in the file
896 my @comparison_for_column; # closures to call to perform the match - same order as @rule_column_names_in_order
897 my %rule_column_name_to_comparison_index;
898  
899 my(%property_for_column, %operator_for_column, %value_for_column); # These are used for logging
900  
901 my $resolve_comparator_for_column_name = sub {
902 my $column_name = shift;
903  
904 my $property_name = $class_meta->property_for_column($column_name);
905 return unless $rule->specifies_value_for($property_name);
906  
907 my $operator = $rule->operator_for($property_name)
908 || '=';
909 my $rule_value = $rule->value_for($property_name);
910  
911 $property_for_column{$column_name} = $property_name;
912 $operator_for_column{$column_name} = $operator;
913 $value_for_column{$column_name} = $rule_value;
914  
915 my $comp_function = $self->_comparator_for_operator_and_property(
916 $class_meta->property($property_name),
917 $operator,
918 $rule_value);
919  
920 push @rule_column_names_in_order, $column_name;
921 push @comparison_for_column, $comp_function;
922 $rule_column_name_to_comparison_index{$column_name} = $#comparison_for_column;
923 return 1;
924 };
925  
926 my $sorted_columns_in_rule_count; # How many columns we can consider when trying "the shortcut" for sorted data
927 my %column_is_used_in_sorted_capacity;
928 foreach my $column_name ( @sorted_column_names ) {
929 if (! $resolve_comparator_for_column_name->($column_name)
930 and ! defined($sorted_columns_in_rule_count)
931 ) {
932 # The first time we don't match a sorted column, record the index
933 $sorted_columns_in_rule_count = scalar(@rule_column_names_in_order);
934 } else {
935 $column_is_used_in_sorted_capacity{$column_name} = ' (sorted)';
936 }
937 }
938 $sorted_columns_in_rule_count ||= scalar(@rule_column_names_in_order);
939  
940 foreach my $column_name ( @unsorted_column_names ) {
941 $resolve_comparator_for_column_name->($column_name);
942 }
943  
944 # sort them by filename
945 my @possible_file_info_list = sort { $a->[0] cmp $b->[0] }
946 $self->resolve_file_info_for_rule_and_path_spec($rule);
947  
948 my $table_name = $class_meta->table_name;
949 if (defined($table_name) and $table_name ne '__default__') {
950 # Tack the final file name onto the end if the class has a table name
951 @possible_file_info_list = map { [ $_->[0] . "/$table_name", $_->[1] ] } @possible_file_info_list;
952 }
953  
954 my $handle_class = $self->handle_class;
955 my $use_quick_read = $handle_class eq 'IO::Handle';
956 my $split_regex = $self->_regex();
957 my $logger = $self->_logger('UR_DBI_MONITOR_SQL');
958 my $record_separator = $self->record_separator;
959  
960 my $monitor_start_time = Time::HiRes::time();
961  
962 { no warnings 'uninitialized';
963 $logger->("\nFILE: starting query covering " . scalar(@possible_file_info_list)." files:\n\t"
964 . join("\n\t", map { $_->[0] } @possible_file_info_list )
965 . "\nFILTERS: "
966 . (scalar(@rule_column_names_in_order)
967 ? join("\n\t", map {
968 $_ . $column_is_used_in_sorted_capacity{$_}
969 . " $operator_for_column{$_} "
970 . (ref($value_for_column{$_}) eq 'ARRAY'
971 ? '[' . join(',',@{$value_for_column{$_}}) .']'
972 : $value_for_column{$_} )
973 }
974 @rule_column_names_in_order)
975 : '*none*')
976 . "\n\n"
977 );
978 }
979  
980 my $query_plan = $self->_resolve_query_plan($rule_template);
981 if (@{ $query_plan->{'loading_templates'} } > 1) {
982 Carp::croak(__PACKAGE__ . " does not support joins. The rule was $rule");
983 }
984 my $loading_template = $query_plan->{loading_templates}->[0];
985 my @property_names_in_loading_template_order = @{ $loading_template->{'property_names'} };
986 my @column_names_in_loading_template_order = map { $class_meta->column_for_property($_) }
987 @property_names_in_loading_template_order;
988  
989 my %property_name_to_resultset_index_map;
990 my %column_name_to_resultset_index_map;
991 for (my $i = 0; $i < @property_names_in_loading_template_order; $i++) {
992 my $property_name = $property_names_in_loading_template_order[$i];
993 $property_name_to_resultset_index_map{$property_name} = $i;
994 $column_name_to_resultset_index_map{$class_meta->column_for_property($property_name)} = $i;
995 }
996  
997 my @iterator_for_each_file;
998 foreach ( @possible_file_info_list ) {
999 my $pathname = $_->[0];
1000 my $property_values_from_path_spec = $_->[1];
1001  
1002 my @properties_from_path_spec = keys %$property_values_from_path_spec;
1003 my @values_from_path_spec = values %$property_values_from_path_spec;
1004  
1005 my $pid = $$; # For tracking whether there's been a fork()
1006 my $fh = $handle_class->new($pathname);
1007 unless ($fh) {
1008 $logger->("FILE: Skipping $pathname because it did not open: $!\n");
1009 next; # missing or unopenable files is not fatal
1010 }
1011  
1012 my $column_names_in_order = $self->_resolve_column_names_from_pathname($pathname,$fh);
1013 # %value_for_column_name holds subs that return the value for that column. For values
1014 # determined from the path resolver, save that value here. Most other values get plucked out
1015 # of the line read from the file. The remaining values are special tokens like $. and __FILE__.
1016 # These subs are used both for testing whether values read from the data source pass the rule
1017 # and for constructing the resultset passed up to the Context
1018 my %value_for_column_name;
1019 my %column_name_to_index_map;
1020 my $ordered_column_names_count = scalar(@$column_names_in_order);
1021 for (my $i = 0; $i < $ordered_column_names_count; $i++) {
1022 my $column_name = $column_names_in_order->[$i];
1023 next unless (defined $column_name);
1024 $column_name_to_index_map{$column_name} = $i;
1025 $value_for_column_name{$column_name}
1026 = $self->_create_value_extractor_for_column_name($rule, $column_name, $i);
1027 }
1028 foreach ( '$.', '__FILE__' ) {
1029 $value_for_column_name{$_} = $self->_create_value_extractor_for_column_name($rule, $_, undef);
1030 $column_name_to_index_map{$_} = undef;
1031 }
1032 while (my($prop, $value) = each %$property_values_from_path_spec) {
1033 my $column = $class_meta->column_for_property($prop);
1034 $value_for_column_name{$column} = sub { return \$value };
1035 $column_name_to_index_map{$column} = undef;
1036 }
1037  
1038 # Convert the column_name keys here to indexes into the comparison list
1039 my %column_for_this_comparison_is_sorted_descending =
1040 map { $rule_column_name_to_comparison_index{$_} => $column_is_sorted_descending{$_} }
1041 grep { exists $rule_column_name_to_comparison_index{$_} }
1042 keys %column_is_sorted_descending;
1043  
1044 # rule properties that aren't actually columns in the file should be
1045 # satisfied by the path resolution already, so we can strip them out of the
1046 # list of columns to test
1047 my @rule_columns_in_order = map { $column_name_to_index_map{$_} }
1048 grep { exists $column_name_to_index_map{$_} }
1049 @rule_column_names_in_order;
1050 # And also strip out any items in @comparison_for_column for non-column data
1051 my @comparison_for_column_this_file = map { $comparison_for_column[ $rule_column_name_to_comparison_index{$_} ] }
1052 grep { exists $column_name_to_index_map{$_} }
1053 @rule_column_names_in_order;
1054  
1055 # Burn through the requsite number of header lines
1056 my $lines_read = $fh->input_line_number;
1057 my $throwaway_line_count = $self->header_lines;
1058 while($throwaway_line_count > $lines_read) {
1059 $lines_read++;
1060 scalar($fh->getline());
1061 }
1062  
1063 my $lines_matched = 0;
1064  
1065 my $log_first_fetch;
1066 $log_first_fetch = sub {
1067 $logger->(sprintf("FILE: $pathname FIRST FETCH TIME: %.4f s\n\n", Time::HiRes::time() - $monitor_start_time));
1068 $log_first_fetch = \&UR::Util::null_sub;
1069 };
1070 my $log_first_match;
1071 $log_first_match = sub {
1072 $logger->("FILE: $pathname First match after reading $lines_read lines\n\n");
1073 $log_first_match = \&UR::Util::null_sub;
1074 };
1075  
1076  
1077 my $next_record;
1078  
1079 # This sub reads the next record (line) from the file, splits the line into
1080 # columns and puts the data into @$next_record
1081 my $record_separator_re = qr($record_separator$);
1082 my $read_record_from_file = sub {
1083  
1084 # Make sure some wise guy hasn't changed this out from under us
1085 local $/ = $record_separator;
1086  
1087 if ($pid != $$) {
1088 # There's been a fork() between the original opening and now
1089 # This filehandle is no longer valid to read from, but tell()
1090 # should still report the right position
1091 my $pos = $fh->tell();
1092 $logger->("FILE: reopening file $pathname and seeking to position $pos after fork()\n");
1093 my $fh = $handle_class->new($pathname);
1094 unless ($fh) {
1095 $logger->("FILE: Reopening $pathname after fork() failed: $!\n");
1096 return; # behave if we're at EOF
1097 }
1098 $fh->seek($pos, 0); # fast-forward to the old position
1099 $pid = $$;
1100 }
1101  
1102 my $line;
1103 READ_LINE_FROM_FILE:
1104 while(! defined($line)) {
1105 # Hack for OSX 10.5.
1106 # At EOF, the getline below will return undef. Most builds of Perl
1107 # will also set $! to 0 at EOF so you can distinguish between the cases
1108 # of EOF (which may have actually happened a while ago because of buffering)
1109 # and an actual read error. OSX 10.5's Perl does not, and so $!
1110 # retains whatever value it had after the last failed syscall, likely
1111 # a stat() while looking for a Perl module. This should have no effect
1112 # other platforms where you can't trust $! at arbitrary points in time
1113 # anyway
1114 $! = 0;
1115 $line = $use_quick_read ? <$fh> : $fh->getline();
1116  
1117 if ($line and $line !~ $record_separator_re) {
1118 # Was a short read - probably at EOF
1119 # If the record_separator is a multi-char string, and the last
1120 # characters of $line are the first characters of the
1121 # record_separator, it's likely (though not certain) that the right
1122 # Thing to do is to remove the partial record separator.
1123 for (my $keep_chars = length($record_separator); $keep_chars > 0; $keep_chars--) {
1124 my $match_rs = substr($record_separator, 0, $keep_chars);
1125 if ($line =~ m/$match_rs$/) {
1126 substr($line, 0 - $keep_chars) = '';
1127 last;
1128 }
1129 }
1130 }
1131  
1132 unless (defined $line) {
1133 if ($! && ! $fh->eof()) {
1134 redo READ_LINE_FROM_FILE if ($! == EAGAIN or $! == EINTR);
1135 Carp::croak("read failed for file $pathname: $!");
1136 }
1137  
1138 # at EOF. Close up shop and remove this fh from the list
1139 #flock($fh,LOCK_UN);
1140 $fh = undef;
1141 $next_record = undef;
1142  
1143 $logger->("FILE: $pathname at EOF\n"
1144 . "FILE: $lines_read lines read for this request. $lines_matched matches in this file\n"
1145 . sprintf("FILE: TOTAL EXECUTE-FETCH TIME: %.4f s\n\n", Time::HiRes::time() - $monitor_start_time)
1146 );
1147 return;
1148 }
1149 }
1150 $lines_read++;
1151  
1152 $line =~ s/$record_separator$//; # chomp, but for any value
1153 # FIXME - to support record-oriented files, we need some replacement for this...
1154 $next_record = [ split($split_regex, $line, $ordered_column_names_count) ];
1155 };
1156  
1157 my $number_of_comparisons = @comparison_for_column_this_file;
1158  
1159 # The file filter iterator.
1160 # This sub looks at @$next_record and applies the comparator functions in order.
1161 # If it passes all of them, it constructs a resultset row and passes it up to the
1162 # multiplexer iterator
1163 my $file_filter_iterator = sub {
1164 $log_first_fetch->();
1165  
1166 FOR_EACH_LINE:
1167 for(1) {
1168 $read_record_from_file->();
1169  
1170 unless ($next_record) {
1171 # Done reading from this file
1172 return;
1173 }
1174  
1175 for (my $i = 0; $i < $number_of_comparisons; $i++) {
1176 my $comparison = $comparison_for_column_this_file[$i]->(
1177 $value_for_column_name{ $rule_column_names_in_order[$i] }->($self, $next_record, $fh, $pathname)
1178 );
1179  
1180 if ( ( ($column_for_this_comparison_is_sorted_descending{$i} and $comparison < 0) or $comparison > 0)
1181 and $i < $sorted_columns_in_rule_count
1182 ) {
1183 # We've gone past the last thing that could possibly match
1184 $logger->("FILE: $pathname $lines_read lines read for this request. $lines_matched matches\n"
1185 . sprintf("FILE: TOTAL EXECUTE-FETCH TIME: %.4f s\n", Time::HiRes::time() - $monitor_start_time));
1186  
1187 #flock($fh,LOCK_UN);
1188 return;
1189  
1190 } elsif ($comparison) {
1191 # comparison didn't match, read another line from the file
1192 redo FOR_EACH_LINE;
1193 }
1194  
1195 # That comparison worked... stay in the for() loop for other comparisons
1196 }
1197 }
1198 # All the comparisons return '0', meaning they passed
1199  
1200 $log_first_match->();
1201 $lines_matched++;
1202 my @resultset = map { ref($_) ? $$_ : $_ }
1203 map { ref($value_for_column_name{$_})
1204 ? $value_for_column_name{$_}->($self, $next_record, $fh, $pathname)
1205 : $value_for_column_name{$_} # constant value from path spec
1206 }
1207 @column_names_in_loading_template_order;
1208 return \@resultset;
1209 };
1210  
1211 # Higher layers in the loading logic require rows from the data source to be returned
1212 # in ID order. If the file contents is not sorted primarily by ID, then we need to do
1213 # the less efficient thing by first reading in all the matching rows in one go, sorting
1214 # them by ID, then iterating over the results
1215 unless ($self->file_is_sorted_as_requested($query_plan)) {
1216 my @resultset_indexes_to_sort = map { $column_name_to_resultset_index_map{$_} }
1217 @{ $query_plan->order_by_columns() };
1218 $file_filter_iterator
1219 = $self->_create_iterator_for_custom_sorted_columns($file_filter_iterator, $query_plan, \%column_name_to_resultset_index_map);
1220 }
1221  
1222 push @iterator_for_each_file, $file_filter_iterator;
1223 }
1224  
1225 if (! @iterator_for_each_file) {
1226 return \&UR::Util::null_sub; # No matching files
1227 } elsif (@iterator_for_each_file == 1) {
1228 return $iterator_for_each_file[0]; # If there's only 1 file, no need to multiplex
1229 }
1230  
1231 my @next_record_for_each_file; # in the same order as @iterator_for_each_file
1232  
1233 my %column_is_numeric = map { $_->column_name => $_->is_numeric }
1234 map { $class_meta->property_meta_for_name($_) }
1235 map { $class_meta->property_for_column($_) }
1236 map { index($_, '-') == 0 ? substr($_, 1) : $_ }
1237 @{ $query_plan->order_by_columns };
1238  
1239 my @resultset_index_sort_sub
1240 = map { &_resolve_sorter_for( is_numeric => $column_is_numeric{$_},
1241 is_descending => $column_is_sorted_descending{$_},
1242 column_index => $property_name_to_resultset_index_map{$_});
1243 }
1244 @sorted_column_names;
1245  
1246 my %resultset_idx_is_sorted_descending = map { $column_name_to_resultset_index_map{$_} => 1 }
1247 keys %column_is_sorted_descending;
1248 my $resultset_sorter = sub {
1249 my($idx_a,$idx_b) = shift;
1250  
1251 foreach my $sort_sub ( @resultset_index_sort_sub ) {
1252 my $cmp = $sort_sub->($next_record_for_each_file[$idx_a], $next_record_for_each_file[$idx_b]);
1253 return $cmp if $cmp; # done if they're not equal
1254 }
1255 return 0;
1256 };
1257  
1258 # This is the iterator returned to the Context, and knows about all the individual
1259 # file filter iterators. It compares the next resultset from each of them and
1260 # returns the next resultset to the Context
1261 my $multiplex_iterator = sub {
1262 return unless @iterator_for_each_file; # if they're all run out
1263  
1264 my $lowest_slot;
1265 for(my $i = 0; $i < @iterator_for_each_file; $i++) {
1266 unless(defined $next_record_for_each_file[$i]) {
1267 $next_record_for_each_file[$i] = $iterator_for_each_file[$i]->();
1268 unless (defined $next_record_for_each_file[$i]) {
1269 # That iterator is exhausted, splice it out
1270 splice(@iterator_for_each_file, $i, 1);
1271 splice(@next_record_for_each_file, $i, 1);
1272 return unless (@iterator_for_each_file); # This can happen here if none of the files have matching data
1273 redo;
1274 }
1275 }
1276  
1277 unless (defined $lowest_slot) {
1278 $lowest_slot = $i;
1279 next;
1280 }
1281  
1282 my $cmp = $resultset_sorter->($lowest_slot, $i);
1283 if ($cmp > 0) {
1284 $lowest_slot = $i;
1285 }
1286 }
1287  
1288 my $retval = $next_record_for_each_file[$lowest_slot];
1289 $next_record_for_each_file[$lowest_slot] = undef;
1290 return $retval;
1291 };
1292  
1293 return $multiplex_iterator;
1294 }
1295  
1296  
1297 # Constructors for subs to sort appropriately
1298 sub _resolve_sorter_for {
1299 my %params = @_;
1300  
1301 my $col_idx = $params{'column_index'};
1302  
1303 my $is_descending = (exists($params{'is_descending'}) && $params{'is_descending'})
1304 ||
1305 (exists($params{'is_ascending'}) && $params{'is_ascending'});
1306 my $is_numeric = (exists($params{'is_numeric'}) && $params{'is_numeric'})
1307 ||
1308 (exists($params{'is_string'}) && $params{'is_string'});
1309 if ($is_descending) {
1310 if ($is_numeric) {
1311 return sub($$) { $_[1]->[$col_idx] <=> $_[0]->[$col_idx] };
1312 } else {
1313 return sub($$) { $_[1]->[$col_idx] cmp $_[0]->[$col_idx] };
1314 }
1315 } else {
1316 if ($is_numeric) {
1317 return sub($$) { $_[0]->[$col_idx] <=> $_[1]->[$col_idx] };
1318 } else {
1319 return sub($$) { $_[0]->[$col_idx] cmp $_[1]->[$col_idx] };
1320 }
1321 }
1322 }
1323  
1324 # Higher layers in the loading logic require rows from the data source to be returned
1325 # in ID order. If the file contents is not sorted primarily by ID, then we need to do
1326 # the less efficient thing by first reading in all the matching rows in one go, sorting
1327 # them by ID, then iterating over the results
1328 sub _create_iterator_for_custom_sorted_columns {
1329 my($self, $iterator_this_file, $query_plan, $column_name_to_resultset_index_map) = @_;
1330  
1331 my @matching;
1332 while (my $row = $iterator_this_file->()) {
1333 push @matching, $row; # save matches as [id, rowref]
1334 }
1335  
1336 unless (@matching) {
1337 return \&UR::Util::null_sub; # Easy, no matches
1338 }
1339  
1340 my $class_meta = $query_plan->class_name->__meta__;
1341 my %column_is_numeric = map { $_->column_name => $_->is_numeric }
1342 map { $class_meta->property_meta_for_name($_) }
1343 map { $class_meta->property_for_column($_) }
1344 map { index($_, '-') == 0 ? substr($_,1) : $_ }
1345 @{ $query_plan->order_by_columns };
1346  
1347 my @sorters;
1348 { no warnings 'numeric';
1349 no warnings 'uninitialized';
1350 @sorters = map { &_resolve_sorter_for(%$_) }
1351 map { my $col_name = $_;
1352 my $descending = 0;
1353 if (index($col_name, '-') == 0) {
1354 $descending = 1;
1355 substr($col_name, 0, 1, ''); # remove the -
1356 }
1357 my $col_idx = $column_name_to_resultset_index_map->{$col_name};
1358 { column_index => $col_idx, is_descending => $descending, is_numeric => $column_is_numeric{$col_name} };
1359 }
1360 @{ $query_plan->order_by_columns };
1361 }
1362  
1363 my $sort_by_order_by_columns;
1364 if (@sorters == 1) {
1365 $sort_by_order_by_columns = $sorters[0];
1366 } else {
1367 $sort_by_order_by_columns
1368 = sub($$) {
1369 foreach (@sorters) {
1370 if (my $rv = $_->(@_)) {
1371 return $rv;
1372 }
1373 }
1374 return 0;
1375 };
1376 }
1377 @matching = sort $sort_by_order_by_columns
1378 @matching;
1379  
1380 return sub {
1381 return shift @matching;
1382 };
1383 }
1384  
1385  
1386 sub initializer_should_create_column_name_for_class_properties {
1387 1;
1388 }
1389  
1390  
1391 # The string used to join fields of a row together when writing
1392 #
1393 # Since the 'delimiter' property is interpreted as a regex in the reading
1394 # code, we'll try to be smart about making a real string from that.
1395 #
1396 # subclasses can override this to provide a different implementation
1397 sub column_join_string {
1398 my $self = shift;
1399  
1400 my $join_pattern = $self->delimiter;
1401  
1402 # make some common substitutions...
1403 if ($join_pattern eq '\s*,\s*') {
1404 # The default...
1405 return ', ';
1406 }
1407  
1408 $join_pattern =~ s/\\s*//g; # Turn 0-or-more whitespaces to nothing
1409 $join_pattern =~ s/\\t/\t/; # tab
1410 $join_pattern =~ s/\\s/ /; # whitespace
1411  
1412 return $join_pattern;
1413 }
1414  
1415  
1416 sub _sync_database {
1417 my $self = shift;
1418 my %params = @_;
1419  
1420 unless (ref($self)) {
1421 if ($self->isa("UR::Singleton")) {
1422 $self = $self->_singleton_object;
1423 }
1424 else {
1425 Carp::croak("Cannot call _sync_database as a class method on a non-singleton class");
1426 }
1427 }
1428  
1429 $DB::single=1;
1430 my $changed_objects = delete $params{'changed_objects'};
1431  
1432 my $path_spec = $self->path;
1433  
1434 # First, bin up the changed objects by their class' table_name
1435 my %objects_for_path;
1436 foreach my $obj ( @$changed_objects ) {
1437 my @path = $self->resolve_file_info_for_rule_and_path_spec($obj, $path_spec);
1438 if (!@path) {
1439 $self->error_message("Couldn't resolve destination file for object "
1440 .$obj->class." ID ".$obj->id.": ".Data::Dumper::Dumper($obj));
1441 return;
1442 } elsif (@path > 1) {
1443 $self->error_message("Got multiple filenames when resolving destination file for object "
1444 . $obj->class." ID ".$obj->id.": ".join(', ', @path));
1445 }
1446 $objects_for_path{ $path[0]->[0] } ||= [];
1447 push @{ $objects_for_path{ $path[0]->[0] } }, $obj;
1448 }
1449  
1450 my %objects_for_pathname;
1451 foreach my $path ( keys %objects_for_path ) {
1452 foreach my $obj ( @{ $objects_for_path{$path} } ) {
1453 my $class_meta = $obj->__meta__;
1454 my $table_name = $class_meta->table_name;
1455 my $pathname = $path;
1456 if (defined($table_name) and $table_name ne '__default__') {
1457 $pathname .= '/' . $table_name;
1458 }
1459 $objects_for_pathname{$pathname} ||= [];
1460 push @{ $objects_for_pathname{$pathname} }, $obj;
1461 }
1462 }
1463  
1464 my %column_is_sorted_descending;
1465 my @sorted_column_names = map { if (index($_, '-') == 0) {
1466 my $s = $_;
1467 substr($s, 0, 1, '');
1468 $column_is_sorted_descending{$s} = $s;
1469 } else {
1470 $_;
1471 }
1472 }
1473 @{ $self->sorted_columns() || [] };
1474  
1475 my $handle_class = $self->handle_class;
1476 my $use_quick_read = $handle_class->isa('IO::Handle');
1477  
1478 my $join_string = $self->column_join_string;
1479 my $record_separator = $self->record_separator;
1480 my $split_regex = $self->_regex();
1481 local $/; # Make sure some wise guy hasn't changed this out from under us
1482 $/ = $record_separator;
1483  
1484 my $logger = $self->_logger('UR_DBI_MONITOR_SQL');
1485 my $total_save_time = Time::HiRes::time();
1486 $logger->("FILE: Saving changes to ".scalar(keys %objects_for_pathname) . " files:\n\t"
1487 . join("\n\t", keys(%objects_for_pathname)) . "\n\n");
1488  
1489 foreach my $pathname ( keys %objects_for_pathname ) {
1490 my $use_quick_rename;
1491 my $containing_directory = File::Basename::dirname($pathname);
1492 unless (-d $containing_directory) {
1493 File::Path::mkpath($containing_directory);
1494 }
1495 if (-w $containing_directory) {
1496 $use_quick_rename = 1;
1497 } elsif (! -w $pathname) {
1498 Carp::croak("Cannot save to file $pathname: Neither the directory nor the file are writable");
1499 }
1500  
1501 my $read_fh = $handle_class->new($pathname);
1502  
1503 # Objects going to the same file should all be of a common class
1504 my $class_meta = $objects_for_pathname{$pathname}->[0]->__meta__;
1505  
1506 my @property_names_that_are_sorted = map { $class_meta->property_for_column($_) }
1507 @sorted_column_names;
1508 # Returns true of the passed-in object has a change in one of the sorted columns
1509 my $object_has_changed_sorted_column = sub {
1510 my $obj = shift;
1511 foreach my $prop ( @property_names_that_are_sorted ) {
1512 if (UR::Context->_get_committed_property_value($obj, $prop) ne $obj->$prop) {
1513 return 1;
1514 }
1515 }
1516 return 0;
1517 };
1518  
1519 my $column_names_in_file = $self->_resolve_column_names_from_pathname($pathname, $read_fh);
1520 my $column_names_count = @$column_names_in_file;
1521 my %column_name_to_index;
1522 for (my $i = 0; $i < @$column_names_in_file; $i++) {
1523 $column_name_to_index{$column_names_in_file->[$i]} = $i;
1524 }
1525 # This lets us take a hash slice of the object and get a row for the file
1526 my @property_names_in_column_order = map { $class_meta->property_for_column($_) }
1527 @$column_names_in_file;
1528  
1529 my %column_name_is_numeric = map { $_->column_name => $_->is_numeric }
1530 map { $class_meta->property_meta_for_name($_) }
1531 map { $class_meta->property_for_column($_) }
1532 @$column_names_in_file;
1533  
1534 my $insert = [];
1535 my $update = {};
1536 my $delete = {};
1537 foreach my $obj ( @{ $objects_for_pathname{$pathname} } ) {
1538 if ($obj->isa('UR::Object::Ghost')) {
1539 # This should be removed from the file
1540 my $original = $obj->{'db_committed'};
1541 my $line = join($join_string, @{$original}{@property_names_in_column_order}) . $record_separator;
1542 $delete->{$line} = $obj;
1543  
1544 } elsif ($obj->{'db_committed'}) {
1545 # this is a changed object
1546 my $original = $obj->{'db_committed'};
1547  
1548 if ($object_has_changed_sorted_column->($obj)) {
1549 # One of hte sorted columns has changed. Model this as a delete and insert
1550 push @$insert, [ @{$obj}{@property_names_in_column_order} ];
1551 my $line = join($join_string, @{$original}{@property_names_in_column_order}) . $record_separator;
1552 $delete->{$line} = $obj;
1553 } else {
1554 # This object is changed since it was read in the file
1555 my $original_line = join($join_string, @{$original}{@property_names_in_column_order}) . $record_separator;
1556 my $changed_line = join($join_string, @{$obj}{@property_names_in_column_order}) . $record_separator;
1557 $update->{$original_line} = $changed_line;
1558 }
1559  
1560 } else {
1561 # This object is new and should be added to the file
1562 push @$insert, [ @{$obj}{@property_names_in_column_order} ];
1563 }
1564 }
1565  
1566 my %column_is_sorted_descending;
1567 my @sorted_column_names = map { if (index($_, '-') == 0) {
1568 my $s = $_;
1569 substr($s, 0, 1, '');
1570 $column_is_sorted_descending{$s} = $s;
1571 } else {
1572 $_;
1573 }
1574 }
1575 @{ $self->sorted_columns() || [] };
1576  
1577 my $row_sort_sub;
1578 if (@sorted_column_names) {
1579 my @comparison_subs = map { &_resolve_sorter_for(is_numeric => $column_name_is_numeric{$_},
1580 is_descending => $column_is_sorted_descending{$_},
1581 column_index => $column_name_to_index{$_})
1582 }
1583 @sorted_column_names;
1584  
1585 $row_sort_sub = sub ($$) {
1586 foreach my $comparator ( @comparison_subs ) {
1587 my $cmp = $comparator->($_[0], $_[1]);
1588 return $cmp if $cmp;
1589 }
1590 return 0;
1591 };
1592  
1593 # Put the rows-to-insert in sorted order
1594 my @insert_sorted = sort $row_sort_sub @$insert;
1595 $insert = \@insert_sorted;
1596 }
1597  
1598 my $write_fh = $use_quick_rename
1599 ? File::Temp->new(DIR => $containing_directory)
1600 : File::Temp->new();
1601 unless ($write_fh) {
1602 Carp::croak("Can't save changes for $pathname: Can't create temporary file for writing: $!");
1603 }
1604
1605 my $monitor_start_rime = Time::HiRes::time();
1606 my $time = time();
1607 $logger->(sprintf("\nFILE: SYNC DATABASE AT %s [%s]. Started transaction for %s to temp file %s\n",
1608 $time, scalar(localtime($time)), $pathname, $write_fh->filename));
1609  
1610 # Write headers to the new file
1611 for (my $i = 0; $i < $self->header_lines; $i++) {
1612 my $line = $use_quick_read ? <$read_fh> : $read_fh->getline();
1613 $write_fh->print($line);
1614 }
1615  
1616 my $line;
1617 READ_A_LINE:
1618 while(1) {
1619 unless ($line) {
1620 $line = $use_quick_read ? <$read_fh> : $read_fh->getline();
1621 last unless defined $line;
1622 }
1623  
1624 if (@sorted_column_names and scalar(@$insert)) {
1625 # There are sorted things waiting to insert
1626 my $chomped = $line;
1627 $chomped =~ s/$record_separator$//; # chomp, but for any value
1628 my $row = [ split($split_regex, $chomped, $column_names_count) ];
1629 my $cmp = $row_sort_sub->($row, $insert->[0]);
1630 if ($cmp > 0) {
1631 # write the object's data
1632 no warnings 'uninitialized'; # Some of the object's data may be undef
1633 my $new_row = shift @$insert;
1634 my $new_line = join($join_string, @$new_row) . $record_separator;
1635  
1636 $logger->("FILE: INSERT >>$new_line<<\n");
1637  
1638 $write_fh->print($new_line);
1639 # Don't undef the last line read, meaning it could still be written to the output...
1640 next READ_A_LINE;
1641 }
1642 }
1643  
1644 if (my $obj = delete $delete->{$line}) {
1645 $logger->("FILE: DELETE >>$line<<\n");
1646  
1647 } elsif (my $changed = delete $update->{$line}) {
1648 $logger->("FILE: UPDFATE replace >>$line<< with >>$changed<<\n");
1649 $write_fh->print($changed);
1650  
1651 } else {
1652 # This line form the file was unchanged in the app
1653 $write_fh->print($line);
1654 }
1655 $line = undef;
1656 }
1657  
1658 if (keys %$delete) {
1659 $self->warning_message("There were " . scalar( keys %$delete)
1660 . " deleted " . $class_meta->class_name
1661 . " objects that did not match data in file $pathname");
1662 }
1663 if (keys %$update) {
1664 $self->warning_message("There were " . scalar( keys %$delete)
1665 . " updated " . $class_meta->class_name
1666 . " objects that did not match data in file $pathname");
1667 }
1668  
1669 # finish out by writing the rest of the new data
1670 foreach my $new_row ( @$insert ) {
1671 no warnings 'uninitialized'; # Some of the object's data may be undef
1672 my $new_line = join($join_string, @$new_row) . $record_separator;
1673 $logger->("FILE: INSERT >>$new_line<<\n");
1674 $write_fh->print($new_line);
1675 }
1676  
1677 my $changed_objects = $objects_for_pathname{$pathname};
1678 unless ($self->_set_specified_objects_saved_uncommitted( $changed_objects )) {
1679 Carp::croak("Error setting objects to a saved state after syncing");
1680 }
1681 # These closures will keep $write_fh in scope and delay their removal until
1682 # commit() or rollback(). Call these with no args to commit, and one arg (doesn't
1683 # matter what) to roll back
1684 my $commit = $use_quick_rename
1685 ? sub {
1686 if (@_) {
1687 $self->_set_specified_objects_saved_rolled_back($changed_objects);
1688 } else {
1689 my $temp_filename = $write_fh->filename;
1690 $logger->("FILE: COMMIT rename $temp_filename => $pathname\n");
1691 unless (rename($temp_filename, $pathname)) {
1692 $self->error_message("Can't rename $temp_filename to $pathname: $!");
1693 return;
1694 }
1695 $self->_set_specified_objects_saved_committed($changed_objects);
1696 }
1697 return 1;
1698 }
1699 :
1700 sub {
1701 if (@_) {
1702 $self->_set_specified_objects_saved_rolled_back($changed_objects);
1703 } else {
1704 my $temp_filename = $write_fh->filename;
1705 $logger->("FILE: COMMIT copy " . $temp_filename . " => $pathname\n");
1706 my $read_fh = IO::File->new($temp_filename);
1707 unless ($read_fh) {
1708 $self->error_message("Can't open file $temp_filename for reading: $!");
1709 return;
1710 }
1711 my $copy_fh = IO::File->new($pathname, 'w');
1712 unless ($copy_fh) {
1713 $self->error_message("Can't open file $pathname for writing: $!");
1714 return;
1715 }
1716  
1717 while(<$read_fh>) {
1718 $copy_fh->print($_);
1719 }
1720 $copy_fh->close();
1721 $read_fh->close();
1722 $self->_set_specified_objects_saved_committed($changed_objects);
1723 }
1724 return 1;
1725 };
1726  
1727 $write_fh->close();
1728  
1729 $self->{'__saved_uncommitted'} ||= [];
1730 push @{ $self->{'__saved_uncommitted'} }, $commit;
1731  
1732 $time = time();
1733 $logger->("\nFILE: SYNC DATABASE finished ".$write_fh->filename . "\n");
1734 }
1735  
1736 $logger->(sprintf("Saved changes to %d files in %.4f s\n",
1737 scalar(@{ $self->{'__saved_uncommitted'}}), Time::HiRes::time() - $total_save_time));
1738 return 1;
1739 }
1740  
1741 sub commit {
1742 my $self = shift;
1743 if (! ref($self) and $self->isa('UR::Singleton')) {
1744 $self = $self->_singleton_object;
1745 }
1746  
1747 if ($self->{'__saved_uncommitted'}) {
1748 foreach my $commit ( @{ $self->{'__saved_uncommitted'}}) {
1749 $commit->();
1750 }
1751 }
1752 delete $self->{'__saved_uncommitted'};
1753  
1754 return 1;
1755 }
1756  
1757  
1758 sub rollback {
1759 my $self = shift;
1760 if (! ref($self) and $self->isa('UR::Singleton')) {
1761 $self = $self->_singleton_object;
1762 }
1763  
1764 if ($self->{'__saved_uncommitted'}) {
1765 foreach my $commit ( @{ $self->{'__saved_uncommitted'}}) {
1766 $commit->('rollback');
1767 }
1768 }
1769 delete $self->{'__saved_uncommitted'};
1770  
1771 return 1;
1772 }
1773  
1774  
1775 1;
1776  
1777 __END__