DotTable.pm untested

filter: Statementstmt 0.0% 0 / 263 Branchbran 0.0% 0 / 78 Conditioncond 0.0% 0 / 42 MC/DCmcdc 0.0% 0 / 28 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 444 CC 40 SCAR 41.4
CC
40
Cov
0%
query
182.0
_init_self
72.0
collapse
56.0
CRAP 63.1
1 package Bio::ConnectDots::DotTable;
2 use vars qw(@ISA @AUTO_ATTRIBUTES @OTHER_ATTRIBUTES %SYNONYMS %DEFAULTS);
3 use strict;
4 #use lib "/users/ywang/temp";
5 use Bio::ConnectDots::Connector;
6 use Bio::ConnectDots::Dot;
7 use Bio::ConnectDots::DotQuery;
8 use Bio::ConnectDots::DotQuery::InnerCt;
9 use Bio::ConnectDots::DotQuery::InnerCs;
10 use Bio::ConnectDots::DotQuery::OuterCt;
11 use Bio::ConnectDots::DotQuery::OuterCs;
12 use Class::AutoClass;
13 use HTML::Entities;
14 @ISA = qw(Class::AutoClass); # AutoClass must be first!!
15  
16 @AUTO_ATTRIBUTES=qw(db db_id connectdots name outputs alias2info preview preview_limit);
17 @OTHER_ATTRIBUTES=qw();
18 %SYNONYMS=();
19 %DEFAULTS=(query_type=>'inner',input_type=>'ConnectorTable');
20 Class::AutoClass::declare(__PACKAGE__);
21  
22 sub _init_self {
23 my($self,$class,$args)=@_;
24 return unless $class eq __PACKAGE__; # to prevent subclasses from re-running this
25 $self->alias2info || $self->alias2info({});
26 my $cd=$self->connectdots;
27 $self->throw("Required parameter -name missing") unless $self->name;
28 $self->throw("Required parameter -connectdots missing") unless $cd;
29 my($drop,$create,$query)=$args->get_args(qw(drop create query));
30 Bio::ConnectDots::DB::DotTable->drop($self) if $drop || $create;
31 $self->preview($args->get_args('preview'));
32 $self->preview_limit(500);
33  
34 my $saved=Bio::ConnectDots::DB::DotTable->get($self,$cd);
35 if ($saved) { # copy relevant attributes from db object to self
36 $self->throw("DotTable ".$self->name." already exists") if $query;
37 $self->db_id($saved->db_id);
38 $self->alias2info($saved->alias2info);
39 }
40 $self->query($query) if $query;
41  
42 }
43 sub dotsets {
44 my($self)=@_;
45 my @dotsets;
46 foreach my $alias (keys %{$self->{alias2info}}) {
47 push @dotsets, $self->{alias2info}->{$alias}->{dotset};
48 }
49 wantarray? @dotsets: \@dotsets;
50 }
51 sub put {
52 my($self)=@_;
53 Bio::ConnectDots::DB::DotTable->put($self);
54 }
55  
56 sub query {
57 my($self,$args)=@_;
58 if ($self->db_id) {
59 $self->throw("Connectortable ".$self->name." already exists. Use -create to overwrite")
60 unless $args->create;
61 Bio::ConnectDots::DB::DotTable->drop($self);
62 }
63 my $query_type=$args->query_type || $self->DEFAULTS_ARGS->query_type;
64 my $input_type=$args->input_type || $self->DEFAULTS_ARGS->input_type;
65 $self->throw("Unrecognized query type: $query_type") unless $query_type=~/inner|full|outer/i;
66 $self->throw("Unrecognized input type: $input_type") unless $input_type=~/table|set/i;
67 $args->set_args(-dottable=>$self);
68 # create correct query object for query_type and input_type
69 my $query;
70 if ($query_type=~/inner/i && $input_type=~/table/i) {
71 $query=new Bio::ConnectDots::DotQuery::InnerCt($args);
72 } elsif ($query_type=~/inner/i && $input_type=~/set/i) {
73 $query=new Bio::ConnectDots::DotQuery::InnerCs($args);
74 } elsif ($query_type=~/full|outer/i && $input_type=~/table/i) {
75 $query=new Bio::ConnectDots::DotQuery::OuterCt($args);
76 } elsif ($query_type=~/full|outer/i && $input_type=~/set/i) {
77 $query=new Bio::ConnectDots::DotQuery::OuterCs($args);
78 }
79 $query->execute;
80 $self->outputs($query->outputs);
81 $self->put;
82  
83 # copy to outfile
84 my $outfile_name = $args->get_args('outfile');
85 $self->output_file($outfile_name) if $outfile_name;
86
87 # check for collapse
88 my $collapse = $args->get_args('collapse');
89 my $delimiter = $args->get_args('collapse_seperator');
90 $self->collapse($collapse,$delimiter) if $collapse;
91
92 # check for XML output
93 my $xml_file = $args->get_args('xml_file');
94 my $xml_root = $args->get_args('xml_root');
95
96 if($xml_file && $xml_root) { # collapse xml
97 $self->output_xml($xml_file,$xml_root);
98 } elsif ($xml_file) { # by row xml
99 $self->xml_rows($xml_file);
100 }
101 }
102  
103 ### outputs the table to a flat file
104 sub output_file {
105 my ($self, $filename) = @_;
106 my $tablename = $self->name;
107 $self->{db}->do_sql("COPY $tablename TO '$filename'");
108 }
109  
110 ### collapses all rows into one on the given identifier
111 sub collapse {
112 my ($self, $centric, $delimiter) = @_;
113 my $db = $self->{db};
114 my $dbh = $self->{db}->dbh();
115 my $name = $self->name;
116 $delimiter = ',' if !$delimiter;
117 my $centricIdx = -1;
118 my $outlists = []; # lists on column of identifiers
119
120 # get the column names for the table and find column number for centric
121 my @columns;
122 my $i=0;
123 foreach my $output (@{$self->outputs}) {
124 push @columns, $output->{output_name};
125 $centricIdx = $i if $output->{output_name} eq $centric;
126 $i++;
127 }
128  
129 $self->throw ("Unknown column in collapse option: $centric") if $centricIdx == -1; # centric column not found.
130 my $tmp_name = '__'. $name .'_temp';
131 $db->do_sql("DROP TABLE $tmp_name") if $db->table_exist($tmp_name);
132 $db->do_sql("SELECT * INTO $tmp_name FROM $name LIMIT 1"); # create temp table with identical columns
133 $db->do_sql("TRUNCATE TABLE $tmp_name");
134  
135 my $iterator = $dbh->prepare("SELECT * FROM $name ORDER BY $centric");
136 $iterator->execute();
137 my $currentID;
138 while (my @cols = $iterator->fetchrow_array()) {
139 next unless @cols;
140 if($cols[$centricIdx] ne $currentID && defined($currentID)) { # clear out lists and insert row
141 $self->_collapse_insert($outlists,$tmp_name,$centricIdx,$delimiter);
142 $outlists = [];
143 }
144
145 # add columns to lists
146 for(my $c=0; $c<@cols; $c++) { # push identifiers onto their columns
147 $outlists->[$c]->{$cols[$c]} = 1;
148 }
149
150 $currentID = $cols[$centricIdx];
151 }
152 $self->_collapse_insert($outlists,$tmp_name,$centricIdx,$delimiter); # insert last case
153
154 $db->do_sql("DROP TABLE $name");
155 $db->do_sql("ALTER TABLE $tmp_name RENAME TO $name");
156 }
157  
158 # form lists into an insert statement and insert it into tmp_table
159 sub _collapse_insert {
160 my ($self,$outlists, $tmp_name,$centricIdx,$delimiter) = @_;
161 my $db = $self->{db};
162 return unless $outlists->[0];
163 my $sql = "INSERT INTO $tmp_name VALUES(";
164 my $i=0;
165 foreach my $val_list (@$outlists) {
166 if($i == $centricIdx) {
167 my ($id) = keys %{$val_list};
168 $sql .= "'". $id ."',";
169 }
170 else {
171 my $addstr;
172 foreach my $val (keys %{$val_list}) {
173 $addstr .= $val . $delimiter unless $val eq '';
174 }
175 if($addstr) { # cleanup extra delimiter
176 $addstr = substr($addstr,0,length($addstr)-length($delimiter));
177 $sql .= "'". $addstr ."',";
178 }
179 else {
180 $sql .= "'". "',";
181 }
182 }
183 $i++;
184 }
185 chop($sql); # remove extra comma
186 $sql .= ")";
187 $db->do_sql($sql);
188
189 }
190  
191 sub output_xml {
192 my ($self, $xml_file, $xml_root) = @_;
193 $self->throw("You must define -xml_file to output data to XML.") if !$xml_file;
194 $self->throw("You must define -xml_root to output data to XML.") if !$xml_root;
195  
196 open(OUT, ">$xml_file") or $self->throw("Can not open output xml_file: $xml_file");
197  
198 my $db = $self->{db};
199 my $dbh = $self->{db}->dbh();
200 my $name = $self->name;
201 my $rootIdx = -1;
202
203 # get the column names for the table and find column number for centric
204 my @columns;
205 my @internal_tags;
206 my $i=0;
207 foreach my $output (@{$self->outputs}) {
208 push @columns, $output->{output_name};
209 if ($output->{output_name} eq $xml_root) {
210 $rootIdx = $i;
211 } else {
212 push @internal_tags, $output->{output_name}
213 }
214 $i++;
215 }
216 $self->throw ("Unknown column as XML output root: $xml_root") if $rootIdx == -1; # root column not found.
217  
218 # create the DTD
219 my $DTD = "<!DOCTYPE DotTable [";
220 $DTD .= "<!ELEMENT DotTable ($xml_root*)>";
221 $DTD .= "<!ATTLIST DotTable name CDATA #REQUIRED>";
222 $DTD .= "<!ELEMENT $xml_root (". join('*,',@internal_tags) ."*)>";
223 $DTD .= "<!ATTLIST $xml_root id CDATA #REQUIRED>";
224 foreach my $tagname (@internal_tags) {
225 $DTD .= "<!ELEMENT $tagname (#PCDATA)>";
226 }
227 $DTD .= "]>\n";
228 print OUT $DTD;
229  
230 print OUT "<DotTable name='$name'>\n";
231  
232 # iterate over the ids and output XML
233 my $sql = "SELECT $xml_root,". join(',',@internal_tags) ." FROM $name ORDER BY $xml_root";
234 my $iterator = $dbh->prepare($sql);
235 $iterator->execute();
236 my $currentID;
237 my $outcols;
238 while (my @cols = $iterator->fetchrow_array()) {
239 if($cols[0] ne $currentID && defined($currentID)) { # close out tags and start new tag
240 my $entry = _create_xml_entry($outcols,\@internal_tags,$xml_root,$currentID);
241 print OUT $entry;
242 $outcols = [];
243 }
244
245 # save data by column for this id
246 for(my $i=1; $i<@cols; $i++) {
247 $outcols->[$i-1]->{$cols[$i]} = 1;
248 }
249
250 $currentID = $cols[0];
251 }
252 my $entry = _create_xml_entry($outcols,\@internal_tags,$xml_root,$currentID);
253 print OUT $entry;
254  
255 print OUT "</DotTable>";
256 close(OUT);
257 }
258  
259 # returns an xml entry based off the structure of the passed in ...
260 sub _create_xml_entry {
261 my ($outcols, $internal_tags, $xml_root, $keyid) = @_;
262 return unless $outcols && defined($keyid);
263 $keyid = _encode($keyid);
264 my $entry;
265 $entry = "<$xml_root id='$keyid'>";
266 for(my $c=0; $c<@$outcols; $c++) {
267 my $hash = $outcols->[$c];
268 my $tag = $internal_tags->[$c];
269 foreach my $data (keys %$hash) {
270 $data = _encode($data);
271 $entry .= "<$tag>$data</$tag>" if $data;
272 }
273 }
274 $entry .= "</$xml_root>\n";
275 return $entry;
276 }
277  
278  
279  
280 # exports xml by row
281 sub xml_rows {
282 my ($self, $xml_file) = @_;
283 $self->throw("You must define -xmlrows_file to output data to XML.") if !$xml_file;
284  
285 open(OUT, ">$xml_file") or $self->throw("Can not open output xml_file: $xml_file");
286  
287 my $db = $self->{db};
288 my $dbh = $self->{db}->dbh();
289 my $name = $self->name;
290  
291 # get the column names for the table and find column number for centric
292 my @columns;
293 foreach my $output (@{$self->outputs}) {
294 push @columns, $output->{output_name};
295 }
296  
297 # create the DTD
298 my $DTD = "<!DOCTYPE DotTable [";
299 $DTD .= "<!ELEMENT DotTable (row*)>";
300 $DTD .= "<!ATTLIST DotTable name CDATA #REQUIRED>";
301 $DTD .= "<!ELEMENT row (". join('*,',@columns) ."*)>";
302 $DTD .= "<!ATTLIST row line CDATA #REQUIRED>";
303 foreach my $tagname (@columns) {
304 $DTD .= "<!ELEMENT $tagname (#PCDATA)>";
305 }
306 $DTD .= "]>\n";
307 print OUT $DTD;
308 print OUT "<DotTable name='$name'>\n";
309  
310 my $sql = "SELECT ". join(',',@columns) ." FROM $name";
311 my $iterator = $dbh->prepare($sql);
312 $iterator->execute();
313 my $linenum=1;
314 while (my @cols = $iterator->fetchrow_array()) {
315 my $entry = "<row line='$linenum'>";
316 for (my $i=0; $i<@cols; $i++) {
317 my $tag = $columns[$i];
318 my $data = _encode($cols[$i]);
319 $entry .= "<$tag>$data</$tag>" if defined($cols[$i]);
320 }
321 $entry .= "</row>\n";
322 print OUT $entry;
323 $linenum++;
324 }
325  
326 print OUT "</DotTable>\n";
327 close(OUT);
328 }
329  
330 sub _encode() {
331 my ($string) = @_;
332 $string = encode_entities($string);
333 $string =~ s/\'/&apos;/g;
334 return $string;
335 }
336  
337 1;
338  
339  
340  
341  
342  
343  
344  
345  
346  
347  
348  
349  
350  
351  
352  
353  
354