DataFileAdaptor.pm 11.5 KB
Newer Older
1
=head1 LICENSE
2

3
Copyright [1999-2013] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
4

5 6 7 8 9
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
10

11 12 13 14 15
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.
16

17 18 19 20 21
=cut

package Bio::EnsEMBL::DBSQL::DataFileAdaptor;

=pod
22 23 24 25 26


=head1 CONTACT

  Please email comments or questions to the public Ensembl
Magali Ruffier's avatar
Magali Ruffier committed
27
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
28 29

  Questions may also be sent to the Ensembl help desk at
Magali Ruffier's avatar
Magali Ruffier committed
30
  <http://www.ensembl.org/Help/Contact>.
31 32 33 34 35 36 37 38 39 40

=head1 NAME

Bio::EnsEMBL::DBSQL::DataFileAdaptor

=head1 SYNOPSIS

	my $dfa = $dba->get_DataFileAdaptor();
	my $file = $dfa->fetch_by_dbID(1);
	my $files = $dfa->fetch_all();
41 42
	
	my $logic_name_files = $dfa->fetch_all_by_logic_name('bam_alignments');
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

=head1 DESCRIPTION

Provides a database wrapper to store the locations of files and to pull these
records back out. DataFile objects can only provide basic information but they
can return an intended external database adaptor which can be used to 
parse the information. This system assumes nothing about the file just that
your parser can access it.

Files are supported over any protocol your parser supports and locations can be
made absolute, built on the fly or versioned.

=head1 METHODS

=cut

use strict;
use warnings;

use base qw/Bio::EnsEMBL::DBSQL::BaseAdaptor/;

use Bio::EnsEMBL::DataFile;
use Bio::EnsEMBL::DBSQL::BaseAdaptor;
66
use Bio::EnsEMBL::Utils::Exception qw/throw warning deprecate/;
67 68
use Bio::EnsEMBL::Utils::Scalar qw/:assert/;

69 70 71 72 73
my $GLOBAL_BASE_PATH;

=head2 global_base_path

  Arg[1]     	: String; base path 
Kieron Taylor's avatar
Kieron Taylor committed
74
  Example       : Bio::EnsEMBL::DBSQL::DataFileAdaptor->global_base_path('/base/path');
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
  Description	: Stores a global value to be used when building data file paths
  Returntype 	: String
  Exceptions 	: None

=cut

sub global_base_path {
  my ($class, $base_path) = @_;
  return $GLOBAL_BASE_PATH unless $base_path;
  $GLOBAL_BASE_PATH = $base_path;
  return $GLOBAL_BASE_PATH;
}

=head2 get_base_path

  Arg[1]      : String; (optional) base path 
  Example     : $dfa->get_base_path();
  Description : If given the path it will return that path; if not it consults
                $self->global_base_path() for a value. As a last resort
                it will look at the meta table for an entry keyed by
                B<data_file.base_path>
  Returntype  : String
  Exceptions  : Thrown if nothing is found after consulting all three locations

=cut

sub get_base_path {
  my ($self, $path) = @_;
  return $path if defined $path;
  my $global_base_path = $self->global_base_path();
  return $global_base_path if defined $global_base_path;
  my $meta_base_path = $self->db()->get_MetaContainer()->single_value_by_key('data_file.base_path', 1);
  return $meta_base_path if defined $meta_base_path;
  throw "No base path discovered. Either provide a path, set a global using global_base_path() or specify 'data_file.base_path' in meta";
}

111 112
=head2 DataFile_to_extension

Kieron Taylor's avatar
Kieron Taylor committed
113
  Deprecated
114 115 116 117 118 119 120 121 122
  Arg[1]      : Bio::EnsEMBL::DataFile
  Example     : my $ext = $dfa->DataFile_to_extension($bam_df);
  Description : Returns an expected extension for the given DataFile type
  Returntype  : Scalar of the expected file extension
  Exceptions  : Raised if the given file type is not understood

=cut

sub DataFile_to_extension {
123 124 125 126 127 128
  my ($self, $df) = @_;
  deprecate("Use DataFile_to_extensions() instead");
  my $extensions = $self->DataFile_to_extensions($df);
  return $extensions->[0];
}

Andy Yates's avatar
Andy Yates committed
129
=head2 DataFile_to_extensions
130

Andy Yates's avatar
Andy Yates committed
131 132 133 134 135 136
  Arg[1]      : Bio::EnsEMBL::DataFile
  Example     : my $exts = $dfa->DataFile_to_extensions($bam_df);
  Description : Returns all expected extensions for the given DataFile type. The
                first returned is the default extension
  Returntype  : ArrayRef
  Exceptions  : Raised if the given file type is not understood
137 138 139 140

=cut

