SeqFeature/Store/DBI/Pg.pm untested

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