OpenInteract2/SQLInstall.pm

filter: Statementstmt 91.6% 22 / 24 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 93.7% 30 / 32 CC 1 SCAR 0.4
CC
1
Cov
92%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« OpenInteract2/Action/CommonSearch.pm ↑ Summary OpenInteract2/Brick/Widgets.pm »
1 package OpenInteract2::SQLInstall;
2  
3 # $Id: SQLInstall.pm,v 1.30 2005/03/17 14:57:58 sjn Exp $
4  
5 87 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 87 ▶use base qw( Class::Accessor::Fast );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 87 ▶use Log::Log4perl qw( get_logger );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 87 ▶use DateTime;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 87 ▶use OpenInteract2::Constants qw( :log );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 87 ▶use OpenInteract2::Context qw( CTX );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 87 ▶use OpenInteract2::Exception qw( oi_error );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 0 ▶use SPOPS::Import;
Subroutine BEGIN: called CC=1 SCAR=2.6
13  
14 $OpenInteract2::SQLInstall::VERSION = sprintf("%d.%02d", q$Revision: 1.30 $ =~ /(\d+)\.(\d+)/);
15  
16 my ( $log );
17  
18 my @FIELDS = qw( package );
19 OpenInteract2::SQLInstall->mk_accessors( @FIELDS );
20  
21 my $STRUCT_DIR = 'struct';
22 my $DATA_DIR = 'data';
23  
24 sub new_from_package {
25 my ( $class, $package ) = @_;
26 $log ||= get_logger( LOG_INIT );
27  
28 unless ( UNIVERSAL::isa( $package, 'OpenInteract2::Package' ) ) {
29 oi_error "Cannot create SQL installer from item that is not a package";
30 }
31 my $install_class = $package->config->sql_installer;
32 unless ( $install_class ) {
33 $log->warn( "No SQL installer specified in config for ",
34 $package->name );
35 return undef;
36 }
37 eval "require $install_class";
38 if ( $@ ) {
39 oi_error "Failed to include SQL install class [$install_class] ",
40 "specified in package ", $package->full_name;
41 }
42 return $install_class->new({ package => $package });
43 }
44  
45 sub new {
46 my ( $class, $params ) = @_;
47 $log ||= get_logger( LOG_INIT );
48  
49 my $self = bless( { _status => {},
50 _error => {},
51 _statement => {},
52 }, $class );
53 for ( @FIELDS ) {
54 $self->$_( $params->{ $_ } ) if ( $params->{ $_ } );
55 }
56 $self->init( $params );
57 return $self;
58 }
59  
60 sub init {}
61  
62 ########################################
63 # GET/SET ITEM STATE TRACKING
64  
65 sub get_status {
66 my ( $self, $file ) = @_;
67 if ( $file ) {
68 return $self->{_status}{ $file };
69 }
70 my @status = ();
71 foreach my $status_file ( sort keys %{ $self->{_status} } ) {
72 if ( $self->{_status}{ $status_file } ) {
73 push @status, { is_ok => 'yes',
74 filename => $status_file };
75 }
76 else {
77 push @status, { is_ok => 'no',
78 filename => $status_file,
79 message => $self->get_error( $status_file ) };
80 }
81 }
82 return @status;
83 }
84  
85 sub get_error {
86 my ( $self, $file ) = @_;
87 return $self->{_error}{ $file };
88 }
89  
90 sub get_statement {
91 my ( $self, $file ) = @_;
92 return ( $self->{_statement}{ $file } )
93 ? $self->{_statement}{ $file } : 'n/a';
94 }
95  
96 sub get_datasource {
97 my ( $self, $file ) = @_;
98 return ( $self->{_datasource}{ $file } )
99 ? $self->{_datasource}{ $file } : 'n/a';
100 }
101  
102  
103 # These are private
104  
105 sub _set_status {
106 my ( $self, $file, $status ) = @_;
107 $self->{_status}{ $file } = $status;
108 }
109  
110 sub _set_error {
111 my ( $self, $file, $error ) = @_;
112 $self->{_error}{ $file } = $error;
113 }
114  
115 sub _set_statement {
116 my ( $self, $file, $statement ) = @_;
117 $self->{_statement}{ $file } = $statement;
118 }
119  
120 sub _set_datasource {
121 my ( $self, $file, $ds ) = @_;
122 $self->{_datasource}{ $file } = $ds;
123 }
124  
125 # Set most everything at once (normally done with errors)
126  
127 sub _set_state {
128 my ( $self, $file, $status, $error, $statement ) = @_;
129 $file ||= '';
130 $self->{_status}{ $file } = $status;
131 $self->{_error}{ $file } = $error;
132 $self->{_statement}{ $file } = $statement;
133 }
134  
135  
136 ########################################
137 # SUBCLASSES OVERRIDE
138  
139 sub get_structure_set { return undef }
140 sub get_structure_file { return undef }
141 sub get_data_file { return undef }
142 sub get_security_file { return undef }
143 sub get_migration_information { return undef }
144  
145  
146 ########################################
147 # INSTALL
148  
149 sub install_all {
150 my ( $self ) = @_;
151 unless ( UNIVERSAL::isa( $self->package, 'OpenInteract2::Package' ) ) {
152 oi_error 'Cannot install without first setting package';
153 }
154  
155 $log->is_info &&
156 $log->info( "Installing structure, data and security for package ",
157 $self->package->full_name );
158 $self->install_structure;
159 $self->install_data;
160 $self->install_security;
161 }
162  
163  
164 ########################################
165 # INSTALL STRUCTURE
166  
167 sub install_structure {
168 my ( $self, @restrict_files ) = @_;
169  
170 # filter out empty/undef items
171 @restrict_files = grep { $_ } @restrict_files;
172  
173 my $pkg = $self->package;
174 unless ( UNIVERSAL::isa( $self->package, 'OpenInteract2::Package' ) ) {
175 oi_error 'Cannot install structure without first setting package';
176 }
177  
178 $log->is_info &&
179 $log->info( "Installing structure for package ",
180 $self->package->full_name, "and skipping files [",
181 join( '] [', @restrict_files ), ']' );
182  
183 my $package_name = $pkg->name;
184  
185 # Note: We can't have the importer send the SQL directly to the
186 # database since we may create tables that don't correspond to
187 # SPOPS objects.
188  
189 my $importer = SPOPS::Import->new( 'table' );
190 $importer->return_only(1);
191 $importer->transforms( [ \&_transform_usertype,
192 \&_transform_grouptype ] );
193  
194 my @sets = $self->_massage_arrayref( $self->get_structure_set );
195  
196 my $full_spops_conf = CTX->spops_config;
197 unless ( ref( $full_spops_conf ) eq 'HASH' ) {
198 my $website_dir = $pkg->repository->website_dir;
199 oi_error "SPOPS configuration is not yet defined, cannot continue. ",
200 "This probably means the context didn't initialize ",
201 "properly -- look in $website_dir/logs/oi2.log for ",
202 "enlightenment.";
203 }
204  
205 STRUCTURE:
206 foreach my $structure_set ( @sets ) {
207 my ( $ds_name, $ds_info, $ds );
208 $log->is_info &&
209 $log->info( "Trying to evaluate structure '$structure_set'" );
210 eval {
211 if ( $structure_set eq 'system' ) {
212 $ds_name = CTX->lookup_system_datasource_name;
213 }
214 elsif ( $structure_set =~ /^datasource:\s*(\w+)\s*$/ ) {
215 $ds_name = $1;
216 }
217 else {
218 unless ( exists $full_spops_conf->{ $structure_set } ) {
219 oi_error "Set '$structure_set' pulled from package ",
220 "'$package_name' is not a valid SPOPS key.";
221 }
222 $ds_name = $full_spops_conf->{ $structure_set }{datasource};
223 }
224 $ds_info = CTX->datasource_manager->get_datasource_info( $ds_name );
225 $ds = CTX->datasource( $ds_name );
226 };
227 if ( $@ ) {
228 $log->error( "Failed to get datasource '$ds_name': $@" );
229 $self->_set_state( "Set: $structure_set",
230 undef,
231 "Error creating datasource: $@",
232 undef );
233 next STRUCTURE;
234 }
235 my $driver_name = $ds_info->{sql_install}
236 || $ds_info->{driver_name};
237 my @all_files = $self->_massage_arrayref(
238 $self->get_structure_file( $structure_set, $driver_name )
239 );
240  
241 my $num_skip_files = scalar @restrict_files;
242 my %restrict_to = map { $_ => 1 } @restrict_files;
243  
244 foreach my $structure_file ( @all_files ) {
245 if ( $num_skip_files and ! $restrict_to{ $structure_file } ) {
246 $log->info( "Skipping file '$structure_file' since ",
247 "$num_skip_files files were specified to ",
248 "skip and this one is not in the list" );
249 next;
250 }
251 $log->info( "Processing structure file '$structure_file'" );
252 $self->_set_datasource( $structure_file, $ds_name );
253  
254 my ( $table_sql );
255 my $relative_file = "$STRUCT_DIR/$structure_file";
256 my $full_file = $pkg->find_file( $relative_file );
257 eval {
258 $table_sql = $pkg->read_file( $relative_file );
259 };
260 if ( $@ or ! $table_sql ) {
261 my $error = $@ || "File cannot be found or it is empty";
262 $log->error( $error );
263 $self->_set_state( $full_file,
264 undef, $error, undef );
265 next STRUCTURE;
266 }
267  
268 $importer->database_type( $driver_name );
269 $importer->data( $table_sql );
270 my $full_table_sql = $importer->run;
271 $self->_set_statement( $structure_file, $full_table_sql );
272 eval { $ds->do( $full_table_sql ) };
273 if ( $@ ) {
274 $log->error( "Caught exception ($@) running 'do' on SQL:\n",
275 $full_table_sql );
276 $self->_set_status( $full_file, undef );
277 $self->_set_error( $full_file, $@ );
278 }
279 else {
280 $log->info( "SQL from '$full_file' processed ok" );
281 $self->_set_status( $full_file, 1 );
282 $self->_set_error( $full_file, undef );
283 }
284 }
285 }
286 return $self;
287 }
288  
289  
290 sub _transform_usertype {
291 my ( $self, $sql ) = @_;
292 my $type = CTX->lookup_id_config( 'user_type' ) || 'int';
293 if ( $type eq 'char' ) {
294 my $size = CTX->lookup_id_config( 'user_size' ) || 25;
295 $$sql =~ s/%%USERID_TYPE%%/VARCHAR($size)/g;
296 }
297 elsif ( $type eq 'int' ) {
298 $$sql =~ s/%%USERID_TYPE%%/INT/g;
299 }
300 else {
301 oi_error "Given user type '$type' invalid. Only available ",
302 "types are 'int' and 'char'.";
303 }
304 }
305  
306  
307 sub _transform_grouptype {
308 my ( $self, $sql ) = @_;
309 my $type = CTX->lookup_id_config( 'group_type' ) || 'int';
310 if ( $type eq 'char' ) {
311 my $size = CTX->lookup_id_config( 'group_size' ) || 25;
312 $$sql =~ s/%%GROUPID_TYPE%%/VARCHAR($size)/g;
313 }
314 elsif ( $type eq 'int' ) {
315 $$sql =~ s/%%GROUPID_TYPE%%/INT/g;
316 }
317 else {
318 oi_error "Given group type '$type' invalid. Only available ",
319 "types are 'int' and 'char'.";
320 }
321 }
322  
323  
324 ########################################
325 # INSTALL DATA/SECURITY
326  
327  
328 sub install_data {
329 my ( $self ) = @_;
330 unless ( UNIVERSAL::isa( $self->package, 'OpenInteract2::Package' ) ) {
331 oi_error 'Cannot install data without first setting package';
332 }
333 my @files = $self->_massage_arrayref( $self->get_data_file );
334 return unless ( scalar @files );
335 $self->process_data_file( @files );
336 }
337  
338  
339 sub install_security {
340 my ( $self ) = @_;
341 unless ( UNIVERSAL::isa( $self->package, 'OpenInteract2::Package' ) ) {
342 oi_error 'Cannot install data without first setting package';
343 }
344 my @files = $self->_massage_arrayref( $self->get_security_file );
345 return unless ( scalar @files );
346 $self->process_data_file( @files );
347 }
348  
349  
350 sub process_data_file {
351 my ( $self, @files ) = @_;
352 my $pkg = $self->package;
353  
354 DATAFILE:
355 foreach my $data_file ( @files ) {
356 my $relative_file = "$DATA_DIR/$data_file";
357 my $full_file = $pkg->find_file( $relative_file );
358 my $data_text = $pkg->read_file( $relative_file );
359 my ( $data_struct );
360 {
361 no strict 'vars';
362 $data_struct = eval $data_text;
363 if ( $@ ) {
364 $self->_set_state( $full_file,
365 undef,
366 "Invalid Perl data structure: $@",
367 undef );
368 next DATAFILE;
369 }
370 }
371 $log->is_debug &&
372 $log->debug( "Data structure read from '$full_file': ",
373 CTX->dump( $data_struct ) );
374 my $import_type = $data_struct->[0]->{import_type};
375 unless ( $import_type ) {
376 $self->_set_state( $full_file,
377 undef,
378 "No 'import_type' specified, cannot process",
379 undef );
380 next DATAFILE;
381 }
382 my ( $importer );
383 eval {
384 $importer = SPOPS::Import->new( $import_type )
385 ->assign_raw_data( $data_struct );
386 };
387 if ( $@ || ! $importer ) {
388 my $error = $@ || 'No exception, but importer object not returned';
389 $self->_set_state( $full_file,
390 undef,
391 "Failed to create importer: $error",
392 undef );
393 next DATAFILE;
394 }
395  
396 my ( $ds_name );
397 if ( $import_type eq 'object' ) {
398 my $spops_class = $data_struct->[0]->{spops_class};
399 $ds_name = $spops_class->CONFIG->{datasource};
400 }
401 elsif ( $import_type =~ /^(dbdata|dbupdate|dbdelete)$/ ) {
402 my $ds_lookup = $data_struct->[0]->{datasource_pointer};
403 if ( $ds_lookup eq 'system' ) {
404 $ds_name = CTX->lookup_system_datasource_name;
405 }
406 elsif ( $ds_lookup =~ /^datasource:\s*(\w+)\s*$/ ) {
407 $ds_name = $1;
408 }
409 else {
410 unless ( exists CTX->spops_config->{ $ds_lookup } ) {
411 $self->_set_state( undef,
412 "Cannot find datasource for pointer '$ds_lookup'",
413 undef );
414 next DATAFILE;
415 }
416 $ds_name = CTX->spops_config->{ $ds_lookup }{datasource};
417 }
418  
419 # Now that we have the datasource name, get the actual
420 # datasource
421  
422 $importer->db( CTX->datasource( $ds_name ) );
423 }
424  
425 $self->_set_datasource( $data_file, $ds_name );
426 $self->transform_data( $importer );
427 my $file_status = $importer->run;
428  
429 my $file_ok = 1;
430 my @errors = ();
431 my @ok = ();
432 foreach my $status ( @{ $file_status } ) {
433 if ( $status->[0] and ref $status->[1] ne 'ARRAY') {
434 push @ok, $status->[1]->id;
435 }
436 elsif ( $status->[0] ) {
437 push @ok, $status->[1][0]; # assume the first item is an ID...
438 }
439 else {
440 $file_ok = 0;
441 push @errors, $status->[2];
442 }
443 }
444 my $insert_ok = join( ', ', @ok );
445 if ( $file_ok ) {
446 $self->_set_state( $full_file,
447 1, undef, "Inserted: $insert_ok" );
448 }
449 else {
450 $self->_set_state( $full_file,
451 undef,
452 join( "\n", @errors ),
453 "Inserted: $insert_ok" );
454 }
455 }
456 }
457  
458  
459 sub transform_data {
460 my ( $self, $importer ) = @_;
461 my $metadata = $importer->extra_metadata;
462 my $field_ord = $importer->fields_as_hashref;
463 foreach my $data ( @{ $importer->data } ) {
464 if ( $metadata->{transform_default} ) {
465 for ( @{ $metadata->{transform_default} } ) {
466 my $idx = $field_ord->{ $_ };
467 if ( $data->[ $idx ] ) {
468 $data->[ $idx ] =
469 $self->_transform_default( $data->[ $idx ] );
470 }
471 }
472 }
473 if ( $metadata->{transform_now} ) {
474 for ( @{ $metadata->{transform_now} } ) {
475 my $idx = $field_ord->{ $_ };
476 $data->[ $idx ] =
477 $self->_transform_now( $data->[ $idx ] );
478 }
479 }
480 }
481 }
482  
483  
484 sub _transform_default {
485 my ( $self, $value ) = @_;
486 return $value unless ( $value );
487 my $default_value = CTX->lookup_default_object_id( $value );
488 return $default_value || $value;
489 }
490  
491  
492 sub _transform_now {
493 my ( $self ) = @_;
494 return DateTime->now->strftime( '%Y-%m-%d %T' );
495 }
496  
497  
498 ########################################
499 # MIGRATE
500  
501 sub migrate_data {
502 my ( $self, $migrate_ds ) = @_;
503 unless ( UNIVERSAL::isa( $self->package, 'OpenInteract2::Package' ) ) {
504 oi_error 'Cannot migrate data without first setting package';
505 }
506 $log ||= get_logger( LOG_INIT );
507  
508 my @migrations = $self->_massage_arrayref(
509 $self->get_migration_information()
510 );
511 unless ( scalar @migrations > 0 ) {
512 $log->info( "No migrations found for package ", $self->package->name,
513 "; nothing to do" );
514 return;
515 }
516  
517 # Disable tracking using a supersekrit invocation; this should
518 # last until the subroutine ends
519  
520 local $OpenInteract2::SPOPS::TRACKING_DISABLED = 1;
521  
522 $log->info( "Migrating data from package ", $self->package->name, " ",
523 "with ", scalar @migrations, " migration packets." );
524 MIGRATION:
525 foreach my $migration_info ( @migrations ) {
526  
527 # Now do the migration for this information. Each migration
528 # implementation routine is responsible for adding the
529 # status(es) of the action.
530  
531 # First try data-to-object...
532  
533 if ( $migration_info->{spops_class} ) {
534 $self->_migrate_data_to_object( $migration_info, $migrate_ds );
535 }
536  
537 # ...and data-to-data
538  
539 else {
540 $self->_migrate_data_to_data( $migration_info, $migrate_ds );
541 }
542 }
543 return $self;
544 }
545  
546 # $info should be something like:
547 # \% spops_class => $
548 # table => $
549 # field => { new => \@, old => \@ }
550 # transform_sub => \& | [ \& ]
551 # include_id => $ ('yes|no')
552  
553 sub _migrate_data_to_object {
554 my ( $self, $info, $migrate_ds ) = @_;
555 $log ||= get_logger( LOG_INIT );
556  
557 my $spops_class = $info->{spops_class};
558 my $state_tag = "Migration to class $spops_class";
559 $log->info( "Migrating data to class '$spops_class'" );
560  
561 # First be sure that we've actually got an SPOPS class...
562  
563 my $config = eval { $spops_class->CONFIG };
564 if ( $@ or ! $config ) {
565 my $error = $@ || 'not a valid SPOPS class';
566 $self->_set_state( $state_tag, undef,
567 "Failed to read configuration from class: $error",
568 undef );
569 $log->error( "Cannot read CONFIG from '$spops_class': $error" );
570 return;
571 }
572  
573 # If 'table' undefined use the value from the SPOPS class for both
574 # source and destination
575  
576 unless ( $info->{table} ) {
577 $info->{table} = $spops_class->table_name;
578 }
579  
580 # If 'field' undefined use the value from the SPOPS class for both
581 # source and destination
582  
583 unless ( $info->{field} ) {
584 $info->{field} = $spops_class->field_list;
585 }
586  
587 $log->info( "Reading old data from table '$info->{table}'" );
588  
589 my @old_fields = ();
590 if ( ref $info->{field} eq 'HASH' and scalar keys %{ $info->{field} } ) {
591 @old_fields = $self->_massage_arrayref( $info->{field}{old} );
592 }
593 elsif ( ref $info->{field} eq 'HASH' ) {
594 @old_fields = ();
595 }
596 else {
597 @old_fields = $self->_massage_arrayref( $info->{field} );
598 }
599  
600 # If 'fields' undefined or empty then pull the fieldnames from the
601 # SPOPS class, assuming they're the same between the two tables
602  
603 if ( scalar @old_fields == 0 ) {
604 @old_fields = @{ $spops_class->field_list };
605 }
606 $log->info( "Reading data from old fields: ",
607 join( ', ', @old_fields ) );
608  
609 my $records = eval {
610 $self->_migrate_fetch_old_data(
611 $migrate_ds, $info->{table}, \@old_fields );
612 };
613 if ( $@ ) {
614 $log->error( "Failed to fetch old data: $@" );
615 $self->_set_state( $state_tag, undef,
616 "Failed to fetch data from old datasource: $@",
617 undef );
618 return;
619 }
620 my @object_fields = ( ref $info->{field} eq 'HASH' )
621 ? $self->_massage_arrayref( $info->{field}{new} )
622 : $self->_massage_arrayref( $info->{field} );
623 my @transforms = $self->_massage_arrayref( $info->{transform_sub} );
624  
625 my @errors = ();
626 my $success = 0;
627 my $rec_count = 0;
628  
629 my $num_fields = scalar( @object_fields ) - 1;
630 foreach my $rec ( @{ $records } ) {
631 $rec_count++;
632 # $log->info( "Record fetched:\n", CTX->dump( $rec ) );
633 my %object_data = map { $object_fields[ $_ ] => $rec->[ $_ ] }
634 ( 0 .. $num_fields );
635 # $log->info( "Assigning data to new object\n", CTX->dump( \%object_data ) );
636 my $object = $spops_class->new( \%object_data );
637 foreach my $tsub ( @transforms ) {
638 next unless ( ref $tsub eq 'CODE' );
639 $tsub->( $info, $rec, $object );
640 }
641 $log->info( "Trying to create object [#$rec_count] ID ",
642 "[", $object->id, "]" );
643 eval { $object->save({ skip_security => 'yes', is_add => 1 }) };
644 if ( $@ ) {
645 $log->error( "Failed with [#$rec_count]: $@" );
646 push @errors, "Record #$rec_count (ID: ", scalar( $object->id ), ": $@";
647 }
648 else {
649 $log->info( "Added record [#$rec_count] ok" );
650 $success++;
651 }
652 }
653 if ( scalar @errors ) {
654 $self->_set_state( $state_tag, undef,
655 join( "\n", @errors ),
656 "Migrated: $success records" );
657 }
658 else {
659 $self->_set_state( $state_tag, 1, undef,
660 "Migrated: $success records" );
661 }
662 }
663  
664 # $info should be something like:
665 # \% table => { new => $, old => $ }
666 # field => { new => \@, old => \@ },
667 # transform_sub => [ \& ],
668  
669 sub _migrate_data_to_data {
670 my ( $self, $info, $migrate_ds ) = @_;
671 $log ||= get_logger( LOG_INIT );
672  
673 # Do some initial sanity checking
674  
675 unless ( $info->{table} ) {
676 $self->_set_state( "Migration (unknown)",
677 undef,
678 "The key 'table' must be specified in the migration information",
679 undef );
680 return;
681 }
682  
683 my @old_fields = ( ref $info->{field} eq 'HASH' )
684 ? $self->_massage_arrayref( $info->{field}{old} )
685 : $self->_massage_arrayref( $info->{field} );
686 my $old_table = ( ref $info->{table} eq 'HASH' )
687 ? $info->{table}{old}
688 : $info->{table};
689 my @new_fields = ( ref $info->{field} eq 'HASH' )
690 ? $self->_massage_arrayref( $info->{field}{new} )
691 : $self->_massage_arrayref( $info->{field} );
692 my $new_table = ( ref $info->{table} eq 'HASH' )
693 ? $info->{table}{new}
694 : $info->{table};
695 my $state_tag = "Migration from $old_table -> $new_table";
696 $log->info( "Migrating data from table '$old_table' to '$new_table'" );
697 $log->info( "Migrating data from fields\n[",
698 join( ', ', @old_fields ), "] to\n[",
699 join( ', ', @new_fields ), "]" );
700  
701 my $records = eval {
702 $self->_migrate_fetch_old_data( $migrate_ds, $old_table, \@old_fields );
703 };
704 if ( $@ ) {
705 $log->error( "Failed to fetch old data: $@" );
706 $self->_set_state( $state_tag, undef,
707 "Failed to fetch data from old datasource: $@",
708 undef );
709 return;
710 }
711  
712 my $new_field_listing = join( ', ', @new_fields );
713 my $new_field_ph = join( ', ', map { '?' } @new_fields );
714 my $insert_sql = qq{
715 INSERT INTO $new_table ( $new_field_listing )
716 VALUES ( $new_field_ph )
717 };
718 $log->info( "Generated INSERT prepare SQL:\n$insert_sql" );
719  
720 # gets the primary datasource...
721 my $new_ds = CTX->datasource;
722 my ( $sth );
723 eval {
724 $sth = $new_ds->prepare( $insert_sql );
725 };
726 if ( $@ ) {
727 $log->error( "Failed to prepare INSERT: $@" );
728 $self->_set_state( $state_tag, undef,
729 "Cannot prepare INSERT for new data: $@",
730 undef );
731 return;
732 }
733  
734 my @transforms = $self->_massage_arrayref( $info->{transform_sub} );
735 my @errors = ();
736 my $success = 0;
737 my $rec_count = 0;
738 my $num_fields = scalar( @new_fields ) - 1;
739  
740 foreach my $rec ( @{ $records } ) {
741 $rec_count++;
742 #$log->info( "Assigning record\n", CTX->dump( $rec ) );
743 my %new_value_hash = map { $new_fields[ $_ ] => $rec->[ $_ ] }
744 ( 0 .. $num_fields );
745 foreach my $tsub ( @transforms ) {
746 next unless ( ref $tsub eq 'CODE' );
747 $tsub->( $info, $rec, \%new_value_hash );
748 }
749 my @insert_data = map { $new_value_hash{ $_ } } @new_fields;
750 $log->info( "Creating new record with data [",
751 join( "] [", @insert_data ), "]" );
752 eval { $sth->execute( @insert_data ) };
753 if ( $@ ) {
754 $log->error( "Error creating new record [#$rec_count]: $@" );
755 push @errors, "Record #$rec_count: $@";
756 }
757 else {
758 $log->error( "Added new record [#$rec_count] ok" );
759 $success++;
760 }
761 }
762 if ( scalar @errors ) {
763 $self->_set_state( $state_tag, undef,
764 join( "\n", @errors ),
765 "Migrated: $success records" );
766 }
767 else {
768 $self->_set_state( $state_tag, 1, undef,
769 "Migrated: $success records" );
770 }
771 }
772  
773 sub _migrate_fetch_old_data {
774 my ( $self, $ds, $table, $fields ) = @_;
775 $log ||= get_logger( LOG_INIT );
776 my $num_fields = scalar( @{ $fields } ) - 1;
777 my $field_listing = join( ', ', @{ $fields } );
778 my $sql = qq{SELECT $field_listing FROM $table};
779 $log->info( "SQL for fetching old data:\n$sql" );
780 my $sth = $ds->prepare( $sql );
781 $sth->execute;
782 my @records = ();
783 while ( my $row = $sth->fetchrow_arrayref ) {
784 #my %data = map { $fields->[ $_ ] => $row->[ $_ ] } ( 0..$num_fields );
785 #push @records, \%data;
786 push @records, [ @{ $row } ];
787 }
788 $log->info( "Returning ", scalar( @records ), " records from old table" );
789 return \@records;
790 }
791  
792  
793 ########################################
794 # UTILS
795  
796 sub _massage_arrayref {
797 my ( $self, $files ) = @_;
798 return () unless ( $files );
799 return ( ref $files eq 'ARRAY' ) ? @{ $files } : ( $files );
800 }
801  
802 1;
803  
804 __END__
« OpenInteract2/Action/CommonSearch.pm ↑ Summary OpenInteract2/Brick/Widgets.pm »