| 1 | |||
| 2 | package Bio::DB::SeqFeature::Store::DBI::Pg; | ||
| 3 | $Bio::DB::SeqFeature::Store::DBI::Pg::VERSION = '1.7.3'; | ||
| 4 | 1 | ▶ | use DBD::Pg qw(:pg_types); |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 5 | use MIME::Base64; | ||
| 6 | # $Id: Pg.pm 14656 2008-04-14 15:05:37Z lstein $ | ||
| 7 | |||
| 8 | =head1 NAME | ||
| 9 | |||
| 10 | Bio::DB::SeqFeature::Store::DBI::Pg -- PostgreSQL implementation of Bio::DB::SeqFeature::Store | ||
| 11 | |||
| 12 | =head1 SYNOPSIS | ||
| 13 | |||
| 14 | use Bio::DB::SeqFeature::Store; | ||
| 15 | |||
| 16 | # Open the sequence database | ||
| 17 | my $db = Bio::DB::SeqFeature::Store->new(-adaptor => 'DBI::Pg', | ||
| 18 | -dsn => 'dbi:Pg:test'); | ||
| 19 | |||
| 20 | # get a feature from somewhere | ||
| 21 | my $feature = Bio::SeqFeature::Generic->new(...); | ||
| 22 | |||
| 23 | # store it | ||
| 24 | $db->store($feature) or die "Couldn't store!"; | ||
| 25 | |||
| 26 | # primary ID of the feature is changed to indicate its primary ID | ||
| 27 | # in the database... | ||
| 28 | my $id = $feature->primary_id; | ||
| 29 | |||
| 30 | # get the feature back out | ||
| 31 | my $f = $db->fetch($id); | ||
| 32 | |||
| 33 | # change the feature and update it | ||
| 34 | $f->start(100); | ||
| 35 | $db->update($f) or die "Couldn't update!"; | ||
| 36 | |||
| 37 | # searching... | ||
| 38 | # ...by id | ||
| 39 | my @features = $db->fetch_many(@list_of_ids); | ||
| 40 | |||
| 41 | # ...by name | ||
| 42 | @features = $db->get_features_by_name('ZK909'); | ||
| 43 | |||
| 44 | # ...by alias | ||
| 45 | @features = $db->get_features_by_alias('sma-3'); | ||
| 46 | |||
| 47 | # ...by type | ||
| 48 | @features = $db->get_features_by_name('gene'); | ||
| 49 | |||
| 50 | # ...by location | ||
| 51 | @features = $db->get_features_by_location(-seq_id=>'Chr1',-start=>4000,-end=>600000); | ||
| 52 | |||
| 53 | # ...by attribute | ||
| 54 | @features = $db->get_features_by_attribute({description => 'protein kinase'}) | ||
| 55 | |||
| 56 | # ...by the GFF "Note" field | ||
| 57 | @result_list = $db->search_notes('kinase'); | ||
| 58 | |||
| 59 | # ...by arbitrary combinations of selectors | ||
| 60 | @features = $db->features(-name => $name, | ||
| 61 | -type => $types, | ||
| 62 | -seq_id => $seqid, | ||
| 63 | -start => $start, | ||
| 64 | -end => $end, | ||
| 65 | -attributes => $attributes); | ||
| 66 | |||
| 67 | # ...using an iterator | ||
| 68 | my $iterator = $db->get_seq_stream(-name => $name, | ||
| 69 | -type => $types, | ||
| 70 | -seq_id => $seqid, | ||
| 71 | -start => $start, | ||
| 72 | -end => $end, | ||
| 73 | -attributes => $attributes); | ||
| 74 | |||
| 75 | while (my $feature = $iterator->next_seq) { | ||
| 76 | # do something with the feature | ||
| 77 | } | ||
| 78 | |||
| 79 | # ...limiting the search to a particular region | ||
| 80 | my $segment = $db->segment('Chr1',5000=>6000); | ||
| 81 | my @features = $segment->features(-type=>['mRNA','match']); | ||
| 82 | |||
| 83 | # getting & storing sequence information | ||
| 84 | # Warning: this returns a string, and not a PrimarySeq object | ||
| 85 | $db->insert_sequence('Chr1','GATCCCCCGGGATTCCAAAA...'); | ||
| 86 | my $sequence = $db->fetch_sequence('Chr1',5000=>6000); | ||
| 87 | |||
| 88 | # what feature types are defined in the database? | ||
| 89 | my @types = $db->types; | ||
| 90 | |||
| 91 | # create a new feature in the database | ||
| 92 | my $feature = $db->new_feature(-primary_tag => 'mRNA', | ||
| 93 | -seq_id => 'chr3', | ||
| 94 | -start => 10000, | ||
| 95 | -end => 11000); | ||
| 96 | |||
| 97 | =head1 DESCRIPTION | ||
| 98 | |||
| 99 | Bio::DB::SeqFeature::Store::Pg is the Pg adaptor for | ||
| 100 | Bio::DB::SeqFeature::Store. You will not create it directly, but | ||
| 101 | instead use Bio::DB::SeqFeature::Store-E<gt>new() to do so. | ||
| 102 | |||
| 103 | See L<Bio::DB::SeqFeature::Store> for complete usage instructions. | ||
| 104 | |||
| 105 | =head2 Using the Pg adaptor | ||
| 106 | |||
| 107 | Before you can use the adaptor, you must use the Pgadmin tool to | ||
| 108 | create a database and establish a user account with write | ||
| 109 | permission. In order to use "fast" loading, the user account must have | ||
| 110 | "file" privileges. | ||
| 111 | |||
| 112 | To establish a connection to the database, call | ||
| 113 | Bio::DB::SeqFeature::Store-E<gt>new(-adaptor=E<gt>'DBI::Pg',@more_args). The | ||
| 114 | additional arguments are as follows: | ||
| 115 | |||
| 116 | Argument name Description | ||
| 117 | ------------- ----------- | ||
| 118 | |||
| 119 | -dsn The database name. You can abbreviate | ||
| 120 | "dbi:Pg:foo" as "foo" if you wish. | ||
| 121 | |||
| 122 | -user Username for authentication. | ||
| 123 | |||
| 124 | -pass Password for authentication. | ||
| 125 | |||
| 126 | -namespace Creates a SCHEMA for the tables. This allows you | ||
| 127 | to have several virtual databases in the same | ||
| 128 | physical database. | ||
| 129 | |||
| 130 | -temp Boolean flag. If true, a temporary database | ||
| 131 | will be created and destroyed as soon as | ||
| 132 | the Store object goes out of scope. (synonym -temporary) | ||
| 133 | |||
| 134 | -autoindex Boolean flag. If true, features in the database will be | ||
| 135 | reindexed every time they change. This is the default. | ||
| 136 | |||
| 137 | |||
| 138 | -tmpdir Directory in which to place temporary files during "fast" loading. | ||
| 139 | Defaults to File::Spec->tmpdir(). (synonyms -dump_dir, -dumpdir, -tmp) | ||
| 140 | |||
| 141 | -dbi_options A hashref to pass to DBI->connect's 4th argument, the "attributes." | ||
| 142 | (synonyms -options, -dbi_attr) | ||
| 143 | |||
| 144 | -write Pass true to open database for writing or updating. | ||
| 145 | |||
| 146 | If successful, a new instance of | ||
| 147 | Bio::DB::SeqFeature::Store::DBI::Pg will be returned. | ||
| 148 | |||
| 149 | In addition to the standard methods supported by all well-behaved | ||
| 150 | Bio::DB::SeqFeature::Store databases, several following | ||
| 151 | adaptor-specific methods are provided. These are described in the next | ||
| 152 | sections. | ||
| 153 | |||
| 154 | =cut | ||
| 155 | |||
| 156 | use strict; | ||
| 157 | |||
| 158 | use base 'Bio::DB::SeqFeature::Store::DBI::mysql'; | ||
| 159 | use Bio::DB::SeqFeature::Store::DBI::Iterator; | ||
| 160 | use DBI; | ||
| 161 | use Memoize; | ||
| 162 | use Cwd 'abs_path'; | ||
| 163 | use Bio::DB::GFF::Util::Rearrange 'rearrange'; | ||
| 164 | use File::Copy; | ||
| 165 | use File::Spec; | ||
| 166 | use constant DEBUG=>0; | ||
| 167 | |||
| 168 | use constant MAX_INT => 2_147_483_647; | ||
| 169 | use constant MIN_INT => -2_147_483_648; | ||
| 170 | use constant MAX_BIN => 1_000_000_000; # size of largest feature = 1 Gb | ||
| 171 | use constant MIN_BIN => 1000; # smallest bin we'll make - on a 100 Mb chromosome, there'll be 100,000 of these | ||
| 172 | |||
| 173 | ### | ||
| 174 | # object initialization | ||
| 175 | # | ||
| 176 | # NOTE: most of this code can be refactored and inherited from DBI or DBI::mysql adapter | ||
| 177 | # | ||
| 178 | sub init { | ||
| 179 | my $self = shift; | ||
| 180 | my ($dsn, | ||
| 181 | $is_temporary, | ||
| 182 | $autoindex, | ||
| 183 | $namespace, | ||
| 184 | $dump_dir, | ||
| 185 | $user, | ||
| 186 | $pass, | ||
| 187 | $dbi_options, | ||
| 188 | $writeable, | ||
| 189 | $create, | ||
| 190 | $schema, | ||
| 191 | ) = rearrange(['DSN', | ||
| 192 | ['TEMP','TEMPORARY'], | ||
| 193 | 'AUTOINDEX', | ||
| 194 | 'NAMESPACE', | ||
| 195 | ['DUMP_DIR','DUMPDIR','TMP','TMPDIR'], | ||
| 196 | 'USER', | ||
| 197 | ['PASS','PASSWD','PASSWORD'], | ||
| 198 | ['OPTIONS','DBI_OPTIONS','DBI_ATTR'], | ||
| 199 | ['WRITE','WRITEABLE'], | ||
| 200 | 'CREATE', | ||
| 201 | 'SCHEMA' | ||
| 202 | ],@_); | ||
| 203 | |||
| 204 | |||
| 205 | $dbi_options ||= {pg_server_prepare => 0}; | ||
| 206 | $writeable = 1 if $is_temporary or $dump_dir; | ||
| 207 | |||
| 208 | $dsn or $self->throw("Usage: ".__PACKAGE__."->init(-dsn => \$dbh || \$dsn)"); | ||
| 209 | |||
| 210 | my $dbh; | ||
| 211 | if (ref $dsn) { | ||
| 212 | $dbh = $dsn; | ||
| 213 | } else { | ||
| 214 | $dsn = "dbi:Pg:$dsn" unless $dsn =~ /^dbi:/; | ||
| 215 | $dbh = DBI->connect($dsn,$user,$pass,$dbi_options) or $self->throw($DBI::errstr); | ||
| 216 | } | ||
| 217 | $dbh->do('set client_min_messages=warning') if $dbh; | ||
| 218 | $self->{'original_arguments'} = { | ||
| 219 | 'dsn' => $dsn, | ||
| 220 | 'user' => $user, | ||
| 221 | 'pass' => $pass, | ||
| 222 | 'dbh_options' => $dbi_options, | ||
| 223 | }; | ||
| 224 | $self->{dbh} = $dbh; | ||
| 225 | $self->{dbh}->{InactiveDestroy} = 1; | ||
| 226 | $self->{is_temp} = $is_temporary; | ||
| 227 | $self->{writeable} = $writeable; | ||
| 228 | $self->{namespace} = $namespace || $schema || 'public'; | ||
| 229 | $self->schema($self->{namespace}); | ||
| 230 | |||
| 231 | $self->default_settings; | ||
| 232 | $self->autoindex($autoindex) if defined $autoindex; | ||
| 233 | $self->dumpdir($dump_dir) if $dump_dir; | ||
| 234 | if ($self->is_temp) { | ||
| 235 | # warn "creating a temp database isn't supported"; | ||
| 236 | #$self->init_tmp_database(); | ||
| 237 | $self->init_database('erase'); | ||
| 238 | } elsif ($create) { | ||
| 239 | $self->init_database('erase'); | ||
| 240 | } | ||
| 241 | } | ||
| 242 | |||
| 243 | sub table_definitions { | ||
| 244 | my $self = shift; | ||
| 245 | return { | ||
| 246 | feature => <<END, | ||
| 247 | ( | ||
| 248 | id serial primary key, | ||
| 249 | typeid int not null, | ||
| 250 | seqid int, | ||
| 251 | start int, | ||
| 252 | "end" int, | ||
| 253 | strand int default 0, | ||
| 254 | tier int, | ||
| 255 | bin int, | ||
| 256 | indexed int default 1, | ||
| 257 | object bytea not null | ||
| 258 | ); | ||
| 259 | CREATE INDEX feature_stuff ON feature(seqid,tier,bin,typeid); | ||
| 260 | CREATE INDEX feature_typeid ON feature(typeid); | ||
| 261 | END | ||
| 262 | |||
| 263 | locationlist => <<END, | ||
| 264 | ( | ||
| 265 | id serial primary key, | ||
| 266 | seqname text not null | ||
| 267 | ); CREATE INDEX locationlist_seqname ON locationlist(seqname); | ||
| 268 | END | ||
| 269 | |||
| 270 | typelist => <<END, | ||
| 271 | ( | ||
| 272 | id serial primary key, | ||
| 273 | tag text not null | ||
| 274 | ); CREATE INDEX typelist_tab ON typelist(tag); | ||
| 275 | END | ||
| 276 | name => <<END, | ||
| 277 | ( | ||
| 278 | id int not null, | ||
| 279 | name text not null, | ||
| 280 | display_name int default 0 | ||
| 281 | ); | ||
| 282 | CREATE INDEX name_id ON name( id ); | ||
| 283 | CREATE INDEX name_name ON name( name ); | ||
| 284 | CREATE INDEX name_lcname ON name( lower(name) ); | ||
| 285 | CREATE INDEX name_lcname_varchar_patt_ops ON name USING BTREE (lower(name) varchar_pattern_ops); | ||
| 286 | END | ||
| 287 | |||
| 288 | attribute => <<END, | ||
| 289 | ( | ||
| 290 | id int not null, | ||
| 291 | attribute_id int not null, | ||
| 292 | attribute_value text | ||
| 293 | ); | ||
| 294 | CREATE INDEX attribute_id ON attribute(id); | ||
| 295 | CREATE INDEX attribute_id_val ON attribute(attribute_id,SUBSTR(attribute_value, 1, 10)); | ||
| 296 | END | ||
| 297 | |||
| 298 | attributelist => <<END, | ||
| 299 | ( | ||
| 300 | id serial primary key, | ||
| 301 | tag text not null | ||
| 302 | ); | ||
| 303 | CREATE INDEX attributelist_tag ON attributelist(tag); | ||
| 304 | END | ||
| 305 | parent2child => <<END, | ||
| 306 | ( | ||
| 307 | id int not null, | ||
| 308 | child int not null | ||
| 309 | ); | ||
| 310 | CREATE UNIQUE INDEX parent2child_id_child ON parent2child(id,child); | ||
| 311 | END | ||
| 312 | |||
| 313 | meta => <<END, | ||
| 314 | ( | ||
| 315 | name text primary key, | ||
| 316 | value text not null | ||
| 317 | ) | ||
| 318 | END | ||
| 319 | sequence => <<END, | ||
| 320 | ( | ||
| 321 | id int not null, | ||
| 322 | "offset" int not null, | ||
| 323 | sequence text, | ||
| 324 | primary key(id,"offset") | ||
| 325 | ) | ||
| 326 | END | ||
| 327 | |||
| 328 | interval_stats => <<END, | ||
| 329 | ( | ||
| 330 | typeid int not null, | ||
| 331 | seqid int not null, | ||
| 332 | bin int not null, | ||
| 333 | cum_count int not null | ||
| 334 | ); | ||
| 335 | CREATE UNIQUE INDEX interval_stats_id ON interval_stats(typeid,seqid,bin); | ||
| 336 | END | ||
| 337 | }; | ||
| 338 | } | ||
| 339 | |||
| 340 | sub schema { | ||
| 341 | my ($self, $schema) = @_; | ||
| 342 | $self->{'schema'} = $schema if defined($schema); | ||
| 343 | if ($schema) { | ||
| 344 | $self->_check_for_namespace(); | ||
| 345 | $self->dbh->do("SET search_path TO " . $self->{'schema'} ); | ||
| 346 | } else { | ||
| 347 | $self->dbh->do("SET search_path TO public"); | ||
| 348 | } | ||
| 349 | return $self->{'schema'}; | ||
| 350 | } | ||
| 351 | ### | ||
| 352 | # wipe database clean and reinstall schema | ||
| 353 | # | ||
| 354 | sub _init_database { | ||
| 355 | my $self = shift; | ||
| 356 | my $erase = shift; | ||
| 357 | |||
| 358 | my $dbh = $self->dbh; | ||
| 359 | my $namespace = $self->namespace; | ||
| 360 | my $tables = $self->table_definitions; | ||
| 361 | my $temporary = $self->is_temp ? 'TEMPORARY' : ''; | ||
| 362 | foreach (keys %$tables) { | ||
| 363 | next if $_ eq 'meta'; # don't get rid of meta data! | ||
| 364 | my $table = $self->_qualify($_); | ||
| 365 | $dbh->do("DROP TABLE IF EXISTS $table") if $erase; | ||
| 366 | my @table_exists = $dbh->selectrow_array("SELECT * FROM pg_tables WHERE tablename = '$table' AND schemaname = '$self->namespace'"); | ||
| 367 | if (!scalar(@table_exists)) { | ||
| 368 | my $query = "CREATE $temporary TABLE $table $tables->{$_}"; | ||
| 369 | $dbh->do($query) or $self->throw($dbh->errstr); | ||
| 370 | } | ||
| 371 | } | ||
| 372 | $self->subfeatures_are_indexed(1) if $erase; | ||
| 373 | 1; | ||
| 374 | } | ||
| 375 | |||
| 376 | sub maybe_create_meta { | ||
| 377 | my $self = shift; | ||
| 378 | return unless $self->writeable; | ||
| 379 | my $namespace = $self->namespace; | ||
| 380 | my $table = $self->_qualify('meta'); | ||
| 381 | my $tables = $self->table_definitions; | ||
| 382 | my $temporary = $self->is_temp ? 'TEMPORARY' : ''; | ||
| 383 | my @table_exists = $self->dbh->selectrow_array("SELECT * FROM pg_tables WHERE tablename = 'meta' AND schemaname = '$namespace'"); | ||
| 384 | $self->dbh->do("CREATE $temporary TABLE $table $tables->{meta}") | ||
| 385 | unless @table_exists; | ||
| 386 | } | ||
| 387 | |||
| 388 | ### | ||
| 389 | # check if the namespace/schema exists, if not create it | ||
| 390 | # | ||
| 391 | |||
| 392 | sub _check_for_namespace { | ||
| 393 | my $self = shift; | ||
| 394 | my $namespace = $self->namespace; | ||
| 395 | return if $namespace eq 'public'; | ||
| 396 | my $dbh = $self->dbh; | ||
| 397 | my @schema_exists = $dbh->selectrow_array("SELECT * FROM pg_namespace WHERE nspname = '$namespace'"); | ||
| 398 | if (!scalar(@schema_exists)) { | ||
| 399 | my $query = "CREATE SCHEMA $namespace"; | ||
| 400 | $dbh->do($query) or $self->throw($dbh->errstr); | ||
| 401 | |||
| 402 | # if temp parameter is set and schema created for this process then enable removal in remove_namespace() | ||
| 403 | if ($self->is_temp) { | ||
| 404 | $self->{delete_schema} = 1; | ||
| 405 | } | ||
| 406 | } | ||
| 407 | } | ||
| 408 | |||
| 409 | ### | ||
| 410 | # Overiding inherited mysql _qualify (We do not need to qualify for PostgreSQL as we have set the search_path above) | ||
| 411 | # | ||
| 412 | sub _qualify { | ||
| 413 | my $self = shift; | ||
| 414 | my $table_name = shift; | ||
| 415 | return $table_name; | ||
| 416 | } | ||
| 417 | |||
| 418 | ### | ||
| 419 | # when is_temp is set and the schema did not exist beforehand then we are able to remove it | ||
| 420 | # | ||
| 421 | sub remove_namespace { | ||
| 422 | my $self = shift; | ||
| 423 | if ($self->{delete_schema}) { | ||
| 424 | my $namespace = $self->namespace; | ||
| 425 | $self->dbh->do("DROP SCHEMA $namespace") or $self->throw($self->dbh->errstr); | ||
| 426 | } | ||
| 427 | } | ||
| 428 | |||
| 429 | ####Overiding the inherited mysql function _prepare | ||
| 430 | |||
| 431 | sub _prepare { | ||
| 432 | my $self = shift; | ||
| 433 | my $query = shift; | ||
| 434 | my $dbh = $self->dbh; | ||
| 435 | my $schema = $self->{namespace}; | ||
| 436 | |||
| 437 | if ($schema) { | ||
| 438 | $self->_check_for_namespace(); | ||
| 439 | $dbh->do("SET search_path TO " . $self->{'schema'} ); | ||
| 440 | } else { | ||
| 441 | $dbh->do("SET search_path TO public"); | ||
| 442 | } | ||
| 443 | my $sth = $dbh->prepare_cached($query, {}, 3) or | ||
| 444 | $self->throw($dbh->errstr); | ||
| 445 | $sth; | ||
| 446 | } | ||
| 447 | |||
| 448 | sub _finish_bulk_update { | ||
| 449 | my $self = shift; | ||
| 450 | my $dbh = $self->dbh; | ||
| 451 | my $dir = $self->{dumpdir} || '.'; | ||
| 452 | for my $table ('feature',$self->index_tables) { | ||
| 453 | my $fh = $self->dump_filehandle($table); | ||
| 454 | my $path = $self->dump_path($table); | ||
| 455 | $fh->close; | ||
| 456 | my $qualified_table = $self->_qualify($table); | ||
| 457 | copy($path, "$path.bak"); | ||
| 458 | # Get stuff from file into STDIN so we don't have to be superuser | ||
| 459 | open my $FH, '<', $path or $self->throw("Could not read file '$path': $!"); | ||
| 460 | print STDERR "Loading file $path\n"; | ||
| 461 | $dbh->do("COPY $qualified_table FROM STDIN CSV QUOTE '''' DELIMITER '\t'") or $self->throw($dbh->errstr); | ||
| 462 | while (my $line = <$FH>) { | ||
| 463 | $dbh->pg_putline($line); | ||
| 464 | } | ||
| 465 | $dbh->pg_endcopy() or $self->throw($dbh->errstr); | ||
| 466 | close $FH; | ||
| 467 | #unlink $path; | ||
| 468 | } | ||
| 469 | delete $self->{bulk_update_in_progress}; | ||
| 470 | delete $self->{filehandles}; | ||
| 471 | } | ||
| 472 | |||
| 473 | |||
| 474 | ### | ||
| 475 | # Add a subparts to a feature. Both feature and all subparts must already be in database. | ||
| 476 | # | ||
| 477 | sub _add_SeqFeature { | ||
| 478 | my $self = shift; | ||
| 479 | |||
| 480 | # special purpose method for case when we are doing a bulk update | ||
| 481 | return $self->_dump_add_SeqFeature(@_) if $self->{bulk_update_in_progress}; | ||
| 482 | |||
| 483 | my $parent = shift; | ||
| 484 | my @children = @_; | ||
| 485 | |||
| 486 | my $dbh = $self->dbh; | ||
| 487 | local $dbh->{RaiseError} = 1; | ||
| 488 | |||
| 489 | my $child_table = $self->_parent2child_table(); | ||
| 490 | my $count = 0; | ||
| 491 | |||
| 492 | my $querydel = "DELETE FROM $child_table WHERE id = ? AND child = ?"; | ||
| 493 | my $query = "INSERT INTO $child_table (id,child) VALUES (?,?)"; | ||
| 494 | my $sthdel = $self->_prepare($querydel); | ||
| 495 | my $sth = $self->_prepare($query); | ||
| 496 | |||
| 497 | my $parent_id = (ref $parent ? $parent->primary_id : $parent) | ||
| 498 | or $self->throw("$parent should have a primary_id"); | ||
| 499 | |||
| 500 | $self->begin_work or $self->throw($dbh->errstr); | ||
| 501 | eval { | ||
| 502 | for my $child (@children) { | ||
| 503 | my $child_id = ref $child ? $child->primary_id : $child; | ||
| 504 | defined $child_id or die "no primary ID known for $child"; | ||
| 505 | $sthdel->execute($parent_id, $child_id); | ||
| 506 | $sth->execute($parent_id,$child_id); | ||
| 507 | $count++; | ||
| 508 | } | ||
| 509 | }; | ||
| 510 | |||
| 511 | if ($@) { | ||
| 512 | warn "Transaction aborted because $@"; | ||
| 513 | $self->rollback; | ||
| 514 | } | ||
| 515 | else { | ||
| 516 | $self->commit; | ||
| 517 | } | ||
| 518 | $sth->finish; | ||
| 519 | $count; | ||
| 520 | } | ||
| 521 | |||
| 522 | # because this is a reserved word in postgresql | ||
| 523 | ### | ||
| 524 | # get primary sequence between start and end | ||
| 525 | # | ||
| 526 | sub _fetch_sequence { | ||
| 527 | my $self = shift; | ||
| 528 | my ($seqid,$start,$end) = @_; | ||
| 529 | |||
| 530 | # backward compatibility to the old days when I liked reverse complementing | ||
| 531 | # dna by specifying $start > $end | ||
| 532 | my $reversed; | ||
| 533 | if (defined $start && defined $end && $start > $end) { | ||
| 534 | $reversed++; | ||
| 535 | ($start,$end) = ($end,$start); | ||
| 536 | } | ||
| 537 | $start-- if defined $start; | ||
| 538 | $end-- if defined $end; | ||
| 539 | |||
| 540 | my $offset1 = $self->_offset_boundary($seqid,$start || 'left'); | ||
| 541 | my $offset2 = $self->_offset_boundary($seqid,$end || 'right'); | ||
| 542 | my $sequence_table = $self->_sequence_table; | ||
| 543 | my $locationlist_table = $self->_locationlist_table; | ||
| 544 | |||
| 545 | my $sth = $self->_prepare(<<END); | ||
| 546 | SELECT sequence,"offset" | ||
| 547 | FROM $sequence_table as s,$locationlist_table as ll | ||
| 548 | WHERE s.id=ll.id | ||
| 549 | AND ll.seqname= ? | ||
| 550 | AND "offset" >= ? | ||
| 551 | AND "offset" <= ? | ||
| 552 | ORDER BY "offset" | ||
| 553 | END | ||
| 554 | |||
| 555 | my $seq = ''; | ||
| 556 | $sth->execute($seqid,$offset1,$offset2) or $self->throw($sth->errstr); | ||
| 557 | |||
| 558 | while (my($frag,$offset) = $sth->fetchrow_array) { | ||
| 559 | substr($frag,0,$start-$offset) = '' if defined $start && $start > $offset; | ||
| 560 | $seq .= $frag; | ||
| 561 | } | ||
| 562 | substr($seq,$end-$start+1) = '' if defined $end && $end-$start+1 < length($seq); | ||
| 563 | if ($reversed) { | ||
| 564 | $seq = reverse $seq; | ||
| 565 | $seq =~ tr/gatcGATC/ctagCTAG/; | ||
| 566 | } | ||
| 567 | $sth->finish; | ||
| 568 | $seq; | ||
| 569 | } | ||
| 570 | |||
| 571 | sub _offset_boundary { | ||
| 572 | my $self = shift; | ||
| 573 | my ($seqid,$position) = @_; | ||
| 574 | |||
| 575 | my $sequence_table = $self->_sequence_table; | ||
| 576 | my $locationlist_table = $self->_locationlist_table; | ||
| 577 | |||
| 578 | my $sql; | ||
| 579 | $sql = $position eq 'left' ? "SELECT min(\"offset\") FROM $sequence_table as s,$locationlist_table as ll WHERE s.id=ll.id AND ll.seqname=?" | ||
| 580 | :$position eq 'right' ? "SELECT max(\"offset\") FROM $sequence_table as s,$locationlist_table as ll WHERE s.id=ll.id AND ll.seqname=?" | ||
| 581 | :"SELECT max(\"offset\") FROM $sequence_table as s,$locationlist_table as ll WHERE s.id=ll.id AND ll.seqname=? AND \"offset\"<=?"; | ||
| 582 | |||
| 583 | my $sth = $self->_prepare($sql); | ||
| 584 | my @args = $position =~ /^-?\d+$/ ? ($seqid,$position) : ($seqid); | ||
| 585 | $sth->execute(@args) or $self->throw($sth->errstr); | ||
| 586 | my $boundary = $sth->fetchall_arrayref->[0][0]; | ||
| 587 | $sth->finish; | ||
| 588 | return $boundary; | ||
| 589 | } | ||
| 590 | |||
| 591 | sub _name_sql { | ||
| 592 | my $self = shift; | ||
| 593 | my ($name,$allow_aliases,$join) = @_; | ||
| 594 | my $name_table = $self->_name_table; | ||
| 595 | |||
| 596 | my $from = "$name_table as n"; | ||
| 597 | my ($match,$string) = $self->_match_sql($name); | ||
| 598 | |||
| 599 | my $where = "n.id=$join AND lower(n.name) $match"; | ||
| 600 | $where .= " AND n.display_name>0" unless $allow_aliases; | ||
| 601 | return ($from,$where,'',$string); | ||
| 602 | } | ||
| 603 | |||
| 604 | sub _search_attributes { | ||
| 605 | my $self = shift; | ||
| 606 | my ($search_string,$attribute_names,$limit) = @_; | ||
| 607 | my @words = map {quotemeta($_)} split /\s+/,$search_string; | ||
| 608 | my $name_table = $self->_name_table; | ||
| 609 | my $attribute_table = $self->_attribute_table; | ||
| 610 | my $attributelist_table = $self->_attributelist_table; | ||
| 611 | my $type_table = $self->_type_table; | ||
| 612 | my $typelist_table = $self->_typelist_table; | ||
| 613 | |||
| 614 | my @tags = @$attribute_names; | ||
| 615 | my $tag_sql = join ' OR ',("al.tag=?") x @tags; | ||
| 616 | |||
| 617 | my $perl_regexp = join '|',@words; | ||
| 618 | |||
| 619 | my @wild_card_words = map { "%$_%" } @words; | ||
| 620 | my $sql_regexp = join ' OR ',("a.attribute_value SIMILAR TO ?") x @words; | ||
| 621 | my $sql = <<END; | ||
| 622 | SELECT name,attribute_value,tl.tag,n.id | ||
| 623 | FROM $name_table as n,$attribute_table as a,$attributelist_table as al,$type_table as t,$typelist_table as tl | ||
| 624 | WHERE n.id=a.id | ||
| 625 | AND al.id=a.attribute_id | ||
| 626 | AND n.id=t.id | ||
| 627 | AND t.typeid=tl.id | ||
| 628 | AND n.display_name=1 | ||
| 629 | AND ($tag_sql) | ||
| 630 | AND ($sql_regexp) | ||
| 631 | END | ||
| 632 | $sql .= "LIMIT $limit" if defined $limit; | ||
| 633 | $self->_print_query($sql,@tags,@wild_card_words) if DEBUG || $self->debug; | ||
| 634 | my $sth = $self->_prepare($sql); | ||
| 635 | $sth->execute(@tags,@wild_card_words) or $self->throw($sth->errstr); | ||
| 636 | |||
| 637 | my @results; | ||
| 638 | while (my($name,$value,$type,$id) = $sth->fetchrow_array) { | ||
| 639 | my (@hits) = $value =~ /$perl_regexp/ig; | ||
| 640 | my @words_in_row = split /\b/,$value; | ||
| 641 | my $score = int(@hits*100/@words/@words_in_row); | ||
| 642 | push @results,[$name,$value,$score,$type,$id]; | ||
| 643 | } | ||
| 644 | $sth->finish; | ||
| 645 | @results = sort {$b->[2]<=>$a->[2]} @results; | ||
| 646 | return @results; | ||
| 647 | } | ||
| 648 | |||
| 649 | # overridden here because the mysql adapter uses | ||
| 650 | # a non-standard query hint | ||
| 651 | sub _attributes_sql { | ||
| 652 | my $self = shift; | ||
| 653 | my ($attributes,$join) = @_; | ||
| 654 | |||
| 655 | my ($wf,@bind_args) = $self->_make_attribute_where('a','al',$attributes); | ||
| 656 | my ($group_by,@group_args)= $self->_make_attribute_group('a',$attributes); | ||
| 657 | |||
| 658 | my $attribute_table = $self->_attribute_table; | ||
| 659 | my $attributelist_table = $self->_attributelist_table; | ||
| 660 | |||
| 661 | my $from = "$attribute_table as a, $attributelist_table as al"; | ||
| 662 | |||
| 663 | my $where = <<END; | ||
| 664 | a.id=$join | ||
| 665 | AND a.attribute_id=al.id | ||
| 666 | AND ($wf) | ||
| 667 | END | ||
| 668 | |||
| 669 | my $group = $group_by; | ||
| 670 | |||
| 671 | my @args = (@bind_args,@group_args); | ||
| 672 | return ($from,$where,$group,@args); | ||
| 673 | } | ||
| 674 | |||
| 675 | sub _match_sql { | ||
| 676 | my $self = shift; | ||
| 677 | my $name = shift; | ||
| 678 | |||
| 679 | my ($match,$string); | ||
| 680 | if ($name =~ /(?:^|[^\\])[*?]/) { | ||
| 681 | $name =~ s/(^|[^\\])([%_])/$1\\$2/g; | ||
| 682 | $name =~ s/(^|[^\\])\*/$1%/g; | ||
| 683 | $name =~ s/(^|[^\\])\?/$1_/g; | ||
| 684 | $match = "LIKE ?"; | ||
| 685 | $string = lc($name); | ||
| 686 | } else { | ||
| 687 | $match = "= lower(?)"; | ||
| 688 | $string = lc($name); | ||
| 689 | } | ||
| 690 | return ($match,$string); | ||
| 691 | } | ||
| 692 | |||
| 693 | # overridden because of differences between LIKE behavior in mysql and postgres | ||
| 694 | # as well as case-sensitivity of matches | ||
| 695 | sub _types_sql { | ||
| 696 | my $self = shift; | ||
| 697 | my ($types,$type_table) = @_; | ||
| 698 | my ($primary_tag,$source_tag); | ||
| 699 | |||
| 700 | my @types = ref $types eq 'ARRAY' ? @$types : $types; | ||
| 701 | |||
| 702 | my $typelist = $self->_typelist_table; | ||
| 703 | my $from = "$typelist AS tl"; | ||
| 704 | |||
| 705 | my (@matches,@args); | ||
| 706 | |||
| 707 | for my $type (@types) { | ||
| 708 | |||
| 709 | if (ref $type && $type->isa('Bio::DB::GFF::Typename')) { | ||
| 710 | $primary_tag = $type->method; | ||
| 711 | $source_tag = $type->source; | ||
| 712 | } else { | ||
| 713 | ($primary_tag,$source_tag) = split ':',$type,2; | ||
| 714 | } | ||
| 715 | |||
| 716 | if ($source_tag) { | ||
| 717 | push @matches,"lower(tl.tag)=lower(?)"; | ||
| 718 | push @args,"$primary_tag:$source_tag"; | ||
| 719 | } else { | ||
| 720 | push @matches,"tl.tag ILIKE ?"; | ||
| 721 | push @args,"$primary_tag:%"; | ||
| 722 | } | ||
| 723 | } | ||
| 724 | my $matches = join ' OR ',@matches; | ||
| 725 | |||
| 726 | my $where = <<END; | ||
| 727 | tl.id=$type_table.typeid | ||
| 728 | AND ($matches) | ||
| 729 | END | ||
| 730 | |||
| 731 | return ($from,$where,'',@args); | ||
| 732 | } | ||
| 733 | |||
| 734 | # overridden because mysql adapter uses the non-standard REPLACE syntax | ||
| 735 | sub setting { | ||
| 736 | my $self = shift; | ||
| 737 | my ($variable_name,$value) = @_; | ||
| 738 | my $meta = $self->_meta_table; | ||
| 739 | |||
| 740 | if (defined $value && $self->writeable) { | ||
| 741 | my $querydel = "DELETE FROM $meta WHERE name = ?"; | ||
| 742 | my $query = "INSERT INTO $meta (name,value) VALUES (?,?)"; | ||
| 743 | my $sthdel = $self->_prepare($querydel); | ||
| 744 | my $sth = $self->_prepare($query); | ||
| 745 | $sthdel->execute($variable_name); | ||
| 746 | $sth->execute($variable_name,$value) or $self->throw($sth->errstr); | ||
| 747 | $sth->finish; | ||
| 748 | $self->{settings_cache}{$variable_name} = $value; | ||
| 749 | } | ||
| 750 | else { | ||
| 751 | return $self->{settings_cache}{$variable_name} if exists $self->{settings_cache}{$variable_name}; | ||
| 752 | my $query = "SELECT value FROM $meta as m WHERE m.name=?"; | ||
| 753 | my $sth = $self->_prepare($query); | ||
| 754 | # $sth->execute($variable_name) or $self->throw($sth->errstr); | ||
| 755 | unless ($sth->execute($variable_name)) { | ||
| 756 | my $errstr = $sth->errstr; | ||
| 757 | $sth = $self->_prepare("SHOW search_path"); | ||
| 758 | $sth->execute(); | ||
| 759 | $errstr .= "With search_path " . $sth->fetchrow_arrayref->[0] . "\n"; | ||
| 760 | $self->throw($errstr); | ||
| 761 | } | ||
| 762 | |||
| 763 | my ($value) = $sth->fetchrow_array; | ||
| 764 | $sth->finish; | ||
| 765 | return $self->{settings_cache}{$variable_name} = $value; | ||
| 766 | } | ||
| 767 | } | ||
| 768 | |||
| 769 | # overridden because of use of REPLACE in mysql adapter | ||
| 770 | ### | ||
| 771 | # Replace Bio::SeqFeatureI into database. | ||
| 772 | # | ||
| 773 | sub replace { | ||
| 774 | my $self = shift; | ||
| 775 | my $object = shift; | ||
| 776 | my $index_flag = shift || undef; | ||
| 777 | |||
| 778 | # ?? shouldn't need to do this | ||
| 779 | # $self->_load_class($object); | ||
| 780 | my $id = $object->primary_id; | ||
| 781 | my $features = $self->_feature_table; | ||
| 782 | |||
| 783 | my $query = "INSERT INTO $features (id,object,indexed,seqid,start,\"end\",strand,tier,bin,typeid) VALUES (?,?,?,?,?,?,?,?,?,?)"; | ||
| 784 | my $query_noid = "INSERT INTO $features (object,indexed,seqid,start,\"end\",strand,tier,bin,typeid) VALUES (?,?,?,?,?,?,?,?,?)"; | ||
| 785 | my $querydel = "DELETE FROM $features WHERE id = ?"; | ||
| 786 | |||
| 787 | my $sthdel = $self->_prepare($querydel); | ||
| 788 | my $sth = $self->_prepare($query); | ||
| 789 | my $sth_noid = $self->_prepare($query_noid); | ||
| 790 | |||
| 791 | my @location = $index_flag ? $self->_get_location_and_bin($object) : (undef)x6; | ||
| 792 | |||
| 793 | my $primary_tag = $object->primary_tag; | ||
| 794 | my $source_tag = $object->source_tag || ''; | ||
| 795 | $primary_tag .= ":$source_tag"; | ||
| 796 | my $typeid = $self->_typeid($primary_tag,1); | ||
| 797 | |||
| 798 | if ($id) { | ||
| 799 | $sthdel->execute($id); | ||
| 800 | $sth->execute($id,encode_base64($self->freeze($object), ''),$index_flag||0,@location,$typeid) or $self->throw($sth->errstr); | ||
| 801 | } else { | ||
| 802 | $sth_noid->execute(encode_base64($self->freeze($object), ''),$index_flag||0,@location,$typeid) or $self->throw($sth->errstr); | ||
| 803 | } | ||
| 804 | |||
| 805 | my $dbh = $self->dbh; | ||
| 806 | |||
| 807 | $object->primary_id($dbh->last_insert_id(undef, undef, undef, undef, {sequence=>$features."_id_seq"})) unless defined $id; | ||
| 808 | |||
| 809 | $self->flag_for_indexing($dbh->last_insert_id(undef, undef, undef, undef, {sequence=>$features."_id_seq"})) if $self->{bulk_update_in_progress}; | ||
| 810 | } | ||
| 811 | |||
| 812 | =head2 types | ||
| 813 | |||
| 814 | Title : types | ||
| 815 | Usage : @type_list = $db->types | ||
| 816 | Function: Get all the types in the database | ||
| 817 | Returns : array of Bio::DB::GFF::Typename objects | ||
| 818 | Args : none | ||
| 819 | Status : public | ||
| 820 | |||
| 821 | =cut | ||
| 822 | |||
| 823 | # overridden because "offset" is reserved in postgres | ||
| 824 | ### | ||
| 825 | # Insert a bit of DNA or protein into the database | ||
| 826 | # | ||
| 827 | sub _insert_sequence { | ||
| 828 | my $self = shift; | ||
| 829 | my ($seqid,$seq,$offset) = @_; | ||
| 830 | my $id = $self->_locationid($seqid); | ||
| 831 | my $seqtable = $self->_sequence_table; | ||
| 832 | my $sthdel = $self->_prepare("DELETE FROM $seqtable WHERE id = ? AND \"offset\" = ?"); | ||
| 833 | my $sth = $self->_prepare(<<END); | ||
| 834 | INSERT INTO $seqtable (id,"offset",sequence) VALUES (?,?,?) | ||
| 835 | END | ||
| 836 | $sthdel->execute($id,$offset); | ||
| 837 | $sth->execute($id,$offset,$seq) or $self->throw($sth->errstr); | ||
| 838 | } | ||
| 839 | |||
| 840 | # overridden because of mysql adapter's use of REPLACE | ||
| 841 | ### | ||
| 842 | # This subroutine flags the given primary ID for later reindexing | ||
| 843 | # | ||
| 844 | sub flag_for_indexing { | ||
| 845 | my $self = shift; | ||
| 846 | my $id = shift; | ||
| 847 | my $needs_updating = $self->_update_table; | ||
| 848 | |||
| 849 | my $querydel = "DELETE FROM $needs_updating WHERE id = ?"; | ||
| 850 | my $query = "INSERT INTO $needs_updating VALUES (?)"; | ||
| 851 | my $sthdel = $self->_prepare($querydel); | ||
| 852 | my $sth = $self->_prepare($query); | ||
| 853 | |||
| 854 | $sthdel->execute($id); | ||
| 855 | $sth->execute($id) or $self->throw($self->dbh->errstr); | ||
| 856 | } | ||
| 857 | |||
| 858 | # overridden because of the different ways that mysql and postgres | ||
| 859 | # handle id sequences | ||
| 860 | sub _genericid { | ||
| 861 | my $self = shift; | ||
| 862 | my ($table,$namefield,$name,$add_if_missing) = @_; | ||
| 863 | my $qualified_table = $self->_qualify($table); | ||
| 864 | my $sth = $self->_prepare(<<END); | ||
| 865 | SELECT id FROM $qualified_table WHERE $namefield=? | ||
| 866 | END | ||
| 867 | $sth->execute($name) or die $sth->errstr; | ||
| 868 | my ($id) = $sth->fetchrow_array; | ||
| 869 | $sth->finish; | ||
| 870 | return $id if defined $id; | ||
| 871 | return unless $add_if_missing; | ||
| 872 | |||
| 873 | $sth = $self->_prepare(<<END); | ||
| 874 | INSERT INTO $qualified_table ($namefield) VALUES (?) | ||
| 875 | END | ||
| 876 | $sth->execute($name) or die $sth->errstr; | ||
| 877 | my $dbh = $self->dbh; | ||
| 878 | return $dbh->last_insert_id(undef, undef, undef, undef, {sequence=>$qualified_table."_id_seq"}); | ||
| 879 | } | ||
| 880 | |||
| 881 | # overridden because of differences in binding between mysql and postgres adapters | ||
| 882 | # given a statement handler that is expected to return rows of (id,object) | ||
| 883 | # unthaw each object and return a list of 'em | ||
| 884 | sub _sth2objs { | ||
| 885 | my $self = shift; | ||
| 886 | my $sth = shift; | ||
| 887 | my @result; | ||
| 888 | my ($id, $o); | ||
| 889 | $sth->bind_col(1, \$id); | ||
| 890 | $sth->bind_col(2, \$o, { pg_type => PG_BYTEA}); | ||
| 891 | #while (my ($id,$o) = $sth->fetchrow_array) { | ||
| 892 | while ($sth->fetch) { | ||
| 893 | my $obj = $self->thaw(decode_base64($o) ,$id); | ||
| 894 | push @result,$obj; | ||
| 895 | } | ||
| 896 | $sth->finish; | ||
| 897 | return @result; | ||
| 898 | } | ||
| 899 | |||
| 900 | # given a statement handler that is expected to return rows of (id,object) | ||
| 901 | # unthaw each object and return a list of 'em | ||
| 902 | sub _sth2obj { | ||
| 903 | my $self = shift; | ||
| 904 | my $sth = shift; | ||
| 905 | my ($id,$o) = $sth->fetchrow_array; | ||
| 906 | return unless $o; | ||
| 907 | my $obj = $self->thaw(decode_base64($o) ,$id); | ||
| 908 | $obj; | ||
| 909 | } | ||
| 910 | |||
| 911 | #################################################################################################### | ||
| 912 | # SQL Fragment generators | ||
| 913 | #################################################################################################### | ||
| 914 | |||
| 915 | # overridden because of base64 encoding needed here | ||
| 916 | ### | ||
| 917 | # special-purpose store for bulk loading - write to a file rather than to the db | ||
| 918 | # | ||
| 919 | sub _dump_store { | ||
| 920 | my $self = shift; | ||
| 921 | my $indexed = shift; | ||
| 922 | |||
| 923 | my $count = 0; | ||
| 924 | my $store_fh = $self->dump_filehandle('feature'); | ||
| 925 | my $dbh = $self->dbh; | ||
| 926 | |||
| 927 | my $autoindex = $self->autoindex; | ||
| 928 | |||
| 929 | for my $obj (@_) { | ||
| 930 | my $id = $self->next_id; | ||
| 931 | my ($seqid,$start,$end,$strand,$tier,$bin) = $indexed ? $self->_get_location_and_bin($obj) : (undef)x6; | ||
| 932 | my $primary_tag = $obj->primary_tag; | ||
| 933 | my $source_tag = $obj->source_tag || ''; | ||
| 934 | $primary_tag .= ":$source_tag"; | ||
| 935 | my $typeid = $self->_typeid($primary_tag,1); | ||
| 936 | |||
| 937 | my $frozen_object = encode_base64($self->freeze($obj), ''); | ||
| 938 | # TODO: Fix this, why does frozen object start with quote but not end with one | ||
| 939 | print $store_fh join("\t",$id,$typeid,$seqid,$start,$end,$strand,$tier,$bin,$indexed,$frozen_object),"\n"; | ||
| 940 | $obj->primary_id($id); | ||
| 941 | $self->_update_indexes($obj) if $indexed && $autoindex; | ||
| 942 | $count++; | ||
| 943 | } | ||
| 944 | |||
| 945 | # remember whether we are have ever stored a non-indexed feature | ||
| 946 | unless ($indexed or $self->{indexed_flag}++) { | ||
| 947 | $self->subfeatures_are_indexed(0); | ||
| 948 | } | ||
| 949 | $count; | ||
| 950 | } | ||
| 951 | |||
| 952 | sub _enable_keys { } # nullop | ||
| 953 | sub _disable_keys { } # nullop | ||
| 954 | |||
| 955 | sub _add_interval_stats_table { | ||
| 956 | my $self = shift; | ||
| 957 | my $tables = $self->table_definitions; | ||
| 958 | my $interval_stats = $self->_interval_stats_table; | ||
| 959 | ##check to see if it exists yet; if it does, just return because | ||
| 960 | ##there is a drop from in the next step | ||
| 961 | my $dbh = $self->dbh; | ||
| 962 | my @table_exists = $dbh->selectrow_array("SELECT * FROM pg_tables WHERE tablename | ||
| 963 | = '$interval_stats' AND schemaname = '".$self->namespace."'"); | ||
| 964 | if (!scalar(@table_exists)) { | ||
| 965 | my $query = "CREATE TABLE $interval_stats $tables->{interval_stats}"; | ||
| 966 | $dbh->do($query) or $self->throw($dbh->errstr); | ||
| 967 | } | ||
| 968 | } | ||
| 969 | |||
| 970 | sub _fetch_indexed_features_sql { | ||
| 971 | my $self = shift; | ||
| 972 | my $features = $self->_feature_table; | ||
| 973 | return <<END; | ||
| 974 | SELECT typeid,seqid,start-1,"end" | ||
| 975 | FROM $features as f | ||
| 976 | WHERE f.indexed=1 | ||
| 977 | ORDER BY typeid,seqid,start | ||
| 978 | END | ||
| 979 | } | ||
| 980 | |||
| 981 | |||
| 982 | |||
| 983 | 1; | ||