sub DataFile_to_extensions {
141 142
  my ($self, $df) = @_;
  my $type = $df->file_type();
143 144
  my $extensions = {
    BAM     => ['bam', 'bam.bai'],
145
#    BIGBED  => 'bb',
146 147
    BIGWIG  => ['bw'],
    VCF     => ['vcf.gz', 'vcf.gz.tbi'],
148
  }->{$type}; 
149 150
  throw sprintf(q{No extensions found for the type '%s'}, $type ) if ! $extensions;
  return $extensions;
151 152
}

153

154 155
=head2 DataFile_to_adaptor

Kieron Taylor's avatar
Kieron Taylor committed
156 157 158 159 160 161
  Arg[1]        : Bio::EnsEMBL::DataFile
  Arg[2]        : (optional) base path
  Example       : my $bam = $dfa->DataFile_to_adaptor($bam_df);
  Description   : Returns an adaptor instance which will access the given DataFile
  Returntype    : Scalar actual return depends upon the given file type
  Exceptions    : Raised if the given file type is not understood
162 163 164 165 166 167 168 169

=cut

sub DataFile_to_adaptor {
  my ($self, $df, $base) = @_;
  my $type = $df->file_type();
  my $dispatch = {
    BAM     => sub {
170 171
      require Bio::EnsEMBL::ExternalData::BAM::BAMAdaptor;
      return Bio::EnsEMBL::ExternalData::BAM::BAMAdaptor->new($df->path($base));
172
    },
173 174 175 176
    BIGBED  => sub {
      require Bio::EnsEMBL::ExternalData::BigFile::BigBedAdaptor;
      return Bio::EnsEMBL::ExternalData::BigFile::BigBedAdaptor->new($df->path($base));
    },
177 178 179 180 181 182 183 184 185 186 187 188 189
    BIGWIG  => sub {
      require Bio::EnsEMBL::ExternalData::BigFile::BigWigAdaptor;
      return Bio::EnsEMBL::ExternalData::BigFile::BigWigAdaptor->new($df->path($base));
    },
    VCF     => sub {
      require Bio::EnsEMBL::ExternalData::VCF::VCFAdaptor;
      return Bio::EnsEMBL::ExternalData::VCF::VCFAdaptor->new($df->path($base));
    },
  }->{$type}; 
  throw sprintf(q{No handler found for the type '%s'}, $type ) if ! $dispatch;
  return $dispatch->();
}

190 191 192
=head2 fetch_all_by_logic_name

  Args [1]   	: String $logic_name for the linked analysis 
Kieron Taylor's avatar
Kieron Taylor committed
193
  Example       : my $dfs = $dfa->fetch_all_by_logic_name('bam_alignments');
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
  Description	: Returns all DataFile entries linked to the given analysis 
                logic name
  Returntype 	: ArrayRef contains Bio::EnsEMBL::DataFile instances
  Exceptions 	: Thrown if logic name does not exist 

=cut

sub fetch_all_by_logic_name {
  my ($self, $logic_name) = @_;
  my $analysis = $self->db()->get_AnalysisAdaptor()->fetch_by_logic_name($logic_name);
  throw "No analysis found for logic_name '${logic_name}'" if ! $analysis;
  return $self->fetch_all_by_Analysis($analysis);
}

=head2 fetch_all_by_Analysis

  Args [1]    : Bio::EnsEMBL::Analysis $analysis to look up by 
  Example     : my $dfs = $dfa->fetch_all_by_Analysis($analysis);
  Description : Returns all DataFile entries linked to the given analysis
  Returntype  : ArrayRef contains Bio::EnsEMBL::DataFile instances
  Exceptions  : None

=cut
217 218 219 220 221 222 223 224

sub fetch_all_by_Analysis {
  my ($self, $analysis) = @_;
  assert_ref($analysis, 'Bio::EnsEMBL::Analysis', 'analysis');
  $self->bind_param_generic_fetch($analysis->dbID(), SQL_INTEGER);
  return $self->generic_fetch('df.analysis_id =?');
}

225 226 227 228 229 230 231 232 233 234 235
=head2 fetch_all_by_CoordSystem

  Args [1]    : Bio::EnsEMBL::CoordSystem $coord_system to look up by 
  Example     : my $dfs = $dfa->fetch_all_by_CoordSystem($cs);
  Description : Returns all DataFile entries linked to the given coordinate
                system. Does B<not> support I<toplevel>
  Returntype  : ArrayRef contains Bio::EnsEMBL::DataFile instances
  Exceptions  : None 

=cut

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 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
sub fetch_all_by_CoordSystem {
  my ($self, $cs) = @_;
  assert_ref($cs, 'Bio::EnsEMBL::CoordSystem', 'coord_system');
  $self->bind_param_generic_fetch($cs->dbID(), SQL_INTEGER);
  return $self->generic_fetch('df.coord_system_id =?');
}

