| 1 | package DB::Introspector::SerializeUtil; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use Storable qw( nstore_fd fd_retrieve ); | ||
| 5 | |||
| 6 | |||
| 7 | sub serialize { | ||
| 8 | my $class = shift; | ||
| 9 | my $introspector = shift; | ||
| 10 | my $fh = shift || *STDOUT; | ||
| 11 | |||
| 12 | my $dbh = $introspector->dbh; | ||
| 13 | $introspector->_clear_dbh; | ||
| 14 | |||
| 15 | my %storage_hash; | ||
| 16 | $storage_hash{dbname} = _dbh_id($dbh); | ||
| 17 | $storage_hash{introspector} = $introspector; | ||
| 18 | |||
| 19 | nstore_fd(\%storage_hash, $fh); | ||
| 20 | |||
| 21 | $introspector->_set_dbh($dbh); | ||
| 22 | } | ||
| 23 | |||
| 24 | sub serialize_to_file { | ||
| 25 | my $class = shift; | ||
| 26 | my $introspector = shift; | ||
| 27 | my $filename = shift; | ||
| 28 | |||
| 29 | my $fh = new IO::File( ">$filename" ) | ||
| 30 | || die($!); | ||
| 31 | $class->serialize($introspector, $fh); | ||
| 32 | } | ||
| 33 | |||
| 34 | |||
| 35 | sub deserialize { | ||
| 36 | my $class = shift; | ||
| 37 | my $fh = shift; | ||
| 38 | my $dbh = shift || die("\$class->deserialize(\$fh, \$dbh) requires a dbh"); | ||
| 39 | |||
| 40 | my $storage_ref = fd_retrieve($fh); | ||
| 41 | if( $storage_ref->{dbname} ne _dbh_id($dbh) ) { | ||
| 42 | die("DBName in handle: ", _dbh_id($dbh), " | ||
| 43 | doesn't match dbname in serialized: ", | ||
| 44 | $storage_ref->{dbname}); | ||
| 45 | } | ||
| 46 | |||
| 47 | my $introspector = $storage_ref->{introspector}; | ||
| 48 | $introspector->_set_dbh($dbh); | ||
| 49 | return $introspector; | ||
| 50 | } | ||
| 51 | |||
| 52 | |||
| 53 | sub deserialize_from_file { | ||
| 54 | my $class = shift; | ||
| 55 | my $filename = shift; | ||
| 56 | my $dbh = shift; | ||
| 57 | |||
| 58 | my $fh = new IO::File($filename) || die($!); | ||
| 59 | my $introspector = $class->deserialize($fh, $dbh); | ||
| 60 | $fh->close; | ||
| 61 | return $introspector; | ||
| 62 | } | ||
| 63 | |||
| 64 | sub _dbh_id { | ||
| 65 | my $dbh = shift; | ||
| 66 | return join(',', $dbh->{Name}, $dbh->{Username}); | ||
| 67 | } | ||
| 68 | |||
| 69 | 1; |