2 |
|
|
3 |
use strict; |
use strict; |
4 |
use Tracer; |
use Tracer; |
5 |
use DBKernel; |
use DBrtns; |
6 |
use Data::Dumper; |
use Data::Dumper; |
7 |
use XML::Simple; |
use XML::Simple; |
8 |
use DBQuery; |
use DBQuery; |
9 |
use DBObject; |
use DBObject; |
10 |
use Stats; |
use Stats; |
11 |
use Time::HiRes qw(gettimeofday); |
use Time::HiRes qw(gettimeofday); |
12 |
|
use Digest::MD5 qw(md5_base64); |
13 |
|
use FIG; |
14 |
|
|
15 |
=head1 Entity-Relationship Database Package |
=head1 Entity-Relationship Database Package |
16 |
|
|
34 |
relation that contains two fields-- the feature ID (C<id>) and the alias name (C<alias>). |
relation that contains two fields-- the feature ID (C<id>) and the alias name (C<alias>). |
35 |
The B<FEATURE> entity also contains an optional virulence number. This is implemented |
The B<FEATURE> entity also contains an optional virulence number. This is implemented |
36 |
as a separate relation C<FeatureVirulence> which contains an ID (C<id>) and a virulence number |
as a separate relation C<FeatureVirulence> which contains an ID (C<id>) and a virulence number |
37 |
(C<virulence>). If the virulence of a feature I<ABC> is known to be 6, there will be one row in the |
(C<virulence>). If the virulence of a feature I<ABC> is known to be 6, there will be one row in |
38 |
C<FeatureVirulence> relation possessing the value I<ABC> as its ID and 6 as its virulence number. |
the C<FeatureVirulence> relation possessing the value I<ABC> as its ID and 6 as its virulence |
39 |
If the virulence of I<ABC> is not known, there will not be any rows for it in C<FeatureVirulence>. |
number. If the virulence of I<ABC> is not known, there will not be any rows for it in |
40 |
|
C<FeatureVirulence>. |
41 |
|
|
42 |
Entities are connected by binary relationships implemented using single relations possessing the |
Entities are connected by binary relationships implemented using single relations possessing the |
43 |
same name as the relationship itself and that has an I<arity> of 1-to-1 (C<11>), 1-to-many (C<1M>), |
same name as the relationship itself and that has an I<arity> of 1-to-1 (C<11>), 1-to-many (C<1M>), |
72 |
is described in the L</GenerateEntity> and L</GenerateConnection> methods, though it is not yet |
is described in the L</GenerateEntity> and L</GenerateConnection> methods, though it is not yet |
73 |
fully implemented. |
fully implemented. |
74 |
|
|
75 |
|
=head2 XML Database Description |
76 |
|
|
77 |
|
=head3 Data Types |
78 |
|
|
79 |
|
The ERDB system supports the following data types. Note that there are numerous string |
80 |
|
types depending on the maximum length. Some database packages limit the total number of |
81 |
|
characters you have in an index key; to insure the database works in all environments, |
82 |
|
the type of string should be the shortest one possible that supports all the known values. |
83 |
|
|
84 |
|
=over 4 |
85 |
|
|
86 |
|
=item char |
87 |
|
|
88 |
|
single ASCII character |
89 |
|
|
90 |
|
=item int |
91 |
|
|
92 |
|
32-bit signed integer |
93 |
|
|
94 |
|
=item date |
95 |
|
|
96 |
|
64-bit unsigned integer, representing a PERL date/time value |
97 |
|
|
98 |
|
=item text |
99 |
|
|
100 |
|
long string; Text fields cannot be used in indexes or sorting and do not support the |
101 |
|
normal syntax of filter clauses, but can be up to a billion character in length |
102 |
|
|
103 |
|
=item float |
104 |
|
|
105 |
|
double-precision floating-point number |
106 |
|
|
107 |
|
=item boolean |
108 |
|
|
109 |
|
single-bit numeric value; The value is stored as a 16-bit signed integer (for |
110 |
|
compatability with certain database packages), but the only values supported are |
111 |
|
0 and 1. |
112 |
|
|
113 |
|
=item id-string |
114 |
|
|
115 |
|
variable-length string, maximum 25 characters |
116 |
|
|
117 |
|
=item key-string |
118 |
|
|
119 |
|
variable-length string, maximum 40 characters |
120 |
|
|
121 |
|
=item name-string |
122 |
|
|
123 |
|
variable-length string, maximum 80 characters |
124 |
|
|
125 |
|
=item medium-string |
126 |
|
|
127 |
|
variable-length string, maximum 160 characters |
128 |
|
|
129 |
|
=item string |
130 |
|
|
131 |
|
variable-length string, maximum 255 characters |
132 |
|
|
133 |
|
=item hash-string |
134 |
|
|
135 |
|
variable-length string, maximum 22 characters |
136 |
|
|
137 |
|
=back |
138 |
|
|
139 |
|
The hash-string data type has a special meaning. The actual key passed into the loader will |
140 |
|
be a string, but it will be digested into a 22-character MD5 code to save space. Although the |
141 |
|
MD5 algorithm is not perfect, it is extremely unlikely two strings will have the same |
142 |
|
digest. Therefore, it is presumed the keys will be unique. When the database is actually |
143 |
|
in use, the hashed keys will be presented rather than the original values. For this reason, |
144 |
|
they should not be used for entities where the key is meaningful. |
145 |
|
|
146 |
|
=head3 Global Tags |
147 |
|
|
148 |
|
The entire database definition must be inside a B<Database> tag. The display name of |
149 |
|
the database is given by the text associated with the B<Title> tag. The display name |
150 |
|
is only used in the automated documentation. It has no other effect. The entities and |
151 |
|
relationships are listed inside the B<Entities> and B<Relationships> tags, |
152 |
|
respectively. None of these tags have attributes. |
153 |
|
|
154 |
|
<Database> |
155 |
|
<Title>... display title here...</Title> |
156 |
|
<Entities> |
157 |
|
... entity definitions here ... |
158 |
|
</Entities> |
159 |
|
<Relationships> |
160 |
|
... relationship definitions here... |
161 |
|
</Relationships> |
162 |
|
</Database> |
163 |
|
|
164 |
|
Entities, relationships, indexes, and fields all allow a text tag called B<Notes>. |
165 |
|
The text inside the B<Notes> tag contains comments that will appear when the database |
166 |
|
documentation is generated. Within a B<Notes> tag, you may use C<[i]> and C<[/i]> for |
167 |
|
italics, C<[b]> and C<[/b]> for bold, and C<[p]> for a new paragraph. |
168 |
|
|
169 |
|
=head3 Fields |
170 |
|
|
171 |
|
Both entities and relationships have fields described by B<Field> tags. A B<Field> |
172 |
|
tag can have B<Notes> associated with it. The complete set of B<Field> tags for an |
173 |
|
object mus be inside B<Fields> tags. |
174 |
|
|
175 |
|
<Entity ... > |
176 |
|
<Fields> |
177 |
|
... Field tags ... |
178 |
|
</Fields> |
179 |
|
</Entity> |
180 |
|
|
181 |
|
The attributes for the B<Field> tag are as follows. |
182 |
|
|
183 |
|
=over 4 |
184 |
|
|
185 |
|
=item name |
186 |
|
|
187 |
|
Name of the field. The field name should contain only letters, digits, and hyphens (C<->), |
188 |
|
and the first character should be a letter. Most underlying databases are case-insensitive |
189 |
|
with the respect to field names, so a best practice is to use lower-case letters only. |
190 |
|
|
191 |
|
=item type |
192 |
|
|
193 |
|
Data type of the field. The legal data types are given above. |
194 |
|
|
195 |
|
=item relation |
196 |
|
|
197 |
|
Name of the relation containing the field. This should only be specified for entity |
198 |
|
fields. The ERDB system does not support optional fields or multi-occurring fields |
199 |
|
in the primary relation of an entity. Instead, they are put into secondary relations. |
200 |
|
So, for example, in the C<Genome> entity, the C<group-name> field indicates a special |
201 |
|
grouping used to select a subset of the genomes. A given genome may not be in any |
202 |
|
groups or may be in multiple groups. Therefore, C<group-name> specifies a relation |
203 |
|
value. The relation name specified must be a valid table name. By convention, it is |
204 |
|
usually the entity name followed by a qualifying word (e.g. C<GenomeGroup>). In an |
205 |
|
entity, the fields without a relation attribute are said to belong to the |
206 |
|
I<primary relation>. This relation has the same name as the entity itself. |
207 |
|
|
208 |
|
=back |
209 |
|
|
210 |
|
=head3 Indexes |
211 |
|
|
212 |
|
An entity can have multiple alternate indexes associated with it. The fields must |
213 |
|
be from the primary relation. The alternate indexes assist in ordering results |
214 |
|
from a query. A relationship can have up to two indexes-- a I<to-index> and a |
215 |
|
I<from-index>. These order the results when crossing the relationship. For |
216 |
|
example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the |
217 |
|
from-index would order the contigs of a ganome, and the to-index would order |
218 |
|
the genomes of a contig. A relationship's index must specify only fields in |
219 |
|
the relationship. |
220 |
|
|
221 |
|
The indexes for an entity must be listed inside the B<Indexes> tag. The from-index |
222 |
|
of a relationship is specified using the B<FromIndex> tag; the to-index is specified |
223 |
|
using the B<ToIndex> tag. |
224 |
|
|
225 |
|
Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields> |
226 |
|
tag containing the B<IndexField> tags. These specify, in order, the fields used in |
227 |
|
the index. The attributes of an B<IndexField> tag are as follows. |
228 |
|
|
229 |
|
=over 4 |
230 |
|
|
231 |
|
=item name |
232 |
|
|
233 |
|
Name of the field. |
234 |
|
|
235 |
|
=item order |
236 |
|
|
237 |
|
Sort order of the field-- C<ascending> or C<descending>. |
238 |
|
|
239 |
|
=back |
240 |
|
|
241 |
|
The B<Index>, B<FromIndex>, and B<ToIndex> tags themselves have no attributes. |
242 |
|
|
243 |
|
=head3 Object and Field Names |
244 |
|
|
245 |
|
By convention entity and relationship names use capital casing (e.g. C<Genome> or |
246 |
|
C<HasRegionsIn>. Most underlying databases, however, are aggressively case-insensitive |
247 |
|
with respect to relation names, converting them internally to all-upper case or |
248 |
|
all-lower case. |
249 |
|
|
250 |
|
If syntax or parsing errors occur when you try to load or use an ERDB database, the |
251 |
|
most likely reason is that one of your objects has an SQL reserved word as its name. |
252 |
|
The list of SQL reserved words keeps increasing; however, most are unlikely to show |
253 |
|
up as a noun or declarative verb phrase. The exceptions are C<Group>, C<User>, |
254 |
|
C<Table>, C<Index>, C<Object>, C<Date>, C<Number>, C<Update>, C<Time>, C<Percent>, |
255 |
|
C<Memo>, C<Order>, and C<Sum>. This problem can crop up in field names as well. |
256 |
|
|
257 |
|
Every entity has a field called C<id> that acts as its primary key. Every relationship |
258 |
|
has fields called C<from-link> and C<to-link> that contain copies of the relevant |
259 |
|
entity IDs. These are essentially ERDB's reserved words, and should not be used |
260 |
|
for user-defined field names. |
261 |
|
|
262 |
|
=head3 Entities |
263 |
|
|
264 |
|
An entity is described by the B<Entity> tag. The entity can contain B<Notes>, an |
265 |
|
B<Indexes> tag containing one or more secondary indexes, and a B<Fields> tag |
266 |
|
containing one or more fields. The attributes of the B<Entity> tag are as follows. |
267 |
|
|
268 |
|
=over 4 |
269 |
|
|
270 |
|
=item name |
271 |
|
|
272 |
|
Name of the entity. The entity name, by convention, uses capital casing (e.g. C<Genome> |
273 |
|
or C<GroupBlock>) and should be a noun or noun phrase. |
274 |
|
|
275 |
|
=item keyType |
276 |
|
|
277 |
|
Data type of the primary key. The primary key is always named C<id>. |
278 |
|
|
279 |
|
=back |
280 |
|
|
281 |
|
=head3 Relationships |
282 |
|
|
283 |
|
A relationship is described by the C<Relationship> tag. Within a relationship, |
284 |
|
there can be a C<Notes> tag, a C<Fields> tag containing the intersection data |
285 |
|
fields, a C<FromIndex> tag containing the from-index, and a C<ToIndex> tag containing |
286 |
|
the to-index. |
287 |
|
|
288 |
|
The C<Relationship> tag has the following attributes. |
289 |
|
|
290 |
|
=over 4 |
291 |
|
|
292 |
|
=item name |
293 |
|
|
294 |
|
Name of the relationship. The relationship name, by convention, uses capital casing |
295 |
|
(e.g. C<ContainsRegionIn> or C<HasContig>), and should be a declarative verb |
296 |
|
phrase, designed to fit between the from-entity and the to-entity (e.g. |
297 |
|
Block C<ContainsRegionIn> Genome). |
298 |
|
|
299 |
|
=item from |
300 |
|
|
301 |
|
Name of the entity from which the relationship starts. |
302 |
|
|
303 |
|
=item to |
304 |
|
|
305 |
|
Name of the entity to which the relationship proceeds. |
306 |
|
|
307 |
|
=item arity |
308 |
|
|
309 |
|
Relationship type: C<1M> for one-to-many and C<MM> for many-to-many. |
310 |
|
|
311 |
|
=back |
312 |
|
|
313 |
=cut |
=cut |
314 |
|
|
315 |
# GLOBALS |
# GLOBALS |
317 |
# Table of information about our datatypes. "sqlType" is the corresponding SQL datatype string. |
# Table of information about our datatypes. "sqlType" is the corresponding SQL datatype string. |
318 |
# "maxLen" is the maximum permissible length of the incoming string data used to populate a field |
# "maxLen" is the maximum permissible length of the incoming string data used to populate a field |
319 |
# of the specified type. "dataGen" is PERL string that will be evaluated if no test data generation |
# of the specified type. "dataGen" is PERL string that will be evaluated if no test data generation |
320 |
#string is specified in the field definition. |
# string is specified in the field definition. "avgLen" is the average byte length for estimating |
321 |
my %TypeTable = ( char => { sqlType => 'CHAR(1)', maxLen => 1, dataGen => "StringGen('A')" }, |
# record sizes. |
322 |
int => { sqlType => 'INTEGER', maxLen => 20, dataGen => "IntGen(0, 99999999)" }, |
my %TypeTable = ( char => { sqlType => 'CHAR(1)', maxLen => 1, avgLen => 1, dataGen => "StringGen('A')" }, |
323 |
string => { sqlType => 'VARCHAR(255)', maxLen => 255, dataGen => "StringGen(IntGen(10,250))" }, |
int => { sqlType => 'INTEGER', maxLen => 20, avgLen => 4, dataGen => "IntGen(0, 99999999)" }, |
324 |
text => { sqlType => 'TEXT', maxLen => 1000000000, dataGen => "StringGen(IntGen(80,1000))" }, |
string => { sqlType => 'VARCHAR(255)', maxLen => 255, avgLen => 100, dataGen => "StringGen(IntGen(10,250))" }, |
325 |
date => { sqlType => 'BIGINT', maxLen => 80, dataGen => "DateGen(-7, 7, IntGen(0,1400))" }, |
text => { sqlType => 'TEXT', maxLen => 1000000000, avgLen => 500, dataGen => "StringGen(IntGen(80,1000))" }, |
326 |
float => { sqlType => 'DOUBLE PRECISION', maxLen => 40, dataGen => "FloatGen(0.0, 100.0)" }, |
date => { sqlType => 'BIGINT', maxLen => 80, avgLen => 8, dataGen => "DateGen(-7, 7, IntGen(0,1400))" }, |
327 |
boolean => { sqlType => 'SMALLINT', maxLen => 1, dataGen => "IntGen(0, 1)" }, |
float => { sqlType => 'DOUBLE PRECISION', maxLen => 40, avgLen => 8, dataGen => "FloatGen(0.0, 100.0)" }, |
328 |
|
boolean => { sqlType => 'SMALLINT', maxLen => 1, avgLen => 1, dataGen => "IntGen(0, 1)" }, |
329 |
|
'hash-string' => |
330 |
|
{ sqlType => 'VARCHAR(22)', maxLen => 22, avgLen => 22, dataGen => "SringGen(22)" }, |
331 |
|
'id-string' => |
332 |
|
{ sqlType => 'VARCHAR(25)', maxLen => 25, avgLen => 25, dataGen => "SringGen(22)" }, |
333 |
'key-string' => |
'key-string' => |
334 |
{ sqlType => 'VARCHAR(40)', maxLen => 40, dataGen => "StringGen(IntGen(10,40))" }, |
{ sqlType => 'VARCHAR(40)', maxLen => 40, avgLen => 10, dataGen => "StringGen(IntGen(10,40))" }, |
335 |
'name-string' => |
'name-string' => |
336 |
{ sqlType => 'VARCHAR(80)', maxLen => 80, dataGen => "StringGen(IntGen(10,80))" }, |
{ sqlType => 'VARCHAR(80)', maxLen => 80, avgLen => 40, dataGen => "StringGen(IntGen(10,80))" }, |
337 |
'medium-string' => |
'medium-string' => |
338 |
{ sqlType => 'VARCHAR(160)', maxLen => 160, dataGen => "StringGen(IntGen(10,160))" }, |
{ sqlType => 'VARCHAR(160)', maxLen => 160, avgLen => 40, dataGen => "StringGen(IntGen(10,160))" }, |
339 |
); |
); |
340 |
|
|
341 |
# Table translating arities into natural language. |
# Table translating arities into natural language. |
391 |
|
|
392 |
=head3 ShowMetaData |
=head3 ShowMetaData |
393 |
|
|
394 |
C<< $database->ShowMetaData($fileName); >> |
C<< $erdb->ShowMetaData($fileName); >> |
395 |
|
|
396 |
This method outputs a description of the database. This description can be used to help users create |
This method outputs a description of the database. This description can be used to help users create |
397 |
the data to be loaded into the relations. |
the data to be loaded into the relations. |
422 |
# Write the HTML heading stuff. |
# Write the HTML heading stuff. |
423 |
print HTMLOUT "<html>\n<head>\n<title>$title</title>\n"; |
print HTMLOUT "<html>\n<head>\n<title>$title</title>\n"; |
424 |
print HTMLOUT "</head>\n<body>\n"; |
print HTMLOUT "</head>\n<body>\n"; |
425 |
|
# Write the documentation. |
426 |
|
print HTMLOUT $self->DisplayMetaData(); |
427 |
|
# Close the document. |
428 |
|
print HTMLOUT "</body>\n</html>\n"; |
429 |
|
# Close the file. |
430 |
|
close HTMLOUT; |
431 |
|
} |
432 |
|
|
433 |
|
=head3 DisplayMetaData |
434 |
|
|
435 |
|
C<< my $html = $erdb->DisplayMetaData(); >> |
436 |
|
|
437 |
|
Return an HTML description of the database. This description can be used to help users create |
438 |
|
the data to be loaded into the relations and form queries. The output is raw includable HTML |
439 |
|
without any HEAD or BODY tags. |
440 |
|
|
441 |
|
=over 4 |
442 |
|
|
443 |
|
=item filename |
444 |
|
|
445 |
|
The name of the output file. |
446 |
|
|
447 |
|
=back |
448 |
|
|
449 |
|
=cut |
450 |
|
|
451 |
|
sub DisplayMetaData { |
452 |
|
# Get the parameters. |
453 |
|
my ($self) = @_; |
454 |
|
# Get the metadata and the title string. |
455 |
|
my $metadata = $self->{_metaData}; |
456 |
|
# Get the title string. |
457 |
|
my $title = $metadata->{Title}; |
458 |
|
# Get the entity and relationship lists. |
459 |
|
my $entityList = $metadata->{Entities}; |
460 |
|
my $relationshipList = $metadata->{Relationships}; |
461 |
|
# Declare the return variable. |
462 |
|
my $retVal = ""; |
463 |
|
# Open the output file. |
464 |
|
Trace("Building MetaData table of contents.") if T(4); |
465 |
# Here we do the table of contents. It starts as an unordered list of section names. Each |
# Here we do the table of contents. It starts as an unordered list of section names. Each |
466 |
# section contains an ordered list of entity or relationship subsections. |
# section contains an ordered list of entity or relationship subsections. |
467 |
print HTMLOUT "<ul>\n<li><a href=\"#EntitiesSection\">Entities</a>\n<ol>\n"; |
$retVal .= "<ul>\n<li><a href=\"#EntitiesSection\">Entities</a>\n<ol>\n"; |
468 |
# Loop through the Entities, displaying a list item for each. |
# Loop through the Entities, displaying a list item for each. |
469 |
foreach my $key (sort keys %{$entityList}) { |
foreach my $key (sort keys %{$entityList}) { |
470 |
# Display this item. |
# Display this item. |
471 |
print HTMLOUT "<li><a href=\"#$key\">$key</a></li>\n"; |
$retVal .= "<li><a href=\"#$key\">$key</a></li>\n"; |
472 |
} |
} |
473 |
# Close off the entity section and start the relationship section. |
# Close off the entity section and start the relationship section. |
474 |
print HTMLOUT "</ol></li>\n<li><a href=\"#RelationshipsSection\">Relationships</a>\n<ol>\n"; |
$retVal .= "</ol></li>\n<li><a href=\"#RelationshipsSection\">Relationships</a>\n<ol>\n"; |
475 |
# Loop through the Relationships. |
# Loop through the Relationships. |
476 |
foreach my $key (sort keys %{$relationshipList}) { |
foreach my $key (sort keys %{$relationshipList}) { |
477 |
# Display this item. |
# Display this item. |
478 |
my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key}); |
my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key}); |
479 |
print HTMLOUT "<li><a href=\"#$key\">$relationshipTitle</a></li>\n"; |
$retVal .= "<li><a href=\"#$key\">$relationshipTitle</a></li>\n"; |
480 |
} |
} |
481 |
# Close off the relationship section and list the join table section. |
# Close off the relationship section and list the join table section. |
482 |
print HTMLOUT "</ol></li>\n<li><a href=\"#JoinTable\">Join Table</a></li>\n"; |
$retVal .= "</ol></li>\n<li><a href=\"#JoinTable\">Join Table</a></li>\n"; |
483 |
# Close off the table of contents itself. |
# Close off the table of contents itself. |
484 |
print HTMLOUT "</ul>\n"; |
$retVal .= "</ul>\n"; |
485 |
# Now we start with the actual data. Denote we're starting the entity section. |
# Now we start with the actual data. Denote we're starting the entity section. |
486 |
print HTMLOUT "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n"; |
$retVal .= "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n"; |
487 |
# Loop through the entities. |
# Loop through the entities. |
488 |
for my $key (sort keys %{$entityList}) { |
for my $key (sort keys %{$entityList}) { |
489 |
Trace("Building MetaData entry for $key entity.") if T(4); |
Trace("Building MetaData entry for $key entity.") if T(4); |
490 |
# Create the entity header. It contains a bookmark and the entity name. |
# Create the entity header. It contains a bookmark and the entity name. |
491 |
print HTMLOUT "<a name=\"$key\"></a><h3>$key</h3>\n"; |
$retVal .= "<a name=\"$key\"></a><h3>$key</h3>\n"; |
492 |
# Get the entity data. |
# Get the entity data. |
493 |
my $entityData = $entityList->{$key}; |
my $entityData = $entityList->{$key}; |
494 |
# If there's descriptive text, display it. |
# If there's descriptive text, display it. |
495 |
if (my $notes = $entityData->{Notes}) { |
if (my $notes = $entityData->{Notes}) { |
496 |
print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n"; |
$retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n"; |
497 |
} |
} |
498 |
# Now we want a list of the entity's relationships. First, we set up the relationship subsection. |
# Now we want a list of the entity's relationships. First, we set up the relationship subsection. |
499 |
print HTMLOUT "<h4>Relationships for <b>$key</b></h4>\n<ul>\n"; |
$retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n"; |
500 |
# Loop through the relationships. |
# Loop through the relationships. |
501 |
for my $relationship (sort keys %{$relationshipList}) { |
for my $relationship (sort keys %{$relationshipList}) { |
502 |
# Get the relationship data. |
# Get the relationship data. |
506 |
# Get the relationship sentence and append the arity. |
# Get the relationship sentence and append the arity. |
507 |
my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure); |
my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure); |
508 |
# Display the relationship data. |
# Display the relationship data. |
509 |
print HTMLOUT "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n"; |
$retVal .= "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n"; |
510 |
} |
} |
511 |
} |
} |
512 |
# Close off the relationship list. |
# Close off the relationship list. |
513 |
print HTMLOUT "</ul>\n"; |
$retVal .= "</ul>\n"; |
514 |
# Get the entity's relations. |
# Get the entity's relations. |
515 |
my $relationList = $entityData->{Relations}; |
my $relationList = $entityData->{Relations}; |
516 |
# Create a header for the relation subsection. |
# Create a header for the relation subsection. |
517 |
print HTMLOUT "<h4>Relations for <b>$key</b></h4>\n"; |
$retVal .= "<h4>Relations for <b>$key</b></h4>\n"; |
518 |
# Loop through the relations, displaying them. |
# Loop through the relations, displaying them. |
519 |
for my $relation (sort keys %{$relationList}) { |
for my $relation (sort keys %{$relationList}) { |
520 |
my $htmlString = _ShowRelationTable($relation, $relationList->{$relation}); |
my $htmlString = _ShowRelationTable($relation, $relationList->{$relation}); |
521 |
print HTMLOUT $htmlString; |
$retVal .= $htmlString; |
522 |
} |
} |
523 |
} |
} |
524 |
# Denote we're starting the relationship section. |
# Denote we're starting the relationship section. |
525 |
print HTMLOUT "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n"; |
$retVal .= "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n"; |
526 |
# Loop through the relationships. |
# Loop through the relationships. |
527 |
for my $key (sort keys %{$relationshipList}) { |
for my $key (sort keys %{$relationshipList}) { |
528 |
Trace("Building MetaData entry for $key relationship.") if T(4); |
Trace("Building MetaData entry for $key relationship.") if T(4); |
530 |
my $relationshipStructure = $relationshipList->{$key}; |
my $relationshipStructure = $relationshipList->{$key}; |
531 |
# Create the relationship header. |
# Create the relationship header. |
532 |
my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure); |
my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure); |
533 |
print HTMLOUT "<h3><a name=\"$key\"></a>$headerText</h3>\n"; |
$retVal .= "<h3><a name=\"$key\"></a>$headerText</h3>\n"; |
534 |
# Get the entity names. |
# Get the entity names. |
535 |
my $fromEntity = $relationshipStructure->{from}; |
my $fromEntity = $relationshipStructure->{from}; |
536 |
my $toEntity = $relationshipStructure->{to}; |
my $toEntity = $relationshipStructure->{to}; |
540 |
# since both sentences will say the same thing. |
# since both sentences will say the same thing. |
541 |
my $arity = $relationshipStructure->{arity}; |
my $arity = $relationshipStructure->{arity}; |
542 |
if ($arity eq "11") { |
if ($arity eq "11") { |
543 |
print HTMLOUT "<p>Each <b>$fromEntity</b> relates to at most one <b>$toEntity</b>.\n"; |
$retVal .= "<p>Each <b>$fromEntity</b> relates to at most one <b>$toEntity</b>.\n"; |
544 |
} else { |
} else { |
545 |
print HTMLOUT "<p>Each <b>$fromEntity</b> relates to multiple <b>$toEntity</b>s.\n"; |
$retVal .= "<p>Each <b>$fromEntity</b> relates to multiple <b>$toEntity</b>s.\n"; |
546 |
if ($arity eq "MM" && $fromEntity ne $toEntity) { |
if ($arity eq "MM" && $fromEntity ne $toEntity) { |
547 |
print HTMLOUT "Each <b>$toEntity</b> relates to multiple <b>$fromEntity</b>s.\n"; |
$retVal .= "Each <b>$toEntity</b> relates to multiple <b>$fromEntity</b>s.\n"; |
548 |
} |
} |
549 |
} |
} |
550 |
print HTMLOUT "</p>\n"; |
$retVal .= "</p>\n"; |
551 |
# If there are notes on this relationship, display them. |
# If there are notes on this relationship, display them. |
552 |
if (my $notes = $relationshipStructure->{Notes}) { |
if (my $notes = $relationshipStructure->{Notes}) { |
553 |
print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n"; |
$retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n"; |
554 |
} |
} |
555 |
# Generate the relationship's relation table. |
# Generate the relationship's relation table. |
556 |
my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key}); |
my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key}); |
557 |
print HTMLOUT $htmlString; |
$retVal .= $htmlString; |
558 |
} |
} |
559 |
Trace("Building MetaData join table.") if T(4); |
Trace("Building MetaData join table.") if T(4); |
560 |
# Denote we're starting the join table. |
# Denote we're starting the join table. |
561 |
print HTMLOUT "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n"; |
$retVal .= "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n"; |
562 |
# Create a table header. |
# Create a table header. |
563 |
print HTMLOUT _OpenTable("Join Table", "Source", "Target", "Join Condition"); |
$retVal .= _OpenTable("Join Table", "Source", "Target", "Join Condition"); |
564 |
# Loop through the joins. |
# Loop through the joins. |
565 |
my $joinTable = $metadata->{Joins}; |
my $joinTable = $metadata->{Joins}; |
566 |
my @joinKeys = keys %{$joinTable}; |
my @joinKeys = keys %{$joinTable}; |
568 |
# Separate out the source, the target, and the join clause. |
# Separate out the source, the target, and the join clause. |
569 |
$joinKey =~ m!^([^/]+)/(.+)$!; |
$joinKey =~ m!^([^/]+)/(.+)$!; |
570 |
my ($sourceRelation, $targetRelation) = ($1, $2); |
my ($sourceRelation, $targetRelation) = ($1, $2); |
571 |
Trace("Join with key $joinKey is from $sourceRelation to $targetRelation.") if T(4); |
Trace("Join with key $joinKey is from $sourceRelation to $targetRelation.") if T(Joins => 4); |
572 |
my $source = $self->ComputeObjectSentence($sourceRelation); |
my $source = $self->ComputeObjectSentence($sourceRelation); |
573 |
my $target = $self->ComputeObjectSentence($targetRelation); |
my $target = $self->ComputeObjectSentence($targetRelation); |
574 |
my $clause = $joinTable->{$joinKey}; |
my $clause = $joinTable->{$joinKey}; |
575 |
# Display them in a table row. |
# Display them in a table row. |
576 |
print HTMLOUT "<tr><td>$source</td><td>$target</td><td>$clause</td></tr>\n"; |
$retVal .= "<tr><td>$source</td><td>$target</td><td>$clause</td></tr>\n"; |
577 |
} |
} |
578 |
# Close the table. |
# Close the table. |
579 |
print HTMLOUT _CloseTable(); |
$retVal .= _CloseTable(); |
580 |
# Close the document. |
Trace("Built MetaData HTML.") if T(3); |
581 |
print HTMLOUT "</body>\n</html>\n"; |
# Return the HTML. |
582 |
# Close the file. |
return $retVal; |
|
close HTMLOUT; |
|
|
Trace("Built MetaData web page.") if T(3); |
|
583 |
} |
} |
584 |
|
|
585 |
=head3 DumpMetaData |
=head3 DumpMetaData |
586 |
|
|
587 |
C<< $database->DumpMetaData(); >> |
C<< $erdb->DumpMetaData(); >> |
588 |
|
|
589 |
Return a dump of the metadata structure. |
Return a dump of the metadata structure. |
590 |
|
|
599 |
|
|
600 |
=head3 CreateTables |
=head3 CreateTables |
601 |
|
|
602 |
C<< $datanase->CreateTables(); >> |
C<< $erdb->CreateTables(); >> |
603 |
|
|
604 |
This method creates the tables for the database from the metadata structure loaded by the |
This method creates the tables for the database from the metadata structure loaded by the |
605 |
constructor. It is expected this function will only be used on rare occasions, when the |
constructor. It is expected this function will only be used on rare occasions, when the |
611 |
sub CreateTables { |
sub CreateTables { |
612 |
# Get the parameters. |
# Get the parameters. |
613 |
my ($self) = @_; |
my ($self) = @_; |
614 |
my $metadata = $self->{_metaData}; |
# Get the relation names. |
615 |
my $dbh = $self->{_dbh}; |
my @relNames = $self->GetTableNames(); |
616 |
# Loop through the entities. |
# Loop through the relations. |
617 |
my $entityHash = $metadata->{Entities}; |
for my $relationName (@relNames) { |
|
for my $entityName (keys %{$entityHash}) { |
|
|
my $entityData = $entityHash->{$entityName}; |
|
|
# Tell the user what we're doing. |
|
|
Trace("Creating relations for entity $entityName.") if T(1); |
|
|
# Loop through the entity's relations. |
|
|
for my $relationName (keys %{$entityData->{Relations}}) { |
|
618 |
# Create a table for this relation. |
# Create a table for this relation. |
619 |
$self->CreateTable($relationName); |
$self->CreateTable($relationName); |
620 |
Trace("Relation $relationName created.") if T(1); |
Trace("Relation $relationName created.") if T(2); |
|
} |
|
|
} |
|
|
# Loop through the relationships. |
|
|
my $relationshipTable = $metadata->{Relationships}; |
|
|
for my $relationshipName (keys %{$metadata->{Relationships}}) { |
|
|
# Create a table for this relationship. |
|
|
Trace("Creating relationship $relationshipName.") if T(1); |
|
|
$self->CreateTable($relationshipName); |
|
621 |
} |
} |
622 |
} |
} |
623 |
|
|
624 |
=head3 CreateTable |
=head3 CreateTable |
625 |
|
|
626 |
C<< $database->CreateTable($tableName, $indexFlag); >> |
C<< $erdb->CreateTable($tableName, $indexFlag, $estimatedRows); >> |
627 |
|
|
628 |
Create the table for a relation and optionally create its indexes. |
Create the table for a relation and optionally create its indexes. |
629 |
|
|
633 |
|
|
634 |
Name of the relation (which will also be the table name). |
Name of the relation (which will also be the table name). |
635 |
|
|
636 |
=item $indexFlag |
=item indexFlag |
637 |
|
|
638 |
TRUE if the indexes for the relation should be created, else FALSE. If FALSE, |
TRUE if the indexes for the relation should be created, else FALSE. If FALSE, |
639 |
L</CreateIndexes> must be called later to bring the indexes into existence. |
L</CreateIndexes> must be called later to bring the indexes into existence. |
640 |
|
|
641 |
|
=item estimatedRows (optional) |
642 |
|
|
643 |
|
If specified, the estimated maximum number of rows for the relation. This |
644 |
|
information allows the creation of tables using storage engines that are |
645 |
|
faster but require size estimates, such as MyISAM. |
646 |
|
|
647 |
=back |
=back |
648 |
|
|
649 |
=cut |
=cut |
650 |
|
|
651 |
sub CreateTable { |
sub CreateTable { |
652 |
# Get the parameters. |
# Get the parameters. |
653 |
my ($self, $relationName, $indexFlag) = @_; |
my ($self, $relationName, $indexFlag, $estimatedRows) = @_; |
654 |
# Get the database handle. |
# Get the database handle. |
655 |
my $dbh = $self->{_dbh}; |
my $dbh = $self->{_dbh}; |
656 |
# Get the relation data and determine whether or not the relation is primary. |
# Get the relation data and determine whether or not the relation is primary. |
674 |
# Insure the table is not already there. |
# Insure the table is not already there. |
675 |
$dbh->drop_table(tbl => $relationName); |
$dbh->drop_table(tbl => $relationName); |
676 |
Trace("Table $relationName dropped.") if T(2); |
Trace("Table $relationName dropped.") if T(2); |
677 |
|
# If there are estimated rows, create an estimate so we can take advantage of |
678 |
|
# faster DB technologies. |
679 |
|
my $estimation = undef; |
680 |
|
if ($estimatedRows) { |
681 |
|
$estimation = [$self->EstimateRowSize($relationName), $estimatedRows]; |
682 |
|
} |
683 |
# Create the table. |
# Create the table. |
684 |
Trace("Creating table $relationName: $fieldThing") if T(2); |
Trace("Creating table $relationName: $fieldThing") if T(2); |
685 |
$dbh->create_table(tbl => $relationName, flds => $fieldThing); |
$dbh->create_table(tbl => $relationName, flds => $fieldThing, estimates => $estimation); |
686 |
Trace("Relation $relationName created in database.") if T(2); |
Trace("Relation $relationName created in database.") if T(2); |
687 |
# If we want to build the indexes, we do it here. |
# If we want to build the indexes, we do it here. |
688 |
if ($indexFlag) { |
if ($indexFlag) { |
690 |
} |
} |
691 |
} |
} |
692 |
|
|
693 |
|
=head3 VerifyFields |
694 |
|
|
695 |
|
C<< my $count = $erdb->VerifyFields($relName, \@fieldList); >> |
696 |
|
|
697 |
|
Run through the list of proposed field values, insuring that all the character fields are |
698 |
|
below the maximum length. If any fields are too long, they will be truncated in place. |
699 |
|
|
700 |
|
=over 4 |
701 |
|
|
702 |
|
=item relName |
703 |
|
|
704 |
|
Name of the relation for which the specified fields are destined. |
705 |
|
|
706 |
|
=item fieldList |
707 |
|
|
708 |
|
Reference to a list, in order, of the fields to be put into the relation. |
709 |
|
|
710 |
|
=item RETURN |
711 |
|
|
712 |
|
Returns the number of fields truncated. |
713 |
|
|
714 |
|
=back |
715 |
|
|
716 |
|
=cut |
717 |
|
|
718 |
|
sub VerifyFields { |
719 |
|
# Get the parameters. |
720 |
|
my ($self, $relName, $fieldList) = @_; |
721 |
|
# Initialize the return value. |
722 |
|
my $retVal = 0; |
723 |
|
# Get the relation definition. |
724 |
|
my $relData = $self->_FindRelation($relName); |
725 |
|
# Get the list of field descriptors. |
726 |
|
my $fieldTypes = $relData->{Fields}; |
727 |
|
my $fieldCount = scalar @{$fieldTypes}; |
728 |
|
# Loop through the two lists. |
729 |
|
for (my $i = 0; $i < $fieldCount; $i++) { |
730 |
|
# Get the type of the current field. |
731 |
|
my $fieldType = $fieldTypes->[$i]->{type}; |
732 |
|
# If it's a character field, verify the length. |
733 |
|
if ($fieldType =~ /string/) { |
734 |
|
my $maxLen = $TypeTable{$fieldType}->{maxLen}; |
735 |
|
my $oldString = $fieldList->[$i]; |
736 |
|
if (length($oldString) > $maxLen) { |
737 |
|
# Here it's too big, so we truncate it. |
738 |
|
Trace("Truncating field $i in relation $relName to $maxLen characters from \"$oldString\".") if T(1); |
739 |
|
$fieldList->[$i] = substr $oldString, 0, $maxLen; |
740 |
|
$retVal++; |
741 |
|
} |
742 |
|
} |
743 |
|
} |
744 |
|
# Return the truncation count. |
745 |
|
return $retVal; |
746 |
|
} |
747 |
|
|
748 |
|
=head3 DigestFields |
749 |
|
|
750 |
|
C<< $erdb->DigestFields($relName, $fieldList); >> |
751 |
|
|
752 |
|
Digest the strings in the field list that correspond to data type C<hash-string> in the |
753 |
|
specified relation. |
754 |
|
|
755 |
|
=over 4 |
756 |
|
|
757 |
|
=item relName |
758 |
|
|
759 |
|
Name of the relation to which the fields belong. |
760 |
|
|
761 |
|
=item fieldList |
762 |
|
|
763 |
|
List of field contents to be loaded into the relation. |
764 |
|
|
765 |
|
=back |
766 |
|
|
767 |
|
=cut |
768 |
|
#: Return Type ; |
769 |
|
sub DigestFields { |
770 |
|
# Get the parameters. |
771 |
|
my ($self, $relName, $fieldList) = @_; |
772 |
|
# Get the relation definition. |
773 |
|
my $relData = $self->_FindRelation($relName); |
774 |
|
# Get the list of field descriptors. |
775 |
|
my $fieldTypes = $relData->{Fields}; |
776 |
|
my $fieldCount = scalar @{$fieldTypes}; |
777 |
|
# Loop through the two lists. |
778 |
|
for (my $i = 0; $i < $fieldCount; $i++) { |
779 |
|
# Get the type of the current field. |
780 |
|
my $fieldType = $fieldTypes->[$i]->{type}; |
781 |
|
# If it's a hash string, digest it in place. |
782 |
|
if ($fieldType eq 'hash-string') { |
783 |
|
$fieldList->[$i] = $self->DigestKey($fieldList->[$i]); |
784 |
|
} |
785 |
|
} |
786 |
|
} |
787 |
|
|
788 |
|
=head3 DigestKey |
789 |
|
|
790 |
|
C<< my $digested = $erdb->DigestKey($keyValue); >> |
791 |
|
|
792 |
|
Return the digested value of a symbolic key. The digested value can then be plugged into a |
793 |
|
key-based search into a table with key-type hash-string. |
794 |
|
|
795 |
|
Currently the digesting process is independent of the database structure, but that may not |
796 |
|
always be the case, so this is an instance method instead of a static method. |
797 |
|
|
798 |
|
=over 4 |
799 |
|
|
800 |
|
=item keyValue |
801 |
|
|
802 |
|
Key value to digest. |
803 |
|
|
804 |
|
=item RETURN |
805 |
|
|
806 |
|
Digested value ofthe key. |
807 |
|
|
808 |
|
=back |
809 |
|
|
810 |
|
=cut |
811 |
|
|
812 |
|
sub DigestKey { |
813 |
|
# Get the parameters. |
814 |
|
my ($self, $keyValue) = @_; |
815 |
|
# Compute the digest. |
816 |
|
my $retVal = md5_base64($keyValue); |
817 |
|
# Return the result. |
818 |
|
return $retVal; |
819 |
|
} |
820 |
|
|
821 |
=head3 CreateIndex |
=head3 CreateIndex |
822 |
|
|
823 |
C<< $database->CreateIndex($relationName); >> |
C<< $erdb->CreateIndex($relationName); >> |
824 |
|
|
825 |
Create the indexes for a relation. If a table is being loaded from a large source file (as |
Create the indexes for a relation. If a table is being loaded from a large source file (as |
826 |
is the case in L</LoadTable>), it is best to create the indexes after the load. If that is |
is the case in L</LoadTable>), it is sometimes best to create the indexes after the load. |
827 |
the case, then L</CreateTable> should be called with the index flag set to FALSE, and this |
If that is the case, then L</CreateTable> should be called with the index flag set to |
828 |
method used after the load to create the indexes for the table. |
FALSE, and this method used after the load to create the indexes for the table. |
829 |
|
|
830 |
=cut |
=cut |
831 |
|
|
846 |
# Get the index's uniqueness flag. |
# Get the index's uniqueness flag. |
847 |
my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false'); |
my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false'); |
848 |
# Create the index. |
# Create the index. |
849 |
$dbh->create_index(idx => $indexName, tbl => $relationName, flds => $flds, unique => $unique); |
my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName, |
850 |
|
flds => $flds, unique => $unique); |
851 |
|
if ($rv) { |
852 |
Trace("Index created: $indexName for $relationName ($flds)") if T(1); |
Trace("Index created: $indexName for $relationName ($flds)") if T(1); |
853 |
|
} else { |
854 |
|
Confess("Error creating index $indexName for $relationName using ($flds): " . $dbh->error_message()); |
855 |
|
} |
856 |
} |
} |
857 |
} |
} |
858 |
|
|
859 |
=head3 LoadTables |
=head3 LoadTables |
860 |
|
|
861 |
C<< my $stats = $database->LoadTables($directoryName, $rebuild); >> |
C<< my $stats = $erdb->LoadTables($directoryName, $rebuild); >> |
862 |
|
|
863 |
This method will load the database tables from a directory. The tables must already have been created |
This method will load the database tables from a directory. The tables must already have been created |
864 |
in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name; |
in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name; |
901 |
$directoryName =~ s!/\\$!!; |
$directoryName =~ s!/\\$!!; |
902 |
# Declare the return variable. |
# Declare the return variable. |
903 |
my $retVal = Stats->new(); |
my $retVal = Stats->new(); |
904 |
# Get the metadata structure. |
# Get the relation names. |
905 |
my $metaData = $self->{_metaData}; |
my @relNames = $self->GetTableNames(); |
906 |
# Loop through the entities. |
for my $relationName (@relNames) { |
|
for my $entity (values %{$metaData->{Entities}}) { |
|
|
# Loop through the entity's relations. |
|
|
for my $relationName (keys %{$entity->{Relations}}) { |
|
907 |
# Try to load this relation. |
# Try to load this relation. |
908 |
my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild); |
my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild); |
909 |
# Accumulate the statistics. |
# Accumulate the statistics. |
910 |
$retVal->Accumulate($result); |
$retVal->Accumulate($result); |
911 |
} |
} |
|
} |
|
|
# Loop through the relationships. |
|
|
for my $relationshipName (keys %{$metaData->{Relationships}}) { |
|
|
# Try to load this relationship's relation. |
|
|
my $result = $self->_LoadRelation($directoryName, $relationshipName, $rebuild); |
|
|
# Accumulate the statistics. |
|
|
$retVal->Accumulate($result); |
|
|
} |
|
912 |
# Add the duration of the load to the statistical object. |
# Add the duration of the load to the statistical object. |
913 |
$retVal->Add('duration', gettimeofday - $startTime); |
$retVal->Add('duration', gettimeofday - $startTime); |
914 |
# Return the accumulated statistics. |
# Return the accumulated statistics. |
915 |
return $retVal; |
return $retVal; |
916 |
} |
} |
917 |
|
|
918 |
|
|
919 |
=head3 GetTableNames |
=head3 GetTableNames |
920 |
|
|
921 |
C<< my @names = $database->GetTableNames; >> |
C<< my @names = $erdb->GetTableNames; >> |
922 |
|
|
923 |
Return a list of the relations required to implement this database. |
Return a list of the relations required to implement this database. |
924 |
|
|
935 |
|
|
936 |
=head3 GetEntityTypes |
=head3 GetEntityTypes |
937 |
|
|
938 |
C<< my @names = $database->GetEntityTypes; >> |
C<< my @names = $erdb->GetEntityTypes; >> |
939 |
|
|
940 |
Return a list of the entity type names. |
Return a list of the entity type names. |
941 |
|
|
950 |
return sort keys %{$entityList}; |
return sort keys %{$entityList}; |
951 |
} |
} |
952 |
|
|
953 |
|
=head3 IsEntity |
954 |
|
|
955 |
|
C<< my $flag = $erdb->IsEntity($entityName); >> |
956 |
|
|
957 |
|
Return TRUE if the parameter is an entity name, else FALSE. |
958 |
|
|
959 |
|
=over 4 |
960 |
|
|
961 |
|
=item entityName |
962 |
|
|
963 |
|
Object name to be tested. |
964 |
|
|
965 |
|
=item RETURN |
966 |
|
|
967 |
|
Returns TRUE if the specified string is an entity name, else FALSE. |
968 |
|
|
969 |
|
=back |
970 |
|
|
971 |
|
=cut |
972 |
|
|
973 |
|
sub IsEntity { |
974 |
|
# Get the parameters. |
975 |
|
my ($self, $entityName) = @_; |
976 |
|
# Test to see if it's an entity. |
977 |
|
return exists $self->{_metaData}->{Entities}->{$entityName}; |
978 |
|
} |
979 |
|
|
980 |
=head3 Get |
=head3 Get |
981 |
|
|
982 |
C<< my $query = $database->Get(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >> |
C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >> |
983 |
|
|
984 |
This method returns a query object for entities of a specified type using a specified filter. |
This method returns a query object for entities of a specified type using a specified filter. |
985 |
The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each |
The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each |
987 |
following call requests all B<Genome> objects for the genus specified in the variable |
following call requests all B<Genome> objects for the genus specified in the variable |
988 |
$genus. |
$genus. |
989 |
|
|
990 |
C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", $genus); >> |
C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >> |
991 |
|
|
992 |
The WHERE clause contains a single question mark, so there is a single additional |
The WHERE clause contains a single question mark, so there is a single additional |
993 |
parameter representing the parameter value. It would also be possible to code |
parameter representing the parameter value. It would also be possible to code |
994 |
|
|
995 |
C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >> |
C<< $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'"); >> |
996 |
|
|
997 |
however, this version of the call would generate a syntax error if there were any quote |
however, this version of the call would generate a syntax error if there were any quote |
998 |
characters inside the variable C<$genus>. |
characters inside the variable C<$genus>. |
1004 |
It is possible to specify multiple entity and relationship names in order to retrieve more than |
It is possible to specify multiple entity and relationship names in order to retrieve more than |
1005 |
one object's data at the same time, which allows highly complex joined queries. For example, |
one object's data at the same time, which allows highly complex joined queries. For example, |
1006 |
|
|
1007 |
C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", $genus); >> |
C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >> |
1008 |
|
|
1009 |
If multiple names are specified, then the query processor will automatically determine a |
If multiple names are specified, then the query processor will automatically determine a |
1010 |
join path between the entities and relationships. The algorithm used is very simplistic. |
join path between the entities and relationships. The algorithm used is very simplistic. |
1011 |
In particular, you can't specify any entity or relationship more than once, and if a |
In particular, if a relationship is recursive, the path is determined by the order in which |
1012 |
relationship is recursive, the path is determined by the order in which the entity |
the entity and the relationship appear. For example, consider a recursive relationship |
1013 |
and the relationship appear. For example, consider a recursive relationship B<IsParentOf> |
B<IsParentOf> which relates B<People> objects to other B<People> objects. If the join path is |
|
which relates B<People> objects to other B<People> objects. If the join path is |
|
1014 |
coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however, |
coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however, |
1015 |
the join path is C<['IsParentOf', 'People']>, then the people returned will be children. |
the join path is C<['IsParentOf', 'People']>, then the people returned will be children. |
1016 |
|
|
1017 |
|
If an entity or relationship is mentioned twice, the name for the second occurrence will |
1018 |
|
be suffixed with C<2>, the third occurrence will be suffixed with C<3>, and so forth. So, |
1019 |
|
for example, if we have C<['Feature', 'HasContig', 'Contig', 'HasContig']>, then the |
1020 |
|
B<to-link> field of the first B<HasContig> is specified as C<HasContig(to-link)>, while |
1021 |
|
the B<to-link> field of the second B<HasContig> is specified as C<HasContig2(to-link)>. |
1022 |
|
|
1023 |
=over 4 |
=over 4 |
1024 |
|
|
1025 |
=item objectNames |
=item objectNames |
1042 |
|
|
1043 |
C<< "Genome(genus) = ? ORDER BY Genome(species)" >> |
C<< "Genome(genus) = ? ORDER BY Genome(species)" >> |
1044 |
|
|
1045 |
|
Note that the case is important. Only an uppercase "ORDER BY" with a single space will |
1046 |
|
be processed. The idea is to make it less likely to find the verb by accident. |
1047 |
|
|
1048 |
The rules for field references in a sort order are the same as those for field references in the |
The rules for field references in a sort order are the same as those for field references in the |
1049 |
filter clause in general; however, odd things may happen if a sort field is from a secondary |
filter clause in general; however, odd things may happen if a sort field is from a secondary |
1050 |
relation. |
relation. |
1051 |
|
|
1052 |
=item param1, param2, ..., paramN |
Finally, you can limit the number of rows returned by adding a LIMIT clause. The LIMIT must |
1053 |
|
be the last thing in the filter clause, and it contains only the word "LIMIT" followed by |
1054 |
|
a positive number. So, for example |
1055 |
|
|
1056 |
|
C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >> |
1057 |
|
|
1058 |
Parameter values to be substituted into the filter clause. |
will only return the first ten genomes for the specified genus. The ORDER BY clause is not |
1059 |
|
required. For example, to just get the first 10 genomes in the B<Genome> table, you could |
1060 |
|
use |
1061 |
|
|
1062 |
|
C<< "LIMIT 10" >> |
1063 |
|
|
1064 |
|
=item params |
1065 |
|
|
1066 |
|
Reference to a list of parameter values to be substituted into the filter clause. |
1067 |
|
|
1068 |
=item RETURN |
=item RETURN |
1069 |
|
|
1075 |
|
|
1076 |
sub Get { |
sub Get { |
1077 |
# Get the parameters. |
# Get the parameters. |
1078 |
my ($self, $objectNames, $filterClause, @params) = @_; |
my ($self, $objectNames, $filterClause, $params) = @_; |
1079 |
# Construct the SELECT statement. The general pattern is |
# Process the SQL stuff. |
1080 |
# |
my ($suffix, $mappedNameListRef, $mappedNameHashRef) = |
1081 |
# SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN |
$self->_SetupSQL($objectNames, $filterClause); |
1082 |
# |
# Create the query. |
1083 |
my $dbh = $self->{_dbh}; |
my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) . |
1084 |
my $command = "SELECT DISTINCT " . join('.*, ', @{$objectNames}) . ".* FROM " . |
".* $suffix"; |
1085 |
join(', ', @{$objectNames}); |
my $sth = $self->_GetStatementHandle($command, $params); |
1086 |
# Check for a filter clause. |
# Now we create the relation map, which enables DBQuery to determine the order, name |
1087 |
if ($filterClause) { |
# and mapped name for each object in the query. |
1088 |
# Here we have one, so we convert its field names and add it to the query. First, |
my @relationMap = (); |
1089 |
# We create a copy of the filter string we can work with. |
for my $mappedName (@{$mappedNameListRef}) { |
1090 |
my $filterString = $filterClause; |
push @relationMap, [$mappedName, $mappedNameHashRef->{$mappedName}]; |
|
# Next, we sort the object names by length. This helps protect us from finding |
|
|
# object names inside other object names when we're doing our search and replace. |
|
|
my @sortedNames = sort { length($b) - length($a) } @{$objectNames}; |
|
|
# We will also keep a list of conditions to add to the WHERE clause in order to link |
|
|
# entities and relationships as well as primary relations to secondary ones. |
|
|
my @joinWhere = (); |
|
|
# The final preparatory step is to create a hash table of relation names. The |
|
|
# table begins with the relation names already in the SELECT command. |
|
|
my %fromNames = (); |
|
|
for my $objectName (@sortedNames) { |
|
|
$fromNames{$objectName} = 1; |
|
1091 |
} |
} |
1092 |
# We are ready to begin. We loop through the object names, replacing each |
# Return the statement object. |
1093 |
# object name's field references by the corresponding SQL field reference. |
my $retVal = DBQuery::_new($self, $sth, \@relationMap); |
1094 |
# Along the way, if we find a secondary relation, we will need to add it |
return $retVal; |
|
# to the FROM clause. |
|
|
for my $objectName (@sortedNames) { |
|
|
# Get the length of the object name plus 2. This is the value we add to the |
|
|
# size of the field name to determine the size of the field reference as a |
|
|
# whole. |
|
|
my $nameLength = 2 + length $objectName; |
|
|
# Get the object's field list. |
|
|
my $fieldList = $self->_GetFieldTable($objectName); |
|
|
# Find the field references for this object. |
|
|
while ($filterString =~ m/$objectName\(([^)]*)\)/g) { |
|
|
# At this point, $1 contains the field name, and the current position |
|
|
# is set immediately after the final parenthesis. We pull out the name of |
|
|
# the field and the position and length of the field reference as a whole. |
|
|
my $fieldName = $1; |
|
|
my $len = $nameLength + length $fieldName; |
|
|
my $pos = pos($filterString) - $len; |
|
|
# Insure the field exists. |
|
|
if (!exists $fieldList->{$fieldName}) { |
|
|
Confess("Field $fieldName not found for object $objectName."); |
|
|
} else { |
|
|
# Get the field's relation. |
|
|
my $relationName = $fieldList->{$fieldName}->{relation}; |
|
|
# Insure the relation is in the FROM clause. |
|
|
if (!exists $fromNames{$relationName}) { |
|
|
# Add the relation to the FROM clause. |
|
|
$command .= ", $relationName"; |
|
|
# Create its join sub-clause. |
|
|
push @joinWhere, "$objectName.id = $relationName.id"; |
|
|
# Denote we have it available for future fields. |
|
|
$fromNames{$relationName} = 1; |
|
1095 |
} |
} |
1096 |
# Form an SQL field reference from the relation name and the field name. |
|
1097 |
my $sqlReference = "$relationName." . _FixName($fieldName); |
=head3 GetFlat |
1098 |
# Put it into the filter string in place of the old value. |
|
1099 |
substr($filterString, $pos, $len) = $sqlReference; |
C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >> |
1100 |
# Reposition the search. |
|
1101 |
pos $filterString = $pos + length $sqlReference; |
This is a variation of L</GetAll> that asks for only a single field per record and |
1102 |
|
returns a single flattened list. |
1103 |
|
|
1104 |
|
=over 4 |
1105 |
|
|
1106 |
|
=item objectNames |
1107 |
|
|
1108 |
|
List containing the names of the entity and relationship objects to be retrieved. |
1109 |
|
|
1110 |
|
=item filterClause |
1111 |
|
|
1112 |
|
WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can |
1113 |
|
be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form |
1114 |
|
B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the |
1115 |
|
parameter list as additional parameters. The fields in a filter clause can come from primary |
1116 |
|
entity relations, relationship relations, or secondary entity relations; however, all of the |
1117 |
|
entities and relationships involved must be included in the list of object names. |
1118 |
|
|
1119 |
|
=item parameterList |
1120 |
|
|
1121 |
|
List of the parameters to be substituted in for the parameters marks in the filter clause. |
1122 |
|
|
1123 |
|
=item field |
1124 |
|
|
1125 |
|
Name of the field to be used to get the elements of the list returned. |
1126 |
|
|
1127 |
|
=item RETURN |
1128 |
|
|
1129 |
|
Returns a list of values. |
1130 |
|
|
1131 |
|
=back |
1132 |
|
|
1133 |
|
=cut |
1134 |
|
#: Return Type @; |
1135 |
|
sub GetFlat { |
1136 |
|
# Get the parameters. |
1137 |
|
my ($self, $objectNames, $filterClause, $parameterList, $field) = @_; |
1138 |
|
# Construct the query. |
1139 |
|
my $query = $self->Get($objectNames, $filterClause, $parameterList); |
1140 |
|
# Create the result list. |
1141 |
|
my @retVal = (); |
1142 |
|
# Loop through the records, adding the field values found to the result list. |
1143 |
|
while (my $row = $query->Fetch()) { |
1144 |
|
push @retVal, $row->Value($field); |
1145 |
} |
} |
1146 |
|
# Return the list created. |
1147 |
|
return @retVal; |
1148 |
} |
} |
1149 |
|
|
1150 |
|
=head3 Delete |
1151 |
|
|
1152 |
|
C<< my $stats = $erdb->Delete($entityName, $objectID); >> |
1153 |
|
|
1154 |
|
Delete an entity instance from the database. The instance is deleted along with all entity and |
1155 |
|
relationship instances dependent on it. The idea of dependence here is recursive. An object is |
1156 |
|
always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many |
1157 |
|
relationship connected to a dependent entity or the "to" entity connected to a 1-to-many |
1158 |
|
dependent relationship. |
1159 |
|
|
1160 |
|
=over 4 |
1161 |
|
|
1162 |
|
=item entityName |
1163 |
|
|
1164 |
|
Name of the entity type for the instance being deleted. |
1165 |
|
|
1166 |
|
=item objectID |
1167 |
|
|
1168 |
|
ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>), |
1169 |
|
then it is presumed to by a LIKE pattern. |
1170 |
|
|
1171 |
|
=item testFlag |
1172 |
|
|
1173 |
|
If TRUE, the delete statements will be traced without being executed. |
1174 |
|
|
1175 |
|
=item RETURN |
1176 |
|
|
1177 |
|
Returns a statistics object indicating how many records of each particular table were |
1178 |
|
deleted. |
1179 |
|
|
1180 |
|
=back |
1181 |
|
|
1182 |
|
=cut |
1183 |
|
#: Return Type $%; |
1184 |
|
sub Delete { |
1185 |
|
# Get the parameters. |
1186 |
|
my ($self, $entityName, $objectID, $testFlag) = @_; |
1187 |
|
# Declare the return variable. |
1188 |
|
my $retVal = Stats->new(); |
1189 |
|
# Get the DBKernel object. |
1190 |
|
my $db = $self->{_dbh}; |
1191 |
|
# We're going to generate all the paths branching out from the starting entity. One of |
1192 |
|
# the things we have to be careful about is preventing loops. We'll use a hash to |
1193 |
|
# determine if we've hit a loop. |
1194 |
|
my %alreadyFound = (); |
1195 |
|
# These next lists will serve as our result stack. We start by pushing object lists onto |
1196 |
|
# the stack, and then popping them off to do the deletes. This means the deletes will |
1197 |
|
# start with the longer paths before getting to the shorter ones. That, in turn, makes |
1198 |
|
# sure we don't delete records that might be needed to forge relationships back to the |
1199 |
|
# original item. We have two lists-- one for TO-relationships, and one for |
1200 |
|
# FROM-relationships and entities. |
1201 |
|
my @fromPathList = (); |
1202 |
|
my @toPathList = (); |
1203 |
|
# This final hash is used to remember what work still needs to be done. We push paths |
1204 |
|
# onto the list, then pop them off to extend the paths. We prime it with the starting |
1205 |
|
# point. Note that we will work hard to insure that the last item on a path in the |
1206 |
|
# TODO list is always an entity. |
1207 |
|
my @todoList = ([$entityName]); |
1208 |
|
while (@todoList) { |
1209 |
|
# Get the current path. |
1210 |
|
my $current = pop @todoList; |
1211 |
|
# Copy it into a list. |
1212 |
|
my @stackedPath = @{$current}; |
1213 |
|
# Pull off the last item on the path. It will always be an entity. |
1214 |
|
my $entityName = pop @stackedPath; |
1215 |
|
# Add it to the alreadyFound list. |
1216 |
|
$alreadyFound{$entityName} = 1; |
1217 |
|
# Get the entity data. |
1218 |
|
my $entityData = $self->_GetStructure($entityName); |
1219 |
|
# The first task is to loop through the entity's relation. A DELETE command will |
1220 |
|
# be needed for each of them. |
1221 |
|
my $relations = $entityData->{Relations}; |
1222 |
|
for my $relation (keys %{$relations}) { |
1223 |
|
my @augmentedList = (@stackedPath, $relation); |
1224 |
|
push @fromPathList, \@augmentedList; |
1225 |
} |
} |
1226 |
# The next step is to join the objects together. We only need to do this if there |
# Now we need to look for relationships connected to this entity. |
1227 |
# is more than one object in the object list. We start with the first object and |
my $relationshipList = $self->{_metaData}->{Relationships}; |
1228 |
# run through the objects after it. Note also that we make a safety copy of the |
for my $relationshipName (keys %{$relationshipList}) { |
1229 |
# list before running through it. |
my $relationship = $relationshipList->{$relationshipName}; |
1230 |
my @objectList = @{$objectNames}; |
# Check the FROM field. We're only interested if it's us. |
1231 |
my $lastObject = shift @objectList; |
if ($relationship->{from} eq $entityName) { |
1232 |
# Get the join table. |
# Add the path to this relationship. |
1233 |
my $joinTable = $self->{_metaData}->{Joins}; |
my @augmentedList = (@stackedPath, $entityName, $relationshipName); |
1234 |
# Loop through the object list. |
push @fromPathList, \@augmentedList; |
1235 |
for my $thisObject (@objectList) { |
# Check the arity. If it's MM we're done. If it's 1M |
1236 |
# Look for a join. |
# and the target hasn't been seen yet, we want to |
1237 |
my $joinKey = "$lastObject/$thisObject"; |
# stack the entity for future processing. |
1238 |
if (!exists $joinTable->{$joinKey}) { |
if ($relationship->{arity} eq '1M') { |
1239 |
# Here there's no join, so we throw an error. |
my $toEntity = $relationship->{to}; |
1240 |
Confess("No join exists to connect from $lastObject to $thisObject."); |
if (! exists $alreadyFound{$toEntity}) { |
1241 |
|
# Here we have a new entity that's dependent on |
1242 |
|
# the current entity, so we need to stack it. |
1243 |
|
my @stackList = (@augmentedList, $toEntity); |
1244 |
|
push @fromPathList, \@stackList; |
1245 |
} else { |
} else { |
1246 |
# Get the join clause and add it to the WHERE list. |
Trace("$toEntity ignored because it occurred previously.") if T(4); |
|
push @joinWhere, $joinTable->{$joinKey}; |
|
|
# Save this object as the last object for the next iteration. |
|
|
$lastObject = $thisObject; |
|
1247 |
} |
} |
1248 |
} |
} |
|
# Now we need to handle the whole ORDER BY thing. We'll put the order by clause |
|
|
# in the following variable. |
|
|
my $orderClause = ""; |
|
|
# Locate the ORDER BY verb (if any). |
|
|
if ($filterString =~ m/^(.*)ORDER BY/g) { |
|
|
# Here we have an ORDER BY verb. Split it off of the filter string. |
|
|
my $pos = pos $filterString; |
|
|
$orderClause = substr($filterString, $pos); |
|
|
$filterString = $1; |
|
1249 |
} |
} |
1250 |
# Add the filter and the join clauses (if any) to the SELECT command. |
# Now check the TO field. In this case only the relationship needs |
1251 |
if ($filterString) { |
# deletion. |
1252 |
push @joinWhere, "($filterString)"; |
if ($relationship->{to} eq $entityName) { |
1253 |
|
my @augmentedList = (@stackedPath, $entityName, $relationshipName); |
1254 |
|
push @toPathList, \@augmentedList; |
1255 |
} |
} |
|
if (@joinWhere) { |
|
|
$command .= " WHERE " . join(' AND ', @joinWhere); |
|
1256 |
} |
} |
|
# Add the sort clause (if any) to the SELECT command. |
|
|
if ($orderClause) { |
|
|
$command .= " ORDER BY $orderClause"; |
|
1257 |
} |
} |
1258 |
|
# Create the first qualifier for the WHERE clause. This selects the |
1259 |
|
# keys of the primary entity records to be deleted. When we're deleting |
1260 |
|
# from a dependent table, we construct a join page from the first qualifier |
1261 |
|
# to the table containing the dependent records to delete. |
1262 |
|
my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?"); |
1263 |
|
# We need to make two passes. The first is through the to-list, and |
1264 |
|
# the second through the from-list. The from-list is second because |
1265 |
|
# the to-list may need to pass through some of the entities the |
1266 |
|
# from-list would delete. |
1267 |
|
my %stackList = ( from_link => \@fromPathList, to_link => \@toPathList ); |
1268 |
|
# Now it's time to do the deletes. We do it in two passes. |
1269 |
|
for my $keyName ('to_link', 'from_link') { |
1270 |
|
# Get the list for this key. |
1271 |
|
my @pathList = @{$stackList{$keyName}}; |
1272 |
|
Trace(scalar(@pathList) . " entries in path list for $keyName.") if T(3); |
1273 |
|
# Loop through this list. |
1274 |
|
while (my $path = pop @pathList) { |
1275 |
|
# Get the table whose rows are to be deleted. |
1276 |
|
my @pathTables = @{$path}; |
1277 |
|
# Start the DELETE statement. We need to call DBKernel because the |
1278 |
|
# syntax of a DELETE-USING varies among DBMSs. |
1279 |
|
my $target = $pathTables[$#pathTables]; |
1280 |
|
my $stmt = $db->SetUsing(@pathTables); |
1281 |
|
# Now start the WHERE. The first thing is the ID field from the starting table. That |
1282 |
|
# starting table will either be the entity relation or one of the entity's |
1283 |
|
# sub-relations. |
1284 |
|
$stmt .= " WHERE $pathTables[0].id $qualifier"; |
1285 |
|
# Now we run through the remaining entities in the path, connecting them up. |
1286 |
|
for (my $i = 1; $i <= $#pathTables; $i += 2) { |
1287 |
|
# Connect the current relationship to the preceding entity. |
1288 |
|
my ($entity, $rel) = @pathTables[$i-1,$i]; |
1289 |
|
# The style of connection depends on the direction of the relationship. |
1290 |
|
$stmt .= " AND $entity.id = $rel.$keyName"; |
1291 |
|
if ($i + 1 <= $#pathTables) { |
1292 |
|
# Here there's a next entity, so connect that to the relationship's |
1293 |
|
# to-link. |
1294 |
|
my $entity2 = $pathTables[$i+1]; |
1295 |
|
$stmt .= " AND $rel.to_link = $entity2.id"; |
1296 |
|
} |
1297 |
|
} |
1298 |
|
# Now we have our desired DELETE statement. |
1299 |
|
if ($testFlag) { |
1300 |
|
# Here the user wants to trace without executing. |
1301 |
|
Trace($stmt) if T(0); |
1302 |
|
} else { |
1303 |
|
# Here we can delete. Note that the SQL method dies with a confessing |
1304 |
|
# if an error occurs, so we just go ahead and do it. |
1305 |
|
Trace("Executing delete from $target using '$objectID'.") if T(3); |
1306 |
|
my $rv = $db->SQL($stmt, 0, $objectID); |
1307 |
|
# Accumulate the statistics for this delete. The only rows deleted |
1308 |
|
# are from the target table, so we use its name to record the |
1309 |
|
# statistic. |
1310 |
|
$retVal->Add($target, $rv); |
1311 |
} |
} |
1312 |
Trace("SQL query: $command") if T(2); |
} |
1313 |
Trace("PARMS: '" . (join "', '", @params) . "'") if (T(3) && (@params > 0)); |
} |
1314 |
my $sth = $dbh->prepare_command($command); |
# Return the result. |
|
# Execute it with the parameters bound in. |
|
|
$sth->execute(@params) || Confess("SELECT error" . $sth->errstr()); |
|
|
# Return the statement object. |
|
|
my $retVal = DBQuery::_new($self, $sth, @{$objectNames}); |
|
1315 |
return $retVal; |
return $retVal; |
1316 |
} |
} |
1317 |
|
|
1318 |
=head3 GetList |
=head3 GetList |
1319 |
|
|
1320 |
C<< my @dbObjects = $database->GetList(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >> |
C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >> |
1321 |
|
|
1322 |
Return a list of object descriptors for the specified objects as determined by the |
Return a list of object descriptors for the specified objects as determined by the |
1323 |
specified filter clause. |
specified filter clause. |
1351 |
filter clause in general; however, odd things may happen if a sort field is from a secondary |
filter clause in general; however, odd things may happen if a sort field is from a secondary |
1352 |
relation. |
relation. |
1353 |
|
|
1354 |
=item param1, param2, ..., paramN |
=item params |
1355 |
|
|
1356 |
Parameter values to be substituted into the filter clause. |
Reference to a list of parameter values to be substituted into the filter clause. |
1357 |
|
|
1358 |
=item RETURN |
=item RETURN |
1359 |
|
|
1365 |
#: Return Type @% |
#: Return Type @% |
1366 |
sub GetList { |
sub GetList { |
1367 |
# Get the parameters. |
# Get the parameters. |
1368 |
my ($self, $objectNames, $filterClause, @params) = @_; |
my ($self, $objectNames, $filterClause, $params) = @_; |
1369 |
# Declare the return variable. |
# Declare the return variable. |
1370 |
my @retVal = (); |
my @retVal = (); |
1371 |
# Perform the query. |
# Perform the query. |
1372 |
my $query = $self->Get($objectNames, $filterClause, @params); |
my $query = $self->Get($objectNames, $filterClause, $params); |
1373 |
# Loop through the results. |
# Loop through the results. |
1374 |
while (my $object = $query->Fetch) { |
while (my $object = $query->Fetch) { |
1375 |
push @retVal, $object; |
push @retVal, $object; |
1378 |
return @retVal; |
return @retVal; |
1379 |
} |
} |
1380 |
|
|
1381 |
|
=head3 GetCount |
1382 |
|
|
1383 |
|
C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >> |
1384 |
|
|
1385 |
|
Return the number of rows found by a specified query. This method would |
1386 |
|
normally be used to count the records in a single table. For example, in a |
1387 |
|
genetics database |
1388 |
|
|
1389 |
|
my $count = $erdb->GetCount(['Genome'], 'Genome(genus-species) LIKE ?', ['homo %']); |
1390 |
|
|
1391 |
|
would return the number of genomes for the genus I<homo>. It is conceivable, however, |
1392 |
|
to use it to return records based on a join. For example, |
1393 |
|
|
1394 |
|
my $count = $erdb->GetCount(['HasFeature', 'Genome'], 'Genome(genus-species) LIKE ?', |
1395 |
|
['homo %']); |
1396 |
|
|
1397 |
|
would return the number of features for genomes in the genus I<homo>. Note that |
1398 |
|
only the rows from the first table are counted. If the above command were |
1399 |
|
|
1400 |
|
my $count = $erdb->GetCount(['Genome', 'Feature'], 'Genome(genus-species) LIKE ?', |
1401 |
|
['homo %']); |
1402 |
|
|
1403 |
|
it would return the number of genomes, not the number of genome/feature pairs. |
1404 |
|
|
1405 |
|
=over 4 |
1406 |
|
|
1407 |
|
=item objectNames |
1408 |
|
|
1409 |
|
Reference to a list of the objects (entities and relationships) included in the |
1410 |
|
query. |
1411 |
|
|
1412 |
|
=item filter |
1413 |
|
|
1414 |
|
A filter clause for restricting the query. The rules are the same as for the L</Get> |
1415 |
|
method. |
1416 |
|
|
1417 |
|
=item params |
1418 |
|
|
1419 |
|
Reference to a list of the parameter values to be substituted for the parameter marks |
1420 |
|
in the filter. |
1421 |
|
|
1422 |
|
=item RETURN |
1423 |
|
|
1424 |
|
Returns a count of the number of records in the first table that would satisfy |
1425 |
|
the query. |
1426 |
|
|
1427 |
|
=back |
1428 |
|
|
1429 |
|
=cut |
1430 |
|
|
1431 |
|
sub GetCount { |
1432 |
|
# Get the parameters. |
1433 |
|
my ($self, $objectNames, $filter, $params) = @_; |
1434 |
|
# Declare the return variable. |
1435 |
|
my $retVal; |
1436 |
|
# Find out if we're counting an entity or a relationship. |
1437 |
|
my $countedField; |
1438 |
|
if ($self->IsEntity($objectNames->[0])) { |
1439 |
|
$countedField = "id"; |
1440 |
|
} else { |
1441 |
|
# For a relationship we count the to-link because it's usually more |
1442 |
|
# numerous. Note we're automatically converting to the SQL form |
1443 |
|
# of the field name (to_link vs. to-link). |
1444 |
|
$countedField = "to_link"; |
1445 |
|
} |
1446 |
|
# Create the SQL command suffix to get the desired records. |
1447 |
|
my ($suffix, $mappedNameListRef, $mappedNameHashRef) = $self->_SetupSQL($objectNames, |
1448 |
|
$filter); |
1449 |
|
# Prefix it with text telling it we want a record count. |
1450 |
|
my $firstObject = $mappedNameListRef->[0]; |
1451 |
|
my $command = "SELECT COUNT($firstObject.$countedField) $suffix"; |
1452 |
|
# Prepare and execute the command. |
1453 |
|
my $sth = $self->_GetStatementHandle($command, $params); |
1454 |
|
# Get the count value. |
1455 |
|
($retVal) = $sth->fetchrow_array(); |
1456 |
|
# Check for a problem. |
1457 |
|
if (! defined($retVal)) { |
1458 |
|
if ($sth->err) { |
1459 |
|
# Here we had an SQL error. |
1460 |
|
Confess("Error retrieving row count: " . $sth->errstr()); |
1461 |
|
} else { |
1462 |
|
# Here we have no result. |
1463 |
|
Confess("No result attempting to retrieve row count."); |
1464 |
|
} |
1465 |
|
} |
1466 |
|
# Return the result. |
1467 |
|
return $retVal; |
1468 |
|
} |
1469 |
|
|
1470 |
=head3 ComputeObjectSentence |
=head3 ComputeObjectSentence |
1471 |
|
|
1472 |
C<< my $sentence = $database->ComputeObjectSentence($objectName); >> |
C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >> |
1473 |
|
|
1474 |
Check an object name, and if it is a relationship convert it to a relationship sentence. |
Check an object name, and if it is a relationship convert it to a relationship sentence. |
1475 |
|
|
1504 |
|
|
1505 |
=head3 DumpRelations |
=head3 DumpRelations |
1506 |
|
|
1507 |
C<< $database->DumpRelations($outputDirectory); >> |
C<< $erdb->DumpRelations($outputDirectory); >> |
1508 |
|
|
1509 |
Write the contents of all the relations to tab-delimited files in the specified directory. |
Write the contents of all the relations to tab-delimited files in the specified directory. |
1510 |
Each file will have the same name as the relation dumped, with an extension of DTX. |
Each file will have the same name as the relation dumped, with an extension of DTX. |
1546 |
|
|
1547 |
=head3 InsertObject |
=head3 InsertObject |
1548 |
|
|
1549 |
C<< my $ok = $database->InsertObject($objectType, \%fieldHash); >> |
C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >> |
1550 |
|
|
1551 |
Insert an object into the database. The object is defined by a type name and then a hash |
Insert an object into the database. The object is defined by a type name and then a hash |
1552 |
of field names to values. Field values in the primary relation are represented by scalars. |
of field names to values. Field values in the primary relation are represented by scalars. |
1555 |
example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases |
example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases |
1556 |
C<ZP_00210270.1> and C<gi|46206278>. |
C<ZP_00210270.1> and C<gi|46206278>. |
1557 |
|
|
1558 |
C<< $database->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >> |
C<< $erdb->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >> |
1559 |
|
|
1560 |
The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and |
The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and |
1561 |
property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>. |
property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>. |
1562 |
|
|
1563 |
C<< $database->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence = 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >> |
C<< $erdb->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence = 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >> |
1564 |
|
|
1565 |
=over 4 |
=over 4 |
1566 |
|
|
1685 |
|
|
1686 |
=head3 LoadTable |
=head3 LoadTable |
1687 |
|
|
1688 |
C<< my %results = $database->LoadTable($fileName, $relationName, $truncateFlag); >> |
C<< my %results = $erdb->LoadTable($fileName, $relationName, $truncateFlag); >> |
1689 |
|
|
1690 |
Load data from a tab-delimited file into a specified table, optionally re-creating the table first. |
Load data from a tab-delimited file into a specified table, optionally re-creating the table |
1691 |
|
first. |
1692 |
|
|
1693 |
=over 4 |
=over 4 |
1694 |
|
|
1706 |
|
|
1707 |
=item RETURN |
=item RETURN |
1708 |
|
|
1709 |
Returns a statistical object containing the number of records read and a list of the error messages. |
Returns a statistical object containing a list of the error messages. |
1710 |
|
|
1711 |
=back |
=back |
1712 |
|
|
1717 |
# Create the statistical return object. |
# Create the statistical return object. |
1718 |
my $retVal = _GetLoadStats(); |
my $retVal = _GetLoadStats(); |
1719 |
# Trace the fact of the load. |
# Trace the fact of the load. |
1720 |
Trace("Loading table $relationName from $fileName") if T(1); |
Trace("Loading table $relationName from $fileName") if T(2); |
1721 |
# Get the database handle. |
# Get the database handle. |
1722 |
my $dbh = $self->{_dbh}; |
my $dbh = $self->{_dbh}; |
1723 |
|
# Get the input file size. |
1724 |
|
my $fileSize = -s $fileName; |
1725 |
# Get the relation data. |
# Get the relation data. |
1726 |
my $relation = $self->_FindRelation($relationName); |
my $relation = $self->_FindRelation($relationName); |
1727 |
# Check the truncation flag. |
# Check the truncation flag. |
1728 |
if ($truncateFlag) { |
if ($truncateFlag) { |
1729 |
Trace("Creating table $relationName") if T(1); |
Trace("Creating table $relationName") if T(2); |
1730 |
|
# Compute the row count estimate. We take the size of the load file, |
1731 |
|
# divide it by the estimated row size, and then multiply by 1.5 to |
1732 |
|
# leave extra room. We postulate a minimum row count of 1000 to |
1733 |
|
# prevent problems with incoming empty load files. |
1734 |
|
my $rowSize = $self->EstimateRowSize($relationName); |
1735 |
|
my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000); |
1736 |
# Re-create the table without its index. |
# Re-create the table without its index. |
1737 |
$self->CreateTable($relationName, 0); |
$self->CreateTable($relationName, 0, $estimate); |
1738 |
|
# If this is a pre-index DBMS, create the index here. |
1739 |
|
if ($dbh->{_preIndex}) { |
1740 |
|
eval { |
1741 |
|
$self->CreateIndex($relationName); |
1742 |
|
}; |
1743 |
|
if ($@) { |
1744 |
|
$retVal->AddMessage($@); |
1745 |
|
} |
1746 |
|
} |
1747 |
} |
} |
|
# Determine whether or not this is a primary relation. Primary relations have an extra |
|
|
# field indicating whether or not a given object is new or was loaded from the flat files. |
|
|
my $primary = $self->_IsPrimary($relationName); |
|
|
# Get the number of fields in this relation. |
|
|
my @fieldList = @{$relation->{Fields}}; |
|
|
my $fieldCount = @fieldList; |
|
|
# Record the number of expected fields. |
|
|
my $expectedFields = $fieldCount + ($primary ? 1 : 0); |
|
|
# Start a database transaction. |
|
|
$dbh->begin_tran; |
|
|
# Open the relation file. We need to create a cleaned-up copy before loading. |
|
|
open TABLEIN, '<', $fileName; |
|
|
my $tempName = "$fileName.tbl"; |
|
|
open TABLEOUT, '>', $tempName; |
|
|
# Loop through the file. |
|
|
while (<TABLEIN>) { |
|
|
# Chop off the new-line character. |
|
|
my $record = $_; |
|
|
chomp $record; |
|
|
# Only proceed if the record is non-blank. |
|
|
if ($record) { |
|
|
# Escape all the backslashes found in the line. |
|
|
$record =~ s/\\/\\\\/g; |
|
|
# Eliminate any trailing tabs. |
|
|
chop $record while substr($record, -1) eq "\t"; |
|
|
# If this is a primary relation, add a 0 for the new-record flag (indicating that |
|
|
# this record is not new, but part of the original load). |
|
|
if ($primary) { |
|
|
$record .= "\t0"; |
|
|
} |
|
|
# Write the record. |
|
|
print TABLEOUT "$record\n"; |
|
|
# Count the record read. |
|
|
my $count = $retVal->Add('records'); |
|
|
my $len = length $record; |
|
|
Trace("Record $count written with $len characters.") if T(4); |
|
|
} |
|
|
} |
|
|
# Close the files. |
|
|
close TABLEIN; |
|
|
close TABLEOUT; |
|
|
Trace("Temporary file $tempName created.") if T(4); |
|
1748 |
# Load the table. |
# Load the table. |
1749 |
my $rv; |
my $rv; |
1750 |
eval { |
eval { |
1751 |
$rv = $dbh->load_table(file => $tempName, tbl => $relationName); |
$rv = $dbh->load_table(file => $fileName, tbl => $relationName); |
1752 |
}; |
}; |
1753 |
if (!defined $rv) { |
if (!defined $rv) { |
1754 |
$retVal->AddMessage($@) if ($@); |
$retVal->AddMessage($@) if ($@); |
1755 |
$retVal->AddMessage("Table load failed for $relationName using $tempName."); |
$retVal->AddMessage("Table load failed for $relationName using $fileName."); |
1756 |
Trace("Table load failed for $relationName.") if T(1); |
Trace("Table load failed for $relationName.") if T(1); |
1757 |
} else { |
} else { |
1758 |
# Here we successfully loaded the table. Trace the number of records loaded. |
# Here we successfully loaded the table. |
1759 |
Trace("$retVal->{records} records read for $relationName.") if T(1); |
$retVal->Add("tables"); |
1760 |
|
my $size = -s $fileName; |
1761 |
|
Trace("$size bytes loaded into $relationName.") if T(2); |
1762 |
# If we're rebuilding, we need to create the table indexes. |
# If we're rebuilding, we need to create the table indexes. |
1763 |
if ($truncateFlag) { |
if ($truncateFlag && ! $dbh->{_preIndex}) { |
1764 |
eval { |
eval { |
1765 |
$self->CreateIndex($relationName); |
$self->CreateIndex($relationName); |
1766 |
}; |
}; |
1769 |
} |
} |
1770 |
} |
} |
1771 |
} |
} |
1772 |
# Commit the database changes. |
# Analyze the table to improve performance. |
1773 |
$dbh->commit_tran; |
$dbh->vacuum_it($relationName); |
|
# Delete the temporary file. |
|
|
unlink $tempName; |
|
1774 |
# Return the statistics. |
# Return the statistics. |
1775 |
return $retVal; |
return $retVal; |
1776 |
} |
} |
1777 |
|
|
1778 |
=head3 GenerateEntity |
=head3 GenerateEntity |
1779 |
|
|
1780 |
C<< my $fieldHash = $database->GenerateEntity($id, $type, \%values); >> |
C<< my $fieldHash = $erdb->GenerateEntity($id, $type, \%values); >> |
1781 |
|
|
1782 |
Generate the data for a new entity instance. This method creates a field hash suitable for |
Generate the data for a new entity instance. This method creates a field hash suitable for |
1783 |
passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest |
passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest |
1833 |
return $this; |
return $this; |
1834 |
} |
} |
1835 |
|
|
1836 |
=head3 GetEntity |
=head3 GetEntity |
1837 |
|
|
1838 |
|
C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >> |
1839 |
|
|
1840 |
|
Return an object describing the entity instance with a specified ID. |
1841 |
|
|
1842 |
|
=over 4 |
1843 |
|
|
1844 |
|
=item entityType |
1845 |
|
|
1846 |
|
Entity type name. |
1847 |
|
|
1848 |
|
=item ID |
1849 |
|
|
1850 |
|
ID of the desired entity. |
1851 |
|
|
1852 |
|
=item RETURN |
1853 |
|
|
1854 |
|
Returns a B<DBObject> representing the desired entity instance, or an undefined value if no |
1855 |
|
instance is found with the specified key. |
1856 |
|
|
1857 |
|
=back |
1858 |
|
|
1859 |
|
=cut |
1860 |
|
|
1861 |
|
sub GetEntity { |
1862 |
|
# Get the parameters. |
1863 |
|
my ($self, $entityType, $ID) = @_; |
1864 |
|
# Create a query. |
1865 |
|
my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]); |
1866 |
|
# Get the first (and only) object. |
1867 |
|
my $retVal = $query->Fetch(); |
1868 |
|
# Return the result. |
1869 |
|
return $retVal; |
1870 |
|
} |
1871 |
|
|
1872 |
|
=head3 GetEntityValues |
1873 |
|
|
1874 |
|
C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >> |
1875 |
|
|
1876 |
|
Return a list of values from a specified entity instance. |
1877 |
|
|
1878 |
|
=over 4 |
1879 |
|
|
1880 |
|
=item entityType |
1881 |
|
|
1882 |
|
Entity type name. |
1883 |
|
|
1884 |
|
=item ID |
1885 |
|
|
1886 |
|
ID of the desired entity. |
1887 |
|
|
1888 |
|
=item fields |
1889 |
|
|
1890 |
|
List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>. |
1891 |
|
|
1892 |
|
=item RETURN |
1893 |
|
|
1894 |
|
Returns a flattened list of the values of the specified fields for the specified entity. |
1895 |
|
|
1896 |
|
=back |
1897 |
|
|
1898 |
|
=cut |
1899 |
|
|
1900 |
|
sub GetEntityValues { |
1901 |
|
# Get the parameters. |
1902 |
|
my ($self, $entityType, $ID, $fields) = @_; |
1903 |
|
# Get the specified entity. |
1904 |
|
my $entity = $self->GetEntity($entityType, $ID); |
1905 |
|
# Declare the return list. |
1906 |
|
my @retVal = (); |
1907 |
|
# If we found the entity, push the values into the return list. |
1908 |
|
if ($entity) { |
1909 |
|
push @retVal, $entity->Values($fields); |
1910 |
|
} |
1911 |
|
# Return the result. |
1912 |
|
return @retVal; |
1913 |
|
} |
1914 |
|
|
1915 |
|
=head3 GetAll |
1916 |
|
|
1917 |
|
C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >> |
1918 |
|
|
1919 |
|
Return a list of values taken from the objects returned by a query. The first three |
1920 |
|
parameters correspond to the parameters of the L</Get> method. The final parameter is |
1921 |
|
a list of the fields desired from each record found by the query. The field name |
1922 |
|
syntax is the standard syntax used for fields in the B<ERDB> system-- |
1923 |
|
B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity |
1924 |
|
or relationship and I<fieldName> is the name of the field. |
1925 |
|
|
1926 |
|
The list returned will be a list of lists. Each element of the list will contain |
1927 |
|
the values returned for the fields specified in the fourth parameter. If one of the |
1928 |
|
fields specified returns multiple values, they are flattened in with the rest. For |
1929 |
|
example, the following call will return a list of the features in a particular |
1930 |
|
spreadsheet cell, and each feature will be represented by a list containing the |
1931 |
|
feature ID followed by all of its aliases. |
1932 |
|
|
1933 |
|
C<< $query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >> |
1934 |
|
|
1935 |
|
=over 4 |
1936 |
|
|
1937 |
|
=item objectNames |
1938 |
|
|
1939 |
|
List containing the names of the entity and relationship objects to be retrieved. |
1940 |
|
|
1941 |
|
=item filterClause |
1942 |
|
|
1943 |
|
WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can |
1944 |
|
be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form |
1945 |
|
B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the |
1946 |
|
parameter list as additional parameters. The fields in a filter clause can come from primary |
1947 |
|
entity relations, relationship relations, or secondary entity relations; however, all of the |
1948 |
|
entities and relationships involved must be included in the list of object names. |
1949 |
|
|
1950 |
|
=item parameterList |
1951 |
|
|
1952 |
|
List of the parameters to be substituted in for the parameters marks in the filter clause. |
1953 |
|
|
1954 |
|
=item fields |
1955 |
|
|
1956 |
|
List of the fields to be returned in each element of the list returned. |
1957 |
|
|
1958 |
|
=item count |
1959 |
|
|
1960 |
|
Maximum number of records to return. If omitted or 0, all available records will be returned. |
1961 |
|
|
1962 |
|
=item RETURN |
1963 |
|
|
1964 |
|
Returns a list of list references. Each element of the return list contains the values for the |
1965 |
|
fields specified in the B<fields> parameter. |
1966 |
|
|
1967 |
|
=back |
1968 |
|
|
1969 |
|
=cut |
1970 |
|
#: Return Type @@; |
1971 |
|
sub GetAll { |
1972 |
|
# Get the parameters. |
1973 |
|
my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_; |
1974 |
|
# Translate the parameters from a list reference to a list. If the parameter |
1975 |
|
# list is a scalar we convert it into a singleton list. |
1976 |
|
my @parmList = (); |
1977 |
|
if (ref $parameterList eq "ARRAY") { |
1978 |
|
Trace("GetAll parm list is an array.") if T(4); |
1979 |
|
@parmList = @{$parameterList}; |
1980 |
|
} else { |
1981 |
|
Trace("GetAll parm list is a scalar: $parameterList.") if T(4); |
1982 |
|
push @parmList, $parameterList; |
1983 |
|
} |
1984 |
|
# Insure the counter has a value. |
1985 |
|
if (!defined $count) { |
1986 |
|
$count = 0; |
1987 |
|
} |
1988 |
|
# Add the row limit to the filter clause. |
1989 |
|
if ($count > 0) { |
1990 |
|
$filterClause .= " LIMIT $count"; |
1991 |
|
} |
1992 |
|
# Create the query. |
1993 |
|
my $query = $self->Get($objectNames, $filterClause, \@parmList); |
1994 |
|
# Set up a counter of the number of records read. |
1995 |
|
my $fetched = 0; |
1996 |
|
# Loop through the records returned, extracting the fields. Note that if the |
1997 |
|
# counter is non-zero, we stop when the number of records read hits the count. |
1998 |
|
my @retVal = (); |
1999 |
|
while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) { |
2000 |
|
my @rowData = $row->Values($fields); |
2001 |
|
push @retVal, \@rowData; |
2002 |
|
$fetched++; |
2003 |
|
} |
2004 |
|
# Return the resulting list. |
2005 |
|
return @retVal; |
2006 |
|
} |
2007 |
|
|
2008 |
|
=head3 EstimateRowSize |
2009 |
|
|
2010 |
|
C<< my $rowSize = $erdb->EstimateRowSize($relName); >> |
2011 |
|
|
2012 |
|
Estimate the row size of the specified relation. The estimated row size is computed by adding |
2013 |
|
up the average length for each data type. |
2014 |
|
|
2015 |
|
=over 4 |
2016 |
|
|
2017 |
|
=item relName |
2018 |
|
|
2019 |
|
Name of the relation whose estimated row size is desired. |
2020 |
|
|
2021 |
|
=item RETURN |
2022 |
|
|
2023 |
|
Returns an estimate of the row size for the specified relation. |
2024 |
|
|
2025 |
|
=back |
2026 |
|
|
2027 |
|
=cut |
2028 |
|
#: Return Type $; |
2029 |
|
sub EstimateRowSize { |
2030 |
|
# Get the parameters. |
2031 |
|
my ($self, $relName) = @_; |
2032 |
|
# Declare the return variable. |
2033 |
|
my $retVal = 0; |
2034 |
|
# Find the relation descriptor. |
2035 |
|
my $relation = $self->_FindRelation($relName); |
2036 |
|
# Get the list of fields. |
2037 |
|
for my $fieldData (@{$relation->{Fields}}) { |
2038 |
|
# Get the field type and add its length. |
2039 |
|
my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen}; |
2040 |
|
$retVal += $fieldLen; |
2041 |
|
} |
2042 |
|
# Return the result. |
2043 |
|
return $retVal; |
2044 |
|
} |
2045 |
|
|
2046 |
|
=head3 GetFieldTable |
2047 |
|
|
2048 |
|
C<< my $fieldHash = $self->GetFieldTable($objectnName); >> |
2049 |
|
|
2050 |
|
Get the field structure for a specified entity or relationship. |
2051 |
|
|
2052 |
|
=over 4 |
2053 |
|
|
2054 |
|
=item objectName |
2055 |
|
|
2056 |
|
Name of the desired entity or relationship. |
2057 |
|
|
2058 |
|
=item RETURN |
2059 |
|
|
2060 |
|
The table containing the field descriptors for the specified object. |
2061 |
|
|
2062 |
|
=back |
2063 |
|
|
2064 |
|
=cut |
2065 |
|
|
2066 |
|
sub GetFieldTable { |
2067 |
|
# Get the parameters. |
2068 |
|
my ($self, $objectName) = @_; |
2069 |
|
# Get the descriptor from the metadata. |
2070 |
|
my $objectData = $self->_GetStructure($objectName); |
2071 |
|
# Return the object's field table. |
2072 |
|
return $objectData->{Fields}; |
2073 |
|
} |
2074 |
|
|
2075 |
|
=head2 Data Mining Methods |
2076 |
|
|
2077 |
|
=head3 GetUsefulCrossValues |
2078 |
|
|
2079 |
|
C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >> |
2080 |
|
|
2081 |
|
Return a list of the useful attributes that would be returned by a B<Cross> call |
2082 |
|
from an entity of the source entity type through the specified relationship. This |
2083 |
|
means it will return the fields of the target entity type and the intersection data |
2084 |
|
fields in the relationship. Only primary table fields are returned. In other words, |
2085 |
|
the field names returned will be for fields where there is always one and only one |
2086 |
|
value. |
2087 |
|
|
2088 |
|
=over 4 |
2089 |
|
|
2090 |
|
=item sourceEntity |
2091 |
|
|
2092 |
|
Name of the entity from which the relationship crossing will start. |
2093 |
|
|
2094 |
|
=item relationship |
2095 |
|
|
2096 |
|
Name of the relationship being crossed. |
2097 |
|
|
2098 |
|
=item RETURN |
2099 |
|
|
2100 |
|
Returns a list of field names in Sprout field format (I<objectName>C<(>I<fieldName>C<)>. |
2101 |
|
|
2102 |
|
=back |
2103 |
|
|
2104 |
|
=cut |
2105 |
|
#: Return Type @; |
2106 |
|
sub GetUsefulCrossValues { |
2107 |
|
# Get the parameters. |
2108 |
|
my ($self, $sourceEntity, $relationship) = @_; |
2109 |
|
# Declare the return variable. |
2110 |
|
my @retVal = (); |
2111 |
|
# Determine the target entity for the relationship. This is whichever entity is not |
2112 |
|
# the source entity. So, if the source entity is the FROM, we'll get the name of |
2113 |
|
# the TO, and vice versa. |
2114 |
|
my $relStructure = $self->_GetStructure($relationship); |
2115 |
|
my $targetEntityType = ($relStructure->{from} eq $sourceEntity ? "to" : "from"); |
2116 |
|
my $targetEntity = $relStructure->{$targetEntityType}; |
2117 |
|
# Get the field table for the entity. |
2118 |
|
my $entityFields = $self->GetFieldTable($targetEntity); |
2119 |
|
# The field table is a hash. The hash key is the field name. The hash value is a structure. |
2120 |
|
# For the entity fields, the key aspect of the target structure is that the {relation} value |
2121 |
|
# must match the entity name. |
2122 |
|
my @fieldList = map { "$targetEntity($_)" } grep { $entityFields->{$_}->{relation} eq $targetEntity } |
2123 |
|
keys %{$entityFields}; |
2124 |
|
# Push the fields found onto the return variable. |
2125 |
|
push @retVal, sort @fieldList; |
2126 |
|
# Get the field table for the relationship. |
2127 |
|
my $relationshipFields = $self->GetFieldTable($relationship); |
2128 |
|
# Here we have a different rule. We want all the fields other than "from-link" and "to-link". |
2129 |
|
# This may end up being an empty set. |
2130 |
|
my @fieldList2 = map { "$relationship($_)" } grep { $_ ne "from-link" && $_ ne "to-link" } |
2131 |
|
keys %{$relationshipFields}; |
2132 |
|
# Push these onto the return list. |
2133 |
|
push @retVal, sort @fieldList2; |
2134 |
|
# Return the result. |
2135 |
|
return @retVal; |
2136 |
|
} |
2137 |
|
|
2138 |
|
=head3 FindColumn |
2139 |
|
|
2140 |
C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >> |
C<< my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier); >> |
2141 |
|
|
2142 |
Return an object describing the entity instance with a specified ID. |
Return the location a desired column in a data mining header line. The data |
2143 |
|
mining header line is a tab-separated list of column names. The column |
2144 |
|
identifier is either the numerical index of a column or the actual column |
2145 |
|
name. |
2146 |
|
|
2147 |
=over 4 |
=over 4 |
2148 |
|
|
2149 |
=item entityType |
=item headerLine |
2150 |
|
|
2151 |
Entity type name. |
The header line from a data mining command, which consists of a tab-separated |
2152 |
|
list of column names. |
2153 |
|
|
2154 |
=item ID |
=item columnIdentifier |
2155 |
|
|
2156 |
ID of the desired entity. |
Either the ordinal number of the desired column (1-based), or the name of the |
2157 |
|
desired column. |
2158 |
|
|
2159 |
=item RETURN |
=item RETURN |
2160 |
|
|
2161 |
Returns a B<DBObject> representing the desired entity instance, or an undefined value if no |
Returns the array index (0-based) of the desired column. |
|
instance is found with the specified key. |
|
2162 |
|
|
2163 |
=back |
=back |
2164 |
|
|
2165 |
=cut |
=cut |
2166 |
|
|
2167 |
sub GetEntity { |
sub FindColumn { |
2168 |
# Get the parameters. |
# Get the parameters. |
2169 |
my ($self, $entityType, $ID) = @_; |
my ($headerLine, $columnIdentifier) = @_; |
2170 |
# Create a query. |
# Declare the return variable. |
2171 |
my $query = $self->Get([$entityType], "$entityType(id) = ?", $ID); |
my $retVal; |
2172 |
# Get the first (and only) object. |
# Split the header line into column names. |
2173 |
my $retVal = $query->Fetch(); |
my @headers = ParseColumns($headerLine); |
2174 |
|
# Determine whether we have a number or a name. |
2175 |
|
if ($columnIdentifier =~ /^\d+$/) { |
2176 |
|
# Here we have a number. Subtract 1 and validate the result. |
2177 |
|
$retVal = $columnIdentifier - 1; |
2178 |
|
if ($retVal < 0 || $retVal > $#headers) { |
2179 |
|
Confess("Invalid column identifer \"$columnIdentifier\": value out of range."); |
2180 |
|
} |
2181 |
|
} else { |
2182 |
|
# Here we have a name. We need to find it in the list. |
2183 |
|
for (my $i = 0; $i <= $#headers && ! defined($retVal); $i++) { |
2184 |
|
if ($headers[$i] eq $columnIdentifier) { |
2185 |
|
$retVal = $i; |
2186 |
|
} |
2187 |
|
} |
2188 |
|
if (! defined($retVal)) { |
2189 |
|
Confess("Invalid column identifier \"$columnIdentifier\": value not found."); |
2190 |
|
} |
2191 |
|
} |
2192 |
# Return the result. |
# Return the result. |
2193 |
return $retVal; |
return $retVal; |
2194 |
} |
} |
2195 |
|
|
2196 |
=head3 GetEntityValues |
=head3 ParseColumns |
2197 |
|
|
2198 |
C<< my @values = GetEntityValues($entityType, $ID, \@fields); >> |
C<< my @columns = ERDB->ParseColumns($line); >> |
2199 |
|
|
2200 |
Return a list of values from a specified entity instance. |
Convert the specified data line to a list of columns. |
2201 |
|
|
2202 |
=over 4 |
=over 4 |
2203 |
|
|
2204 |
=item entityType |
=item line |
|
|
|
|
Entity type name. |
|
|
|
|
|
=item ID |
|
|
|
|
|
ID of the desired entity. |
|
|
|
|
|
=item fields |
|
2205 |
|
|
2206 |
List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>. |
A data mining input, consisting of a tab-separated list of columns terminated by a |
2207 |
|
new-line. |
2208 |
|
|
2209 |
=item RETURN |
=item RETURN |
2210 |
|
|
2211 |
Returns a flattened list of the values of the specified fields for the specified entity. |
Returns a list consisting of the column values. |
2212 |
|
|
2213 |
=back |
=back |
2214 |
|
|
2215 |
=cut |
=cut |
2216 |
|
|
2217 |
sub GetEntityValues { |
sub ParseColumns { |
2218 |
# Get the parameters. |
# Get the parameters. |
2219 |
my ($self, $entityType, $ID, $fields) = @_; |
my ($self, $line) = @_; |
2220 |
# Get the specified entity. |
# Chop off the line-end. |
2221 |
my $entity = $self->GetEntity($entityType, $ID); |
chomp $line; |
2222 |
# Declare the return list. |
# Split it into a list. |
2223 |
my @retVal = (); |
my @retVal = split(/\t/, $line); |
|
# If we found the entity, push the values into the return list. |
|
|
if ($entity) { |
|
|
push @retVal, $entity->Values($fields); |
|
|
} |
|
2224 |
# Return the result. |
# Return the result. |
2225 |
return @retVal; |
return @retVal; |
2226 |
} |
} |
2227 |
|
|
2228 |
=head3 GetAll |
=head2 Internal Utility Methods |
|
|
|
|
C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >> |
|
2229 |
|
|
2230 |
Return a list of values taken from the objects returned by a query. The first three |
=head3 SetupSQL |
|
parameters correspond to the parameters of the L</Get> method. The final parameter is |
|
|
a list of the fields desired from each record found by the query. The field name |
|
|
syntax is the standard syntax used for fields in the B<ERDB> system-- |
|
|
B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity |
|
|
or relationship and I<fieldName> is the name of the field. |
|
2231 |
|
|
2232 |
The list returned will be a list of lists. Each element of the list will contain |
Process a list of object names and a filter clause so that they can be used to |
2233 |
the values returned for the fields specified in the fourth parameter. If one of the |
build an SQL statement. This method takes in a reference to a list of object names |
2234 |
fields specified returns multiple values, they are flattened in with the rest. For |
and a filter clause. It will return a corrected filter clause, a list of mapped |
2235 |
example, the following call will return a list of the features in a particular |
names and the mapped name hash. |
|
spreadsheet cell, and each feature will be represented by a list containing the |
|
|
feature ID followed by all of its aliases. |
|
2236 |
|
|
2237 |
C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >> |
This is an instance method. |
2238 |
|
|
2239 |
=over 4 |
=over 4 |
2240 |
|
|
2241 |
=item objectNames |
=item objectNames |
2242 |
|
|
2243 |
List containing the names of the entity and relationship objects to be retrieved. |
Reference to a list of the object names to be included in the query. |
2244 |
|
|
2245 |
=item filterClause |
=item filterClause |
2246 |
|
|
2247 |
WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can |
A string containing the WHERE clause for the query (without the C<WHERE>) and also |
2248 |
be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form |
optionally the C<ORDER BY> and C<LIMIT> clauses. |
|
B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the |
|
|
parameter list as additional parameters. The fields in a filter clause can come from primary |
|
|
entity relations, relationship relations, or secondary entity relations; however, all of the |
|
|
entities and relationships involved must be included in the list of object names. |
|
2249 |
|
|
2250 |
=item parameterList |
=item RETURN |
2251 |
|
|
2252 |
List of the parameters to be substituted in for the parameters marks in the filter clause. |
Returns a three-element list. The first element is the SQL statement suffix, beginning |
2253 |
|
with the FROM clause. The second element is a reference to a list of the names to be |
2254 |
|
used in retrieving the fields. The third element is a hash mapping the names to the |
2255 |
|
objects they represent. |
2256 |
|
|
2257 |
=item fields |
=back |
2258 |
|
|
2259 |
List of the fields to be returned in each element of the list returned. |
=cut |
2260 |
|
|
2261 |
=item count |
sub _SetupSQL { |
2262 |
|
my ($self, $objectNames, $filterClause) = @_; |
2263 |
|
# Adjust the list of object names to account for multiple occurrences of the |
2264 |
|
# same object. We start with a hash table keyed on object name that will |
2265 |
|
# return the object suffix. The first time an object is encountered it will |
2266 |
|
# not be found in the hash. The next time the hash will map the object name |
2267 |
|
# to 2, then 3, and so forth. |
2268 |
|
my %objectHash = (); |
2269 |
|
# This list will contain the object names as they are to appear in the |
2270 |
|
# FROM list. |
2271 |
|
my @fromList = (); |
2272 |
|
# This list contains the suffixed object name for each object. It is exactly |
2273 |
|
# parallel to the list in the $objectNames parameter. |
2274 |
|
my @mappedNameList = (); |
2275 |
|
# Finally, this hash translates from a mapped name to its original object name. |
2276 |
|
my %mappedNameHash = (); |
2277 |
|
# Now we create the lists. Note that for every single name we push something into |
2278 |
|
# @fromList and @mappedNameList. This insures that those two arrays are exactly |
2279 |
|
# parallel to $objectNames. |
2280 |
|
for my $objectName (@{$objectNames}) { |
2281 |
|
# Get the next suffix for this object. |
2282 |
|
my $suffix = $objectHash{$objectName}; |
2283 |
|
if (! $suffix) { |
2284 |
|
# Here we are seeing the object for the first time. The object name |
2285 |
|
# is used as is. |
2286 |
|
push @mappedNameList, $objectName; |
2287 |
|
push @fromList, $objectName; |
2288 |
|
$mappedNameHash{$objectName} = $objectName; |
2289 |
|
# Denote the next suffix will be 2. |
2290 |
|
$objectHash{$objectName} = 2; |
2291 |
|
} else { |
2292 |
|
# Here we've seen the object before. We construct a new name using |
2293 |
|
# the suffix from the hash and update the hash. |
2294 |
|
my $mappedName = "$objectName$suffix"; |
2295 |
|
$objectHash{$objectName} = $suffix + 1; |
2296 |
|
# The FROM list has the object name followed by the mapped name. This |
2297 |
|
# tells SQL it's still the same table, but we're using a different name |
2298 |
|
# for it to avoid confusion. |
2299 |
|
push @fromList, "$objectName $mappedName"; |
2300 |
|
# The mapped-name list contains the real mapped name. |
2301 |
|
push @mappedNameList, $mappedName; |
2302 |
|
# Finally, enable us to get back from the mapped name to the object name. |
2303 |
|
$mappedNameHash{$mappedName} = $objectName; |
2304 |
|
} |
2305 |
|
} |
2306 |
|
# Begin the SELECT suffix. It starts with |
2307 |
|
# |
2308 |
|
# FROM name1, name2, ... nameN |
2309 |
|
# |
2310 |
|
my $suffix = "FROM " . join(', ', @fromList); |
2311 |
|
# Check for a filter clause. |
2312 |
|
if ($filterClause) { |
2313 |
|
# Here we have one, so we convert its field names and add it to the query. First, |
2314 |
|
# We create a copy of the filter string we can work with. |
2315 |
|
my $filterString = $filterClause; |
2316 |
|
# Next, we sort the object names by length. This helps protect us from finding |
2317 |
|
# object names inside other object names when we're doing our search and replace. |
2318 |
|
my @sortedNames = sort { length($b) - length($a) } @mappedNameList; |
2319 |
|
# We will also keep a list of conditions to add to the WHERE clause in order to link |
2320 |
|
# entities and relationships as well as primary relations to secondary ones. |
2321 |
|
my @joinWhere = (); |
2322 |
|
# The final preparatory step is to create a hash table of relation names. The |
2323 |
|
# table begins with the relation names already in the SELECT command. We may |
2324 |
|
# need to add relations later if there is filtering on a field in a secondary |
2325 |
|
# relation. The secondary relations are the ones that contain multiply- |
2326 |
|
# occurring or optional fields. |
2327 |
|
my %fromNames = map { $_ => 1 } @sortedNames; |
2328 |
|
# We are ready to begin. We loop through the object names, replacing each |
2329 |
|
# object name's field references by the corresponding SQL field reference. |
2330 |
|
# Along the way, if we find a secondary relation, we will need to add it |
2331 |
|
# to the FROM clause. |
2332 |
|
for my $mappedName (@sortedNames) { |
2333 |
|
# Get the length of the object name plus 2. This is the value we add to the |
2334 |
|
# size of the field name to determine the size of the field reference as a |
2335 |
|
# whole. |
2336 |
|
my $nameLength = 2 + length $mappedName; |
2337 |
|
# Get the real object name for this mapped name. |
2338 |
|
my $objectName = $mappedNameHash{$mappedName}; |
2339 |
|
Trace("Processing $mappedName for object $objectName.") if T(4); |
2340 |
|
# Get the object's field list. |
2341 |
|
my $fieldList = $self->GetFieldTable($objectName); |
2342 |
|
# Find the field references for this object. |
2343 |
|
while ($filterString =~ m/$mappedName\(([^)]*)\)/g) { |
2344 |
|
# At this point, $1 contains the field name, and the current position |
2345 |
|
# is set immediately after the final parenthesis. We pull out the name of |
2346 |
|
# the field and the position and length of the field reference as a whole. |
2347 |
|
my $fieldName = $1; |
2348 |
|
my $len = $nameLength + length $fieldName; |
2349 |
|
my $pos = pos($filterString) - $len; |
2350 |
|
# Insure the field exists. |
2351 |
|
if (!exists $fieldList->{$fieldName}) { |
2352 |
|
Confess("Field $fieldName not found for object $objectName."); |
2353 |
|
} else { |
2354 |
|
Trace("Processing $fieldName at position $pos.") if T(4); |
2355 |
|
# Get the field's relation. |
2356 |
|
my $relationName = $fieldList->{$fieldName}->{relation}; |
2357 |
|
# Now we have a secondary relation. We need to insure it matches the |
2358 |
|
# mapped name of the primary relation. First we peel off the suffix |
2359 |
|
# from the mapped name. |
2360 |
|
my $mappingSuffix = substr $mappedName, length($objectName); |
2361 |
|
# Put the mapping suffix onto the relation name to get the |
2362 |
|
# mapped relation name. |
2363 |
|
my $mappedRelationName = "$relationName$mappingSuffix"; |
2364 |
|
# Insure the relation is in the FROM clause. |
2365 |
|
if (!exists $fromNames{$mappedRelationName}) { |
2366 |
|
# Add the relation to the FROM clause. |
2367 |
|
if ($mappedRelationName eq $relationName) { |
2368 |
|
# The name is un-mapped, so we add it without |
2369 |
|
# any frills. |
2370 |
|
$suffix .= ", $relationName"; |
2371 |
|
push @joinWhere, "$objectName.id = $relationName.id"; |
2372 |
|
} else { |
2373 |
|
# Here we have a mapping situation. |
2374 |
|
$suffix .= ", $relationName $mappedRelationName"; |
2375 |
|
push @joinWhere, "$mappedRelationName.id = $mappedName.id"; |
2376 |
|
} |
2377 |
|
# Denote we have this relation available for future fields. |
2378 |
|
$fromNames{$mappedRelationName} = 1; |
2379 |
|
} |
2380 |
|
# Form an SQL field reference from the relation name and the field name. |
2381 |
|
my $sqlReference = "$mappedRelationName." . _FixName($fieldName); |
2382 |
|
# Put it into the filter string in place of the old value. |
2383 |
|
substr($filterString, $pos, $len) = $sqlReference; |
2384 |
|
# Reposition the search. |
2385 |
|
pos $filterString = $pos + length $sqlReference; |
2386 |
|
} |
2387 |
|
} |
2388 |
|
} |
2389 |
|
# The next step is to join the objects together. We only need to do this if there |
2390 |
|
# is more than one object in the object list. We start with the first object and |
2391 |
|
# run through the objects after it. Note also that we make a safety copy of the |
2392 |
|
# list before running through it. |
2393 |
|
my @mappedObjectList = @mappedNameList; |
2394 |
|
my $lastMappedObject = shift @mappedObjectList; |
2395 |
|
# Get the join table. |
2396 |
|
my $joinTable = $self->{_metaData}->{Joins}; |
2397 |
|
# Loop through the object list. |
2398 |
|
for my $thisMappedObject (@mappedObjectList) { |
2399 |
|
# Look for a join using the real object names. |
2400 |
|
my $lastObject = $mappedNameHash{$lastMappedObject}; |
2401 |
|
my $thisObject = $mappedNameHash{$thisMappedObject}; |
2402 |
|
my $joinKey = "$lastObject/$thisObject"; |
2403 |
|
if (!exists $joinTable->{$joinKey}) { |
2404 |
|
# Here there's no join, so we throw an error. |
2405 |
|
Confess("No join exists to connect from $lastMappedObject to $thisMappedObject."); |
2406 |
|
} else { |
2407 |
|
# Get the join clause. |
2408 |
|
my $unMappedJoin = $joinTable->{$joinKey}; |
2409 |
|
# Fix the names. |
2410 |
|
$unMappedJoin =~ s/$lastObject/$lastMappedObject/; |
2411 |
|
$unMappedJoin =~ s/$thisObject/$thisMappedObject/; |
2412 |
|
push @joinWhere, $unMappedJoin; |
2413 |
|
# Save this object as the last object for the next iteration. |
2414 |
|
$lastMappedObject = $thisMappedObject; |
2415 |
|
} |
2416 |
|
} |
2417 |
|
# Now we need to handle the whole ORDER BY / LIMIT thing. The important part |
2418 |
|
# here is we want the filter clause to be empty if there's no WHERE filter. |
2419 |
|
# We'll put the ORDER BY / LIMIT clauses in the following variable. |
2420 |
|
my $orderClause = ""; |
2421 |
|
# Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy |
2422 |
|
# operator so that we find the first occurrence of either verb. |
2423 |
|
if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) { |
2424 |
|
# Here we have an ORDER BY or LIMIT verb. Split it off of the filter string. |
2425 |
|
my $pos = pos $filterString; |
2426 |
|
$orderClause = $2 . substr($filterString, $pos); |
2427 |
|
$filterString = $1; |
2428 |
|
} |
2429 |
|
# Add the filter and the join clauses (if any) to the SELECT command. |
2430 |
|
if ($filterString) { |
2431 |
|
Trace("Filter string is \"$filterString\".") if T(4); |
2432 |
|
push @joinWhere, "($filterString)"; |
2433 |
|
} |
2434 |
|
if (@joinWhere) { |
2435 |
|
$suffix .= " WHERE " . join(' AND ', @joinWhere); |
2436 |
|
} |
2437 |
|
# Add the sort or limit clause (if any) to the SELECT command. |
2438 |
|
if ($orderClause) { |
2439 |
|
$suffix .= " $orderClause"; |
2440 |
|
} |
2441 |
|
} |
2442 |
|
# Return the suffix, the mapped name list, and the mapped name hash. |
2443 |
|
return ($suffix, \@mappedNameList, \%mappedNameHash); |
2444 |
|
} |
2445 |
|
|
2446 |
Maximum number of records to return. If omitted or 0, all available records will be returned. |
=head3 GetStatementHandle |
2447 |
|
|
2448 |
|
This method will prepare and execute an SQL query, returning the statement handle. |
2449 |
|
The main reason for doing this here is so that everybody who does SQL queries gets |
2450 |
|
the benefit of tracing. |
2451 |
|
|
2452 |
|
This is an instance method. |
2453 |
|
|
2454 |
|
=over 4 |
2455 |
|
|
2456 |
|
=item command |
2457 |
|
|
2458 |
|
Command to prepare and execute. |
2459 |
|
|
2460 |
|
=item params |
2461 |
|
|
2462 |
|
Reference to a list of the values to be substituted in for the parameter marks. |
2463 |
|
|
2464 |
=item RETURN |
=item RETURN |
2465 |
|
|
2466 |
Returns a list of list references. Each element of the return list contains the values for the |
Returns a prepared and executed statement handle from which the caller can extract |
2467 |
fields specified in the B<fields> parameter. |
results. |
2468 |
|
|
2469 |
=back |
=back |
2470 |
|
|
2471 |
=cut |
=cut |
2472 |
#: Return Type @@; |
|
2473 |
sub GetAll { |
sub _GetStatementHandle { |
2474 |
# Get the parameters. |
# Get the parameters. |
2475 |
my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_; |
my ($self, $command, $params) = @_; |
2476 |
# Translate the parameters from a list reference to a list. If the parameter |
# Trace the query. |
2477 |
# list is a scalar we convert it into a singleton list. |
Trace("SQL query: $command") if T(SQL => 3); |
2478 |
my @parmList = (); |
Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0)); |
2479 |
if (ref $parameterList eq "ARRAY") { |
# Get the database handle. |
2480 |
@parmList = @{$parameterList}; |
my $dbh = $self->{_dbh}; |
2481 |
} else { |
# Prepare the command. |
2482 |
push @parmList, $parameterList; |
my $sth = $dbh->prepare_command($command); |
2483 |
} |
# Execute it with the parameters bound in. |
2484 |
# Create the query. |
$sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr()); |
2485 |
my $query = $self->Get($objectNames, $filterClause, @parmList); |
# Return the statement handle. |
2486 |
# Set up a counter of the number of records read. |
return $sth; |
|
my $fetched = 0; |
|
|
# Insure the counter has a value. |
|
|
if (!defined $count) { |
|
|
$count = 0; |
|
|
} |
|
|
# Loop through the records returned, extracting the fields. Note that if the |
|
|
# counter is non-zero, we stop when the number of records read hits the count. |
|
|
my @retVal = (); |
|
|
while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) { |
|
|
my @rowData = $row->Values($fields); |
|
|
push @retVal, \@rowData; |
|
|
$fetched++; |
|
|
} |
|
|
# Return the resulting list. |
|
|
return @retVal; |
|
2487 |
} |
} |
2488 |
|
|
|
=head2 Internal Utility Methods |
|
|
|
|
2489 |
=head3 GetLoadStats |
=head3 GetLoadStats |
2490 |
|
|
2491 |
Return a blank statistics object for use by the load methods. |
Return a blank statistics object for use by the load methods. |
2495 |
=cut |
=cut |
2496 |
|
|
2497 |
sub _GetLoadStats { |
sub _GetLoadStats { |
2498 |
return Stats->new('records'); |
return Stats->new(); |
2499 |
} |
} |
2500 |
|
|
2501 |
=head3 GenerateFields |
=head3 GenerateFields |
2690 |
return $objectData->{Relations}; |
return $objectData->{Relations}; |
2691 |
} |
} |
2692 |
|
|
|
=head3 GetFieldTable |
|
|
|
|
|
Get the field structure for a specified entity or relationship. |
|
|
|
|
|
This is an instance method. |
|
|
|
|
|
=over 4 |
|
|
|
|
|
=item objectName |
|
|
|
|
|
Name of the desired entity or relationship. |
|
|
|
|
|
=item RETURN |
|
|
|
|
|
The table containing the field descriptors for the specified object. |
|
|
|
|
|
=back |
|
|
|
|
|
=cut |
|
|
|
|
|
sub _GetFieldTable { |
|
|
# Get the parameters. |
|
|
my ($self, $objectName) = @_; |
|
|
# Get the descriptor from the metadata. |
|
|
my $objectData = $self->_GetStructure($objectName); |
|
|
# Return the object's field table. |
|
|
return $objectData->{Fields}; |
|
|
} |
|
|
|
|
2693 |
=head3 ValidateFieldNames |
=head3 ValidateFieldNames |
2694 |
|
|
2695 |
Determine whether or not the field names are valid. A description of the problems with the names |
Determine whether or not the field names are valid. A description of the problems with the names |
2830 |
sub _LoadMetaData { |
sub _LoadMetaData { |
2831 |
# Get the parameters. |
# Get the parameters. |
2832 |
my ($filename) = @_; |
my ($filename) = @_; |
2833 |
|
Trace("Reading Sprout DBD from $filename.") if T(2); |
2834 |
# Slurp the XML file into a variable. Extensive use of options is used to insure we |
# Slurp the XML file into a variable. Extensive use of options is used to insure we |
2835 |
# get the exact structure we want. |
# get the exact structure we want. |
2836 |
my $metadata = XML::Simple::XMLin($filename, |
my $metadata = XML::Simple::XMLin($filename, |
2858 |
for my $entityName (keys %{$entityList}) { |
for my $entityName (keys %{$entityList}) { |
2859 |
my $entityStructure = $entityList->{$entityName}; |
my $entityStructure = $entityList->{$entityName}; |
2860 |
# |
# |
2861 |
# The first step is to run creating all the entity's default values. For C<Field> elements, |
# The first step is to create all the entity's default values. For C<Field> elements, |
2862 |
# the relation name must be added where it is not specified. For relationships, |
# the relation name must be added where it is not specified. For relationships, |
2863 |
# the B<from-link> and B<to-link> fields must be inserted, and for entities an B<id> |
# the B<from-link> and B<to-link> fields must be inserted, and for entities an B<id> |
2864 |
# field must be added to each relation. Finally, each field will have a C<PrettySort> attribute |
# field must be added to each relation. Finally, each field will have a C<PrettySort> attribute |
3037 |
my @fromList = (); |
my @fromList = (); |
3038 |
my @toList = (); |
my @toList = (); |
3039 |
my @bothList = (); |
my @bothList = (); |
3040 |
Trace("Join table build for $entityName.") if T(3); |
Trace("Join table build for $entityName.") if T(metadata => 4); |
3041 |
for my $relationshipName (keys %{$relationshipList}) { |
for my $relationshipName (keys %{$relationshipList}) { |
3042 |
my $relationship = $relationshipList->{$relationshipName}; |
my $relationship = $relationshipList->{$relationshipName}; |
3043 |
# Determine if this relationship has our entity in one of its link fields. |
# Determine if this relationship has our entity in one of its link fields. |
3044 |
my $fromEntity = $relationship->{from}; |
my $fromEntity = $relationship->{from}; |
3045 |
my $toEntity = $relationship->{to}; |
my $toEntity = $relationship->{to}; |
3046 |
Trace("Join check for relationship $relationshipName from $fromEntity to $toEntity.") if T(3); |
Trace("Join check for relationship $relationshipName from $fromEntity to $toEntity.") if T(Joins => 4); |
3047 |
if ($fromEntity eq $entityName) { |
if ($fromEntity eq $entityName) { |
3048 |
if ($toEntity eq $entityName) { |
if ($toEntity eq $entityName) { |
3049 |
# Here the relationship is recursive. |
# Here the relationship is recursive. |
3050 |
push @bothList, $relationshipName; |
push @bothList, $relationshipName; |
3051 |
Trace("Relationship $relationshipName put in both-list.") if T(3); |
Trace("Relationship $relationshipName put in both-list.") if T(metadata => 4); |
3052 |
} else { |
} else { |
3053 |
# Here the relationship comes from the entity. |
# Here the relationship comes from the entity. |
3054 |
push @fromList, $relationshipName; |
push @fromList, $relationshipName; |
3055 |
Trace("Relationship $relationshipName put in from-list.") if T(3); |
Trace("Relationship $relationshipName put in from-list.") if T(metadata => 4); |
3056 |
} |
} |
3057 |
} elsif ($toEntity eq $entityName) { |
} elsif ($toEntity eq $entityName) { |
3058 |
# Here the relationship goes to the entity. |
# Here the relationship goes to the entity. |
3059 |
push @toList, $relationshipName; |
push @toList, $relationshipName; |
3060 |
Trace("Relationship $relationshipName put in to-list.") if T(3); |
Trace("Relationship $relationshipName put in to-list.") if T(metadata => 4); |
3061 |
} |
} |
3062 |
} |
} |
3063 |
# Create the nonrecursive joins. Note that we build two hashes for running |
# Create the nonrecursive joins. Note that we build two hashes for running |
3073 |
# Create joins between the entity and this relationship. |
# Create joins between the entity and this relationship. |
3074 |
my $linkField = "$relationshipName.${linkType}_link"; |
my $linkField = "$relationshipName.${linkType}_link"; |
3075 |
my $joinClause = "$entityName.id = $linkField"; |
my $joinClause = "$entityName.id = $linkField"; |
3076 |
Trace("Entity join clause is $joinClause for $entityName and $relationshipName.") if T(4); |
Trace("Entity join clause is $joinClause for $entityName and $relationshipName.") if T(metadata => 4); |
3077 |
$joinTable{"$entityName/$relationshipName"} = $joinClause; |
$joinTable{"$entityName/$relationshipName"} = $joinClause; |
3078 |
$joinTable{"$relationshipName/$entityName"} = $joinClause; |
$joinTable{"$relationshipName/$entityName"} = $joinClause; |
3079 |
# Create joins between this relationship and the other relationships. |
# Create joins between this relationship and the other relationships. |
3094 |
# relationship and itself are prohibited. |
# relationship and itself are prohibited. |
3095 |
my $relJoinClause = "$otherName.${otherType}_link = $linkField"; |
my $relJoinClause = "$otherName.${otherType}_link = $linkField"; |
3096 |
$joinTable{$joinKey} = $relJoinClause; |
$joinTable{$joinKey} = $relJoinClause; |
3097 |
Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(4); |
Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(metadata => 4); |
3098 |
} |
} |
3099 |
} |
} |
3100 |
} |
} |
3103 |
# relationship can only be ambiguous with another recursive relationship, |
# relationship can only be ambiguous with another recursive relationship, |
3104 |
# and the incoming relationship from the outer loop is never recursive. |
# and the incoming relationship from the outer loop is never recursive. |
3105 |
for my $otherName (@bothList) { |
for my $otherName (@bothList) { |
3106 |
Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(3); |
Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(metadata => 4); |
3107 |
# Join from the left. |
# Join from the left. |
3108 |
$joinTable{"$relationshipName/$otherName"} = |
$joinTable{"$relationshipName/$otherName"} = |
3109 |
"$linkField = $otherName.from_link"; |
"$linkField = $otherName.from_link"; |
3118 |
# rise to situations where we can't create the path we want; however, it is always |
# rise to situations where we can't create the path we want; however, it is always |
3119 |
# possible to get the same effect using multiple queries. |
# possible to get the same effect using multiple queries. |
3120 |
for my $relationshipName (@bothList) { |
for my $relationshipName (@bothList) { |
3121 |
Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(3); |
Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(metadata => 4); |
3122 |
# Join to the entity from each direction. |
# Join to the entity from each direction. |
3123 |
$joinTable{"$entityName/$relationshipName"} = |
$joinTable{"$entityName/$relationshipName"} = |
3124 |
"$entityName.id = $relationshipName.from_link"; |
"$entityName.id = $relationshipName.from_link"; |
3132 |
return $metadata; |
return $metadata; |
3133 |
} |
} |
3134 |
|
|
3135 |
|
=head3 SortNeeded |
3136 |
|
|
3137 |
|
C<< my $flag = $erdb->SortNeeded($relationName); >> |
3138 |
|
|
3139 |
|
Return TRUE if the specified relation should be sorted during loading to remove duplicate keys, |
3140 |
|
else FALSE. |
3141 |
|
|
3142 |
|
=over 4 |
3143 |
|
|
3144 |
|
=item relationName |
3145 |
|
|
3146 |
|
Name of the relation to be examined. |
3147 |
|
|
3148 |
|
=item RETURN |
3149 |
|
|
3150 |
|
Returns TRUE if the relation needs a sort, else FALSE. |
3151 |
|
|
3152 |
|
=back |
3153 |
|
|
3154 |
|
=cut |
3155 |
|
#: Return Type $; |
3156 |
|
sub SortNeeded { |
3157 |
|
# Get the parameters. |
3158 |
|
my ($self, $relationName) = @_; |
3159 |
|
# Declare the return variable. |
3160 |
|
my $retVal = 0; |
3161 |
|
# Find out if the relation is a primary entity relation. |
3162 |
|
my $entityTable = $self->{_metaData}->{Entities}; |
3163 |
|
if (exists $entityTable->{$relationName}) { |
3164 |
|
my $keyType = $entityTable->{$relationName}->{keyType}; |
3165 |
|
Trace("Relation $relationName found in entity table with key type $keyType.") if T(3); |
3166 |
|
# If the key is not a hash string, we must do the sort. |
3167 |
|
if ($keyType ne 'hash-string') { |
3168 |
|
$retVal = 1; |
3169 |
|
} |
3170 |
|
} |
3171 |
|
# Return the result. |
3172 |
|
return $retVal; |
3173 |
|
} |
3174 |
|
|
3175 |
=head3 CreateRelationshipIndex |
=head3 CreateRelationshipIndex |
3176 |
|
|
3177 |
Create an index for a relationship's relation. |
Create an index for a relationship's relation. |
3209 |
# index descriptor does not exist, it will be created automatically so we can add |
# index descriptor does not exist, it will be created automatically so we can add |
3210 |
# the field to it. |
# the field to it. |
3211 |
unshift @{$newIndex->{IndexFields}}, $firstField; |
unshift @{$newIndex->{IndexFields}}, $firstField; |
3212 |
|
# If this is a one-to-many relationship, the "To" index is unique. |
3213 |
|
if ($relationshipStructure->{arity} eq "1M" && $indexKey eq "To") { |
3214 |
|
$newIndex->{Unique} = 'true'; |
3215 |
|
} |
3216 |
# Add the index to the relation. |
# Add the index to the relation. |
3217 |
_AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex); |
_AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex); |
3218 |
} |
} |
3304 |
# Here we have a field list. Loop through its fields. |
# Here we have a field list. Loop through its fields. |
3305 |
my $fieldStructures = $structure->{Fields}; |
my $fieldStructures = $structure->{Fields}; |
3306 |
for my $fieldName (keys %{$fieldStructures}) { |
for my $fieldName (keys %{$fieldStructures}) { |
3307 |
|
Trace("Processing field $fieldName of $defaultRelationName.") if T(4); |
3308 |
my $fieldData = $fieldStructures->{$fieldName}; |
my $fieldData = $fieldStructures->{$fieldName}; |
3309 |
# Get the field type. |
# Get the field type. |
3310 |
my $type = $fieldData->{type}; |
my $type = $fieldData->{type}; |