sub fetch_by_name_and_type {
  my ($self, $name, $type) = @_;
  $self->bind_param_generic_fetch($name, SQL_VARCHAR);
  $self->bind_param_generic_fetch($type, SQL_VARCHAR);
  my $results = $self->generic_fetch('df.name =? and df.file_type =?');
  return $results->[0] if @{$results};
  return;
}

sub generic_fetch {
  my ($self, $constraint) = @_;
  $constraint ||= q{};
  
  my $sql = <<'SQL';
select df.data_file_id, df.coord_system_id, df.analysis_id, df.name, df.version_lock, df.absolute, df.url, df.file_type
from data_file df
join coord_system cs using (coord_system_id) 
where cs.species_id =?
SQL
  $sql .= 'AND '.$constraint if $constraint;
  
  my $params = $self->bind_param_generic_fetch();
  if(defined $params) {
    $self->{'_bind_param_generic_fetch'} = ();
  }
  else {
    $params = [];
  }
  unshift(@{$params}, $self->db()->species_id());
  
  my $csa = $self->db()->get_CoordSystemAdaptor();
  my $aa = $self->db()->get_AnalysisAdaptor();
  
  return $self->dbc()->sql_helper()->execute(-SQL => $sql, -PARAMS => $params, -CALLBACK => sub {
    my ($row) = @_;
    my ($data_file_id, $coord_system_id, $analysis_id, $name, $version_lock, $absolute, $url, $file_type) = @{$row};
    my $hash = {
      dbID          => $data_file_id,
      adaptor       => $self,
      coord_system  => $csa->fetch_by_dbID($coord_system_id),
      analysis      => $aa->fetch_by_dbID($analysis_id),
      name          => $name,
      version_lock  => $version_lock,
      absolute      => $absolute,
      file_type     => $file_type,
    };
    $hash->{url} = $url if $url;
    return Bio::EnsEMBL::DataFile->new_fast($hash);
  });
}

sub store {
  my ($self, $df) = @_;
  
  assert_ref($df, 'Bio::EnsEMBL::DataFile', 'datafile');
  
  if ($df->is_stored($self->db())) {
    return $df->dbID();
  }
  
  throw 'Analysis is not defined for this data file' if ! defined $df->analysis();
  throw 'Coord system is not defined for this data file' if ! defined $df->coord_system();
  
  my $sql = <<'SQL';
INSERT INTO data_file (coord_system_id, analysis_id, name, version_lock, absolute, url, file_type)
VALUES (?,?,?,?,?,?,?)
SQL
  my $params = [
    [$df->coord_system()->dbID(), SQL_INTEGER], 
    [$df->analysis()->dbID(), SQL_INTEGER],
    [$df->name(), SQL_VARCHAR],
    [$df->version_lock(), SQL_INTEGER],
    [$df->absolute(), SQL_INTEGER],
    [$df->url(), SQL_VARCHAR],
    [$df->file_type(), SQL_VARCHAR],
  ];
  $self->dbc()->sql_helper()->execute_update(-SQL => $sql, -PARAMS => $params, -CALLBACK => sub {
    my ( $sth, $dbh ) = @_;
    $df->dbID($self->last_insert_id());
    return;
  });
  $df->adaptor($self);
  
  return $df->dbID();
}

sub update {
  my ($self, $df) = @_;
  
  assert_ref($df, 'Bio::EnsEMBL::DataFile', 'datafile');
  
  if (! $df->is_stored($self->db())) {
    $self->store($df);
    return;
  }
  
  my $sql = <<'SQL';
UPDATE data_file SET coord_system_id =?, analysis_id=?, name=?, version_lock=?, absolute=?, url=?, file_type=?
WHERE data_file_id =?
SQL
  my $params = [
    [$df->coord_system()->dbID(), SQL_INTEGER], 
    [$df->analysis()->dbID(), SQL_INTEGER],
    [$df->name(), SQL_VARCHAR],
    [$df->version_lock(), SQL_INTEGER],
    [$df->absolute(), SQL_INTEGER],
    [$df->url(), SQL_VARCHAR],
    [$df->file_type(), SQL_VARCHAR],
    [$df->dbID(), SQL_INTEGER],
  ];
  $self->dbc()->sql_helper()->execute_update(-SQL => $sql, -PARAMS => $params);
  return;
}

sub delete {
  my ($self, $df) = @_;
  
  assert_ref($df, 'Bio::EnsEMBL::DataFile', 'datafile');
  
  if (! $df->is_stored($self->db())) {
    throw "Cannot delete the data file if it has not already been stored in this database";
  }
  
  $self->dbc()->sql_helper()->execute_update(
    -SQL => 'DELETE from data_file where data_file_id =?', 
    -PARAMS => [[$df->dbID(), SQL_INTEGER]],
  );
  
  return;
}

sub _tables {
  my ($self) = @_;
  return (
    [qw/data_file df/]
  );
}

Andy Yates's avatar
Andy Yates committed
381
1;