DBAdaptor.pm 12.7 KB
Newer Older
1
=pod
2
3
4

=head1 NAME

5
    Bio::EnsEMBL::Hive::DBSQL::DBAdaptor
6
7
8

=head1 SYNOPSIS

9
    my $db = Bio::EnsEMBL::Hive::DBSQL::DBAdaptor->new( -url => 'mysql://my_username:my_password@my_hostname:3306/my_hive_database' );
10
11

=head1 DESCRIPTION
12

13
14
15
16
    This object represents the handle for a Hive system enabled database

=head1 LICENSE

17
    Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
18
19
20
21
22
23
24
25
26

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License
    is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and limitations under the License.
27
28
29

=head1 CONTACT

30
    Please subscribe to the Hive mailing list:  http://listserver.ebi.ac.uk/mailman/listinfo/ehive-users  to discuss Hive-related questions or to be notified of our updates
31
32
33
34
35
36
37

=cut


package Bio::EnsEMBL::Hive::DBSQL::DBAdaptor;

use strict;
38
use warnings;
39

40
use Bio::EnsEMBL::Hive;
41
use Bio::EnsEMBL::Hive::DBSQL::DBConnection;
42
use Bio::EnsEMBL::Hive::DBSQL::SqlSchemaAdaptor;
43
44
use Bio::EnsEMBL::Hive::Utils ('throw');
use Bio::EnsEMBL::Hive::Utils::Collection;
45

46
47
48
49
use Bio::EnsEMBL::Hive::MetaParameters;
use Bio::EnsEMBL::Hive::PipelineWideParameters;
use Bio::EnsEMBL::Hive::ResourceClass;
use Bio::EnsEMBL::Hive::ResourceDescription;
50
use Bio::EnsEMBL::Hive::Analysis;
51
52
53
use Bio::EnsEMBL::Hive::AnalysisStats;
use Bio::EnsEMBL::Hive::AnalysisCtrlRule;
use Bio::EnsEMBL::Hive::DataflowRule;
54

55

56
sub new {
57
58
    my $class = shift @_;
    my %flags = @_;
59

60
61
    my ($dbc, $url, $reg_conf, $reg_type, $reg_alias, $species, $no_sql_schema_version_check)
        = @flags{qw(-dbconn -url -reg_conf -reg_type -reg_alias -species -no_sql_schema_version_check)};
62

63
    $url .= ';no_sql_schema_version_check=1' if($url && $no_sql_schema_version_check);
64

65
66
67
68
69
    if($reg_conf or $reg_alias) {   # need to initialize Registry even if $reg_conf is not really given
        require Bio::EnsEMBL::Registry;
        Bio::EnsEMBL::Registry->load_all($reg_conf);    # if undefined, default reg_conf will be used
    }

70
71
72
    my $self;

    if($url) {
73

74
        $dbc = Bio::EnsEMBL::Hive::DBSQL::DBConnection->new(-url => $url)
75
76
            or die "Unable to create a DBC using url='$url'";

77
    } elsif($reg_alias) {
78

79
80
81
        if($reg_alias=~/^(\w+):(\w+)$/) {
            ($reg_type, $reg_alias) = ($1, $2);
        }
82

83
84
        unless($reg_type) {     # if no $reg_type explicitly given, try to guess:
            my $dbas = Bio::EnsEMBL::Registry->get_all_DBAdaptors(-species => $reg_alias);
85

86
87
88
89
90
91
92
93
94
95
96
97
98
99
            if( scalar(@$dbas) == 1 ) {
                $self = $dbas->[0];
            } elsif( @$dbas ) {
                warn "The registry contains multiple entries for '$reg_alias', please prepend the reg_alias with the desired type";
            }
        }

        unless($self) {         # otherwise (or if not found) try a specific $reg_type
            $reg_type ||= 'hive';
            $self = Bio::EnsEMBL::Registry->get_DBAdaptor($reg_alias, $reg_type)
                or die "Unable to connect to DBA using reg_conf='$reg_conf', reg_type='$reg_type', reg_alias='$reg_alias'\n";
        }

        if( $self and !$self->isa($class) ) {   # if we found a non-Hive Registry entry, detach the $dbc and build a Hive dba around it:
100
            $dbc = $self->dbc;
101
            $self = undef;
102
        }
103
104
    }

105
    if($dbc && !$self) {
106
        $self = bless {}, $class;
107
        $self->dbc( $dbc );
108
    }
109
110

    unless($no_sql_schema_version_check) {
111
112

        my $dbc = $self->dbc();
113
        my $safe_url = $dbc->url('EHIVE_PASS');
114
115

        my $code_sql_schema_version = Bio::EnsEMBL::Hive::DBSQL::SqlSchemaAdaptor->get_code_sql_schema_version()
116
            || die "DB($safe_url) Could not establish code_sql_schema_version, please check that 'EHIVE_ROOT_DIR' environment variable is set correctly";
117

118
        my $db_sql_schema_version   = eval { $self->get_MetaAdaptor->get_value_by_key( 'hive_sql_schema_version' ); };
119
        if($@) {
120
            if($@ =~ /hive_meta.*doesn't exist/) {
121

122
                die "\nDB($safe_url) The 'hive_meta' table does not seem to exist in the database yet.\nPlease patch the database up to sql_schema_version '$code_sql_schema_version' and try again.\n";
123
124
125

            } else {

126
                die "DB($safe_url) $@";
127
            }
128
129
130

        } elsif(!$db_sql_schema_version) {

131
            die "\nDB($safe_url) The 'hive_meta' table does not contain 'hive_sql_schema_version' entry.\nPlease investigate.\n";
132
133
134

        } elsif($db_sql_schema_version < $code_sql_schema_version) {

135
            my $new_patches = Bio::EnsEMBL::Hive::DBSQL::SqlSchemaAdaptor->get_sql_schema_patches( $db_sql_schema_version, $dbc->driver )
136
                || die "DB($safe_url) sql_schema_version mismatch: the database's version is '$db_sql_schema_version' but the code is already '$code_sql_schema_version'.\n"
137
138
                      ."Unfortunately we cannot patch the database; you may have to create a new database or agree to run older code\n";

139
            my $sql_patcher_command = "$ENV{'EHIVE_ROOT_DIR'}/scripts/db_cmd.pl -url $safe_url";
140

141
            die "DB($safe_url) sql_schema_version mismatch: the database's version is '$db_sql_schema_version' but the code is already '$code_sql_schema_version'.\n"
142
143
144
               ."Please upgrade the database by applying the following patches:\n\n"
               .join("\n", map { ($_=~/\.\w*sql\w*$/) ? "\t$sql_patcher_command < $_" : "$_ -url $safe_url" } @$new_patches)
               ."\n\nand try again.\n";
145
146
147

        } elsif($code_sql_schema_version < $db_sql_schema_version) {

148
            die "DB($safe_url) sql_schema_version mismatch: the database's version is '$db_sql_schema_version', but your code is still '$code_sql_schema_version'.\n"
149
               ."Please update the code and try again.\n";
150
        }
151
    }
152

153
154
155
156
157
    if($species) {      # [compatibility with core code] store the DBAdaptor in Registry:
        require Bio::EnsEMBL::Registry;
        Bio::EnsEMBL::Registry->add_DBAdaptor( $species, 'hive', $self );
    }

158
    return $self;
159
160
161
}


162
163
164
165
166
sub species {   # a stub to please Registry code
    return @_;
}


167
sub dbc {
168
    my $self = shift;
169

170
    $self->{'_dbc'} = bless shift, 'Bio::EnsEMBL::Hive::DBSQL::DBConnection' if(@_);
171

172
    return $self->{'_dbc'};
173
174
175
}


176
177
178
179
sub hive_use_triggers {  # getter only, not setter
    my $self = shift @_;

    unless( defined($self->{'_hive_use_triggers'}) ) {
180
        my $hive_use_triggers = $self->get_MetaAdaptor->get_value_by_key( 'hive_use_triggers' );
181
        $self->{'_hive_use_triggers'} = $hive_use_triggers // 0;
182
183
184
185
186
    } 
    return $self->{'_hive_use_triggers'};
}


187
188
189
190
sub hive_use_param_stack {  # getter only, not setter
    my $self = shift @_;

    unless( defined($self->{'_hive_use_param_stack'}) ) {
191
        my $hive_use_param_stack = $self->get_MetaAdaptor->get_value_by_key( 'hive_use_param_stack' );
192
        $self->{'_hive_use_param_stack'} = $hive_use_param_stack // 0;
193
194
195
196
197
    } 
    return $self->{'_hive_use_param_stack'};
}


198
199
200
201
202
203
204
205
206
207
208
sub hive_auto_rebalance_semaphores {  # getter only, not setter
    my $self = shift @_;

    unless( defined($self->{'_hive_auto_rebalance_semaphores'}) ) {
        my $hive_auto_rebalance_semaphores = $self->get_MetaAdaptor->get_value_by_key( 'hive_auto_rebalance_semaphores' );
        $self->{'_hive_auto_rebalance_semaphores'} = $hive_auto_rebalance_semaphores // 0;
    } 
    return $self->{'_hive_auto_rebalance_semaphores'};
}


209
210
211
212
213
214
215
216
217
218
our %adaptor_type_2_package_name = (
    'Accumulator'           => 'Bio::EnsEMBL::Hive::DBSQL::AccumulatorAdaptor',
    'Analysis'              => 'Bio::EnsEMBL::Hive::DBSQL::AnalysisAdaptor',
    'AnalysisCtrlRule'      => 'Bio::EnsEMBL::Hive::DBSQL::AnalysisCtrlRuleAdaptor',
    'AnalysisData'          => 'Bio::EnsEMBL::Hive::DBSQL::AnalysisDataAdaptor',
    'AnalysisJob'           => 'Bio::EnsEMBL::Hive::DBSQL::AnalysisJobAdaptor',
    'AnalysisStats'         => 'Bio::EnsEMBL::Hive::DBSQL::AnalysisStatsAdaptor',
    'DataflowRule'          => 'Bio::EnsEMBL::Hive::DBSQL::DataflowRuleAdaptor',
    'LogMessage'            => 'Bio::EnsEMBL::Hive::DBSQL::LogMessageAdaptor',
    'Meta'                  => 'Bio::EnsEMBL::Hive::DBSQL::MetaAdaptor',
219
    'PipelineWideParameters'=> 'Bio::EnsEMBL::Hive::DBSQL::PipelineWideParametersAdaptor',
220
221
222
    'NakedTable'            => 'Bio::EnsEMBL::Hive::DBSQL::NakedTableAdaptor',
    'ResourceClass'         => 'Bio::EnsEMBL::Hive::DBSQL::ResourceClassAdaptor',
    'ResourceDescription'   => 'Bio::EnsEMBL::Hive::DBSQL::ResourceDescriptionAdaptor',
223
    'Role'                  => 'Bio::EnsEMBL::Hive::DBSQL::RoleAdaptor',
224
225
226
227
228
    'Queen'                 => 'Bio::EnsEMBL::Hive::Queen',

        # aliases:
    'Job'                   => 'Bio::EnsEMBL::Hive::DBSQL::AnalysisJobAdaptor',
    'Worker'                => 'Bio::EnsEMBL::Hive::Queen',
229
    'MetaParameters'        => 'Bio::EnsEMBL::Hive::DBSQL::MetaAdaptor',
230
231
232
);


Leo Gordon's avatar
Leo Gordon committed
233
sub get_available_adaptors {
234
235

    return \%adaptor_type_2_package_name;
236
}
237

238

239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
sub parse_underscored_id_name {
    my ($self, $underscored_id_name) = @_;

    my ($is_an_id, $foo_id_method_name, $foo_obj_method_name);

    my @syll = split(/_/, $underscored_id_name);
    if($syll[scalar(@syll)-1] eq 'id') {
        pop @syll;
        ($is_an_id, $foo_id_method_name, $foo_obj_method_name) = ( 1, $underscored_id_name, join('_', @syll) );
    } else {
        ($is_an_id, $foo_id_method_name, $foo_obj_method_name) = ( 0, $underscored_id_name .'_id' , $underscored_id_name );
    }

    my $AdaptorType = '';   # will be growing from right to left
    while(@syll) {
        $AdaptorType = ucfirst(pop @syll) . $AdaptorType;
        if(exists( $self->get_available_adaptors->{ $AdaptorType })) {
            return ($AdaptorType, $is_an_id, $foo_id_method_name, $foo_obj_method_name);
        }
    }
    return;   # could not parse
}


263
264
sub get_adaptor {
    my $self = shift;
265
266
267
268
    my $AdaptorType = shift;

    my $adaptor_package_name = $self->get_available_adaptors()->{$AdaptorType}
        or throw("Could not find a module corresponding to '$AdaptorType'");
269

270
    my $signature = join(':', $adaptor_package_name, @_);
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294

    unless( $self->{'_cached_adaptor'}{$signature} ) {

        eval "require $adaptor_package_name"
        or throw("Could not load or compile module '$adaptor_package_name'");

        $self->{'_cached_adaptor'}{$signature} = $adaptor_package_name->new( $self, @_ );
    }

    return $self->{'_cached_adaptor'}{$signature};
}


sub DESTROY { }   # to simplify AUTOLOAD

sub AUTOLOAD {
    our $AUTOLOAD;

    my $type;
    if ( $AUTOLOAD =~ /^.*::get_(\w+)Adaptor$/ ) {
        $type = $1;
    } elsif ( $AUTOLOAD =~ /^.*::get_(\w+)$/ ) {
        $type = $1;
    } else {
295
        throw( "DBAdaptor::AUTOLOAD: Could not interpret the method: $AUTOLOAD" );
296
297
298
299
300
301
302
    }

    my $self = shift;

    return $self->get_adaptor($type, @_);
}

303

304
305
sub init_collections {  # should not really belong to DBAdaptor, temporarily squatting here...

306
    foreach my $AdaptorType ('MetaParameters', 'PipelineWideParameters', 'ResourceClass', 'ResourceDescription', 'Analysis', 'AnalysisStats', 'AnalysisCtrlRule', 'DataflowRule') {
307
308
309
310
311
312
        my $class = 'Bio::EnsEMBL::Hive::'.$AdaptorType;
        $class->collection( Bio::EnsEMBL::Hive::Utils::Collection->new() );
    }
}


313
314
315
sub load_collections {
    my $self = shift @_;

316
    foreach my $AdaptorType ('MetaParameters', 'PipelineWideParameters', 'ResourceClass', 'ResourceDescription', 'Analysis', 'AnalysisStats', 'AnalysisCtrlRule', 'DataflowRule') {
317
        my $adaptor = $self->get_adaptor( $AdaptorType );
318
319
        my $class = 'Bio::EnsEMBL::Hive::'.$AdaptorType;
        $class->collection( Bio::EnsEMBL::Hive::Utils::Collection->new( $adaptor->fetch_all ) );
320
321
322
323
324
325
326
    }
}


sub save_collections {
    my $self = shift @_;

327
    foreach my $AdaptorType ('MetaParameters', 'PipelineWideParameters', 'ResourceClass', 'ResourceDescription', 'Analysis', 'AnalysisStats', 'AnalysisCtrlRule', 'DataflowRule') {
328
        my $adaptor = $self->get_adaptor( $AdaptorType );
329
330
        my $class = 'Bio::EnsEMBL::Hive::'.$AdaptorType;
        foreach my $storable_object ( $class->collection()->list ) {
331
            $adaptor->store_or_update_one( $storable_object, $class->unikey() );
332
333
334
335
336
#            warn "Stored/updated ".$storable_object->toString()."\n";
        }
    }

    my $job_adaptor = $self->get_AnalysisJobAdaptor;
337
    foreach my $analysis ( Bio::EnsEMBL::Hive::Analysis->collection()->list ) {
338
339
340
341
342
343
344
345
346
        if(my $our_jobs = $analysis->jobs_collection ) {
            $job_adaptor->store( $our_jobs );
            foreach my $job (@$our_jobs) {
#                warn "Stored ".$job->toString()."\n";
            }
        }
    }
}

347
1;
348