7531954ad9c27ba784563caeeeb37bb667b3773f
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSourceHandle.pm
1 package DBIx::Class::ResultSourceHandle;
2
3 use strict;
4 use warnings;
5 use Storable;
6 use Carp;
7
8 use base qw/DBIx::Class/;
9
10 use overload
11     # on some RH perls the following line causes serious performance problem
12     # see https://bugzilla.redhat.com/show_bug.cgi?id=196836
13     q/""/ => sub { __PACKAGE__ . ":" . shift->source_moniker; },
14     fallback => 1;
15
16 __PACKAGE__->mk_group_accessors('simple' => qw/schema source_moniker/);
17
18 # Schema to use when thawing.
19 our $thaw_schema;
20
21 =head1 NAME
22
23 DBIx::Class::ResultSourceHandle - Decouple Rows/ResultSets objects from their Source objects
24
25 =head1 DESCRIPTION
26
27 This module removes fixed link between Rows/ResultSets and the actual source
28 objects, which gets round the following problems
29
30 =over 4
31
32 =item *
33
34 Needing to keep C<$schema> in scope, since any objects/result_sets
35 will have a C<$schema> object through their source handle
36
37 =item *
38
39 Large output when using Data::Dump(er) since this class can be set to
40 stringify to almost nothing
41
42 =item *
43
44 Closer to being able to do a Serialize::Storable that doesn't require class-based connections
45
46 =back
47
48 =head1 METHODS
49
50 =head2 new
51
52 =cut
53
54 sub new {
55     my ($class, $data) = @_;
56
57     $class = ref $class if ref $class;
58
59     bless $data, $class;
60 }
61
62 =head2 resolve
63
64 Resolve the moniker into the actual ResultSource object
65
66 =cut
67
68 sub resolve { return $_[0]->schema->source($_[0]->source_moniker) }
69
70 =head2 STORABLE_freeze
71
72 Freezes a handle.
73
74 =cut
75
76 sub STORABLE_freeze {
77     my ($self, $cloning) = @_;
78
79     my $to_serialize = { %$self };
80     
81     my $class = $self->schema->class($self->source_moniker);
82     $to_serialize->{schema} = $class;
83     return (Storable::freeze($to_serialize));
84 }
85
86 =head2 STORABLE_thaw
87
88 Thaws frozen handle. Resets the internal schema reference to the package
89 variable C<$thaw_schema>. The recomened way of setting this is to use 
90 C<< $schema->thaw($ice) >> which handles this for you.
91
92 =cut
93
94
95 sub STORABLE_thaw {
96     my ($self, $cloning,$ice) = @_;
97     %$self = %{ Storable::thaw($ice) };
98
99     my $class = delete $self->{schema};
100     if( $thaw_schema ) {
101         $self->{schema} = $thaw_schema;
102     }
103     else {
104         my $rs = $class->result_source_instance;
105         $self->{schema} = $rs->schema if $rs;
106     }
107
108     carp "Unable to restore schema" unless $self->{schema};
109 }
110
111 =head1 AUTHOR
112
113 Ash Berlin C<< <ash@cpan.org> >>
114
115 =cut
116
117 1;