[Bio] / Sprout / ERDB.pm Repository:
ViewVC logotype

Diff of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.1, Sun Jan 23 16:12:29 2005 UTC revision 1.45, Tue Jun 6 05:05:15 2006 UTC
# Line 1  Line 1 
1  package ERDB;  package ERDB;
2    
3          use strict;          use strict;
         use Carp;  
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    
# Line 33  Line 34 
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>),
# Line 67  Line 69 
69  was inserted by the L</InsertObject> method.  was inserted by the L</InsertObject> method.
70    
71  To facilitate testing, the ERDB module supports automatic generation of test data. This process  To facilitate testing, the ERDB module supports automatic generation of test data. This process
72  is described in the L</GenerateEntity> and L</GenerateConnection> methods.  is described in the L</GenerateEntity> and L</GenerateConnection> methods, though it is not yet
73    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    
# Line 76  Line 317 
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.
# Line 111  Line 357 
357    
358  =head3 new  =head3 new
359    
360  C<< my $database = ERDB::new($dbh, $metaFileName); >>  C<< my $database = ERDB->new($dbh, $metaFileName); >>
361    
362  Create a new ERDB object.  Create a new ERDB object.
363    
# Line 136  Line 382 
382          my $metaData = _LoadMetaData($metaFileName);          my $metaData = _LoadMetaData($metaFileName);
383          # Create the object.          # Create the object.
384          my $self = { _dbh => $dbh,          my $self = { _dbh => $dbh,
385                                   _metaData => $metaData,                   _metaData => $metaData
                                  _options => $options,  
386                             };                             };
387          # Bless and return it.          # Bless and return it.
388          bless $self;      bless $self, $class;
389          return $self;          return $self;
390  }  }
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.
# Line 163  Line 408 
408    
409  sub ShowMetaData {  sub ShowMetaData {
410          # Get the parameters.          # Get the parameters.
411          my $self = shift @_;      my ($self, $filename) = @_;
         my ($filename) = @_;  
412          # Get the metadata and the title string.          # Get the metadata and the title string.
413          my $metadata = $self->{_metaData};          my $metadata = $self->{_metaData};
414          # Get the title string.          # Get the title string.
# Line 174  Line 418 
418          my $relationshipList = $metadata->{Relationships};          my $relationshipList = $metadata->{Relationships};
419          # Open the output file.          # Open the output file.
420          open(HTMLOUT, ">$filename") || Confess("Could not open MetaData display file $filename: $!");          open(HTMLOUT, ">$filename") || Confess("Could not open MetaData display file $filename: $!");
421        Trace("Building MetaData table of contents.") if T(4);
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);
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.
# Line 220  Line 506 
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);
529                  # Get the relationship's structure.                  # Get the relationship's structure.
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};
# Line 253  Line 540 
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);
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          for my $joinKey (sort keys %{$joinTable}) {      my @joinKeys = keys %{$joinTable};
567        for my $joinKey (sort @joinKeys) {
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 ($source, $target, $clause) = ($self->ComputeObjectSentence($1),          my ($sourceRelation, $targetRelation) = ($1, $2);
571                                                                                    $self->ComputeObjectSentence($2),          Trace("Join with key $joinKey is from $sourceRelation to $targetRelation.") if T(Joins => 4);
572                                                                                    $joinTable->{$joinKey});          my $source = $self->ComputeObjectSentence($sourceRelation);
573            my $target = $self->ComputeObjectSentence($targetRelation);
574            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;  
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    
# Line 302  Line 592 
592    
593  sub DumpMetaData {  sub DumpMetaData {
594          # Get the parameters.          # Get the parameters.
595          my $self = shift @_;      my ($self) = @_;
596          # Dump the meta-data.          # Dump the meta-data.
597          return Data::Dumper::Dumper($self->{_metaData});          return Data::Dumper::Dumper($self->{_metaData});
598  }  }
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
# Line 320  Line 610 
610    
611  sub CreateTables {  sub CreateTables {
612          # Get the parameters.          # Get the parameters.
613          my $self = shift @_;      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          while (my ($entityName, $entityData) = each %{$metadata->{Entities}}) {      for my $relationName (@relNames) {
                 # 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    
# Line 355  Line 633 
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 = shift @_;      my ($self, $relationName, $indexFlag, $estimatedRows) = @_;
         my ($relationName, $indexFlag) = @_;  
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.
# Line 391  Line 674 
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) {
# Line 401  Line 690 
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] = md5_base64($fieldList->[$i]);
784            }
785        }
786    }
787    
788  =head3 CreateIndex  =head3 CreateIndex
789    
790  C<< $database->CreateIndex($relationName); >>  C<< $erdb->CreateIndex($relationName); >>
791    
792  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
793  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.
794  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
795  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.
796    
797  =cut  =cut
798    
799  sub CreateIndex {  sub CreateIndex {
800          # Get the parameters.          # Get the parameters.
801          my $self = shift @_;      my ($self, $relationName) = @_;
         my ($relationName) = @_;  
802          # Get the relation's descriptor.          # Get the relation's descriptor.
803          my $relationData = $self->_FindRelation($relationName);          my $relationData = $self->_FindRelation($relationName);
804          # Get the database handle.          # Get the database handle.
805          my $dbh = $self->{_dbh};          my $dbh = $self->{_dbh};
806          # Now we need to create this relation's indexes. We do this by looping through its index table.          # Now we need to create this relation's indexes. We do this by looping through its index table.
807          while (my ($indexName, $indexData) = each %{$relationData->{Indexes}}) {      my $indexHash = $relationData->{Indexes};
808        for my $indexName (keys %{$indexHash}) {
809            my $indexData = $indexHash->{$indexName};
810                  # Get the index's field list.                  # Get the index's field list.
811                  my @fieldList = _FixNames(@{$indexData->{IndexFields}});                  my @fieldList = _FixNames(@{$indexData->{IndexFields}});
812                  my $flds = join(', ', @fieldList);                  my $flds = join(', ', @fieldList);
813                  # Get the index's uniqueness flag.                  # Get the index's uniqueness flag.
814                  my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');                  my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');
815                  # Create the index.                  # Create the index.
816                  $dbh->create_index(idx => $indexName, tbl => $relationName, flds => $flds, unique => $unique);          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,
817                                        flds => $flds, unique => $unique);
818            if ($rv) {
819                  Trace("Index created: $indexName for $relationName ($flds)") if T(1);                  Trace("Index created: $indexName for $relationName ($flds)") if T(1);
820            } else {
821                Confess("Error creating index $indexName for $relationName using ($flds): " . $dbh->error_message());
822            }
823          }          }
824  }  }
825    
826  =head3 LoadTables  =head3 LoadTables
827    
828  C<< my $stats = $database->LoadTables($directoryName, $rebuild); >>  C<< my $stats = $erdb->LoadTables($directoryName, $rebuild); >>
829    
830  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
831  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;
# Line 471  Line 861 
861    
862  sub LoadTables {  sub LoadTables {
863          # Get the parameters.          # Get the parameters.
864          my $self = shift @_;      my ($self, $directoryName, $rebuild) = @_;
         my ($directoryName, $rebuild) = @_;  
865          # Start the timer.          # Start the timer.
866          my $startTime = gettimeofday;          my $startTime = gettimeofday;
867          # Clean any trailing slash from the directory name.          # Clean any trailing slash from the directory name.
868          $directoryName =~ s!/\\$!!;          $directoryName =~ s!/\\$!!;
869          # Declare the return variable.          # Declare the return variable.
870          my $retVal = Stats->new();          my $retVal = Stats->new();
871          # Get the metadata structure.      # Get the relation names.
872          my $metaData = $self->{_metaData};      my @relNames = $self->GetTableNames();
873          # 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}}) {  
874                          # Try to load this relation.                          # Try to load this relation.
875                          my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);                          my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);
876                          # Accumulate the statistics.                          # Accumulate the statistics.
877                          $retVal->Accumulate($result);                          $retVal->Accumulate($result);
878                  }                  }
         }  
         # 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);  
         }  
879          # Add the duration of the load to the statistical object.          # Add the duration of the load to the statistical object.
880          $retVal->Add('duration', gettimeofday - $startTime);          $retVal->Add('duration', gettimeofday - $startTime);
881          # Return the accumulated statistics.          # Return the accumulated statistics.
882          return $retVal;          return $retVal;
883  }  }
884    
885    
886  =head3 GetTableNames  =head3 GetTableNames
887    
888  C<< my @names = $database->GetTableNames; >>  C<< my @names = $erdb->GetTableNames; >>
889    
890  Return a list of the relations required to implement this database.  Return a list of the relations required to implement this database.
891    
# Line 514  Line 893 
893    
894  sub GetTableNames {  sub GetTableNames {
895          # Get the parameters.          # Get the parameters.
896          my $self = shift @_;      my ($self) = @_;
897          # Get the relation list from the metadata.          # Get the relation list from the metadata.
898          my $relationTable = $self->{_metaData}->{RelationTable};          my $relationTable = $self->{_metaData}->{RelationTable};
899          # Return the relation names.          # Return the relation names.
# Line 523  Line 902 
902    
903  =head3 GetEntityTypes  =head3 GetEntityTypes
904    
905  C<< my @names = $database->GetEntityTypes; >>  C<< my @names = $erdb->GetEntityTypes; >>
906    
907  Return a list of the entity type names.  Return a list of the entity type names.
908    
# Line 531  Line 910 
910    
911  sub GetEntityTypes {  sub GetEntityTypes {
912          # Get the database object.          # Get the database object.
913          my $self = shift @_;      my ($self) = @_;
914          # Get the entity list from the metadata object.          # Get the entity list from the metadata object.
915          my $entityList = $self->{_metaData}->{Entities};          my $entityList = $self->{_metaData}->{Entities};
916          # Return the list of entity names in alphabetical order.          # Return the list of entity names in alphabetical order.
917          return sort keys %{$entityList};          return sort keys %{$entityList};
918  }  }
919    
920    =head3 IsEntity
921    
922    C<< my $flag = $erdb->IsEntity($entityName); >>
923    
924    Return TRUE if the parameter is an entity name, else FALSE.
925    
926    =over 4
927    
928    =item entityName
929    
930    Object name to be tested.
931    
932    =item RETURN
933    
934    Returns TRUE if the specified string is an entity name, else FALSE.
935    
936    =back
937    
938    =cut
939    
940    sub IsEntity {
941        # Get the parameters.
942        my ($self, $entityName) = @_;
943        # Test to see if it's an entity.
944        return exists $self->{_metaData}->{Entities}->{$entityName};
945    }
946    
947  =head3 Get  =head3 Get
948    
949  C<< my $query = $database->Get(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>  C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>
950    
951  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.
952  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
# Line 548  Line 954 
954  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
955  $genus.  $genus.
956    
957  C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", $genus); >>  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>
958    
959  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
960  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
961    
962  C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>
963    
964  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
965  characters inside the variable C<$genus>.  characters inside the variable C<$genus>.
# Line 565  Line 971 
971  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
972  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,
973    
974  C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", $genus); >>  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>
975    
976  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
977  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.
978  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
979  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
980  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  
981  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,
982  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.
983    
984    If an entity or relationship is mentioned twice, the name for the second occurrence will
985    be suffixed with C<2>, the third occurrence will be suffixed with C<3>, and so forth. So,
986    for example, if we have C<['Feature', 'HasContig', 'Contig', 'HasContig']>, then the
987    B<to-link> field of the first B<HasContig> is specified as C<HasContig(to-link)>, while
988    the B<to-link> field of the second B<HasContig> is specified as C<HasContig2(to-link)>.
989    
990  =over 4  =over 4
991    
992  =item objectNames  =item objectNames
# Line 598  Line 1009 
1009    
1010  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>
1011    
1012    Note that the case is important. Only an uppercase "ORDER BY" with a single space will
1013    be processed. The idea is to make it less likely to find the verb by accident.
1014    
1015  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
1016  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
1017  relation.  relation.
1018    
1019  =item param1, param2, ..., paramN  Finally, you can limit the number of rows returned by adding a LIMIT clause. The LIMIT must
1020    be the last thing in the filter clause, and it contains only the word "LIMIT" followed by
1021    a positive number. So, for example
1022    
1023    C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>
1024    
1025    will only return the first ten genomes for the specified genus. The ORDER BY clause is not
1026    required. For example, to just get the first 10 genomes in the B<Genome> table, you could
1027    use
1028    
1029  Parameter values to be substituted into the filter clause.  C<< "LIMIT 10" >>
1030    
1031    =item params
1032    
1033    Reference to a list of parameter values to be substituted into the filter clause.
1034    
1035  =item RETURN  =item RETURN
1036    
# Line 616  Line 1042 
1042    
1043  sub Get {  sub Get {
1044          # Get the parameters.          # Get the parameters.
1045          my $self = shift @_;      my ($self, $objectNames, $filterClause, $params) = @_;
1046          my ($objectNames, $filterClause, @params) = @_;      # Process the SQL stuff.
1047          # Construct the SELECT statement. The general pattern is      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1048          #          $self->_SetupSQL($objectNames, $filterClause);
1049          # SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN      # Create the query.
1050          #      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .
1051          my $dbh = $self->{_dbh};          ".* $suffix";
1052          my $command = "SELECT DISTINCT " . join('.*, ', @{$objectNames}) . ".* FROM " .      my $sth = $self->_GetStatementHandle($command, $params);
1053                                  join(', ', @{$objectNames});      # Now we create the relation map, which enables DBQuery to determine the order, name
1054          # Check for a filter clause.      # and mapped name for each object in the query.
1055          if ($filterClause) {      my @relationMap = ();
1056                  # Here we have one, so we convert its field names and add it to the query. First,      for my $mappedName (@{$mappedNameListRef}) {
1057                  # We create a copy of the filter string we can work with.          push @relationMap, [$mappedName, $mappedNameHashRef->{$mappedName}];
                 my $filterString = $filterClause;  
                 # 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;  
1058                  }                  }
1059                  # We are ready to begin. We loop through the object names, replacing each      # Return the statement object.
1060                  # object name's field references by the corresponding SQL field reference.      my $retVal = DBQuery::_new($self, $sth, \@relationMap);
1061                  # 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;  
1062                                          }                                          }
1063                                          # Form an SQL field reference from the relation name and the field name.  
1064                                          my $sqlReference = "$relationName." . _FixName($fieldName);  =head3 GetFlat
1065                                          # Put it into the filter string in place of the old value.  
1066                                          substr($filterString, $pos, $len) = $sqlReference;  C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>
1067                                          # Reposition the search.  
1068                                          pos $filterString = $pos + length $sqlReference;  This is a variation of L</GetAll> that asks for only a single field per record and
1069    returns a single flattened list.
1070    
1071    =over 4
1072    
1073    =item objectNames
1074    
1075    List containing the names of the entity and relationship objects to be retrieved.
1076    
1077    =item filterClause
1078    
1079    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1080    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1081    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1082    parameter list as additional parameters. The fields in a filter clause can come from primary
1083    entity relations, relationship relations, or secondary entity relations; however, all of the
1084    entities and relationships involved must be included in the list of object names.
1085    
1086    =item parameterList
1087    
1088    List of the parameters to be substituted in for the parameters marks in the filter clause.
1089    
1090    =item field
1091    
1092    Name of the field to be used to get the elements of the list returned.
1093    
1094    =item RETURN
1095    
1096    Returns a list of values.
1097    
1098    =back
1099    
1100    =cut
1101    #: Return Type @;
1102    sub GetFlat {
1103        # Get the parameters.
1104        my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
1105        # Construct the query.
1106        my $query = $self->Get($objectNames, $filterClause, $parameterList);
1107        # Create the result list.
1108        my @retVal = ();
1109        # Loop through the records, adding the field values found to the result list.
1110        while (my $row = $query->Fetch()) {
1111            push @retVal, $row->Value($field);
1112                                  }                                  }
1113        # Return the list created.
1114        return @retVal;
1115                          }                          }
1116    
1117    =head3 Delete
1118    
1119    C<< my $stats = $erdb->Delete($entityName, $objectID); >>
1120    
1121    Delete an entity instance from the database. The instance is deleted along with all entity and
1122    relationship instances dependent on it. The idea of dependence here is recursive. An object is
1123    always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many
1124    relationship connected to a dependent entity or the "to" entity connected to a 1-to-many
1125    dependent relationship.
1126    
1127    =over 4
1128    
1129    =item entityName
1130    
1131    Name of the entity type for the instance being deleted.
1132    
1133    =item objectID
1134    
1135    ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),
1136    then it is presumed to by a LIKE pattern.
1137    
1138    =item testFlag
1139    
1140    If TRUE, the delete statements will be traced without being executed.
1141    
1142    =item RETURN
1143    
1144    Returns a statistics object indicating how many records of each particular table were
1145    deleted.
1146    
1147    =back
1148    
1149    =cut
1150    #: Return Type $%;
1151    sub Delete {
1152        # Get the parameters.
1153        my ($self, $entityName, $objectID, $testFlag) = @_;
1154        # Declare the return variable.
1155        my $retVal = Stats->new();
1156        # Get the DBKernel object.
1157        my $db = $self->{_dbh};
1158        # We're going to generate all the paths branching out from the starting entity. One of
1159        # the things we have to be careful about is preventing loops. We'll use a hash to
1160        # determine if we've hit a loop.
1161        my %alreadyFound = ();
1162        # These next lists will serve as our result stack. We start by pushing object lists onto
1163        # the stack, and then popping them off to do the deletes. This means the deletes will
1164        # start with the longer paths before getting to the shorter ones. That, in turn, makes
1165        # sure we don't delete records that might be needed to forge relationships back to the
1166        # original item. We have two lists-- one for TO-relationships, and one for
1167        # FROM-relationships and entities.
1168        my @fromPathList = ();
1169        my @toPathList = ();
1170        # This final hash is used to remember what work still needs to be done. We push paths
1171        # onto the list, then pop them off to extend the paths. We prime it with the starting
1172        # point. Note that we will work hard to insure that the last item on a path in the
1173        # TODO list is always an entity.
1174        my @todoList = ([$entityName]);
1175        while (@todoList) {
1176            # Get the current path.
1177            my $current = pop @todoList;
1178            # Copy it into a list.
1179            my @stackedPath = @{$current};
1180            # Pull off the last item on the path. It will always be an entity.
1181            my $entityName = pop @stackedPath;
1182            # Add it to the alreadyFound list.
1183            $alreadyFound{$entityName} = 1;
1184            # Get the entity data.
1185            my $entityData = $self->_GetStructure($entityName);
1186            # The first task is to loop through the entity's relation. A DELETE command will
1187            # be needed for each of them.
1188            my $relations = $entityData->{Relations};
1189            for my $relation (keys %{$relations}) {
1190                my @augmentedList = (@stackedPath, $relation);
1191                push @fromPathList, \@augmentedList;
1192            }
1193            # Now we need to look for relationships connected to this entity.
1194            my $relationshipList = $self->{_metaData}->{Relationships};
1195            for my $relationshipName (keys %{$relationshipList}) {
1196                my $relationship = $relationshipList->{$relationshipName};
1197                # Check the FROM field. We're only interested if it's us.
1198                if ($relationship->{from} eq $entityName) {
1199                    # Add the path to this relationship.
1200                    my @augmentedList = (@stackedPath, $entityName, $relationshipName);
1201                    push @fromPathList, \@augmentedList;
1202                    # Check the arity. If it's MM we're done. If it's 1M
1203                    # and the target hasn't been seen yet, we want to
1204                    # stack the entity for future processing.
1205                    if ($relationship->{arity} eq '1M') {
1206                        my $toEntity = $relationship->{to};
1207                        if (! exists $alreadyFound{$toEntity}) {
1208                            # Here we have a new entity that's dependent on
1209                            # the current entity, so we need to stack it.
1210                            my @stackList = (@augmentedList, $toEntity);
1211                            push @fromPathList, \@stackList;
1212                        } else {
1213                            Trace("$toEntity ignored because it occurred previously.") if T(4);
1214                  }                  }
1215                  # The next step is to join the objects together. We only need to do this if there                  }
1216                  # is more than one object in the object list. We start with the first object and              }
1217                  # run through the objects after it. Note also that we make a safety copy of the              # Now check the TO field. In this case only the relationship needs
1218                  # list before running through it.              # deletion.
1219                  my @objectList = @{$objectNames};              if ($relationship->{to} eq $entityName) {
1220                  my $lastObject = shift @objectList;                  my @augmentedList = (@stackedPath, $entityName, $relationshipName);
1221                  # Get the join table.                  push @toPathList, \@augmentedList;
1222                  my $joinTable = $self->{_metaData}->{Joins};              }
1223                  # Loop through the object list.          }
1224                  for my $thisObject (@objectList) {      }
1225                          # Look for a join.      # Create the first qualifier for the WHERE clause. This selects the
1226                          my $joinKey = "$lastObject/$thisObject";      # keys of the primary entity records to be deleted. When we're deleting
1227                          if (!exists $joinTable->{$joinKey}) {      # from a dependent table, we construct a join page from the first qualifier
1228                                  # Here there's no join, so we throw an error.      # to the table containing the dependent records to delete.
1229                                  Confess("No join exists to connect from $lastObject to $thisObject.");      my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");
1230        # We need to make two passes. The first is through the to-list, and
1231        # the second through the from-list. The from-list is second because
1232        # the to-list may need to pass through some of the entities the
1233        # from-list would delete.
1234        my %stackList = ( from_link => \@fromPathList, to_link => \@toPathList );
1235        # Now it's time to do the deletes. We do it in two passes.
1236        for my $keyName ('to_link', 'from_link') {
1237            # Get the list for this key.
1238            my @pathList = @{$stackList{$keyName}};
1239            Trace(scalar(@pathList) . " entries in path list for $keyName.") if T(3);
1240            # Loop through this list.
1241            while (my $path = pop @pathList) {
1242                # Get the table whose rows are to be deleted.
1243                my @pathTables = @{$path};
1244                # Start the DELETE statement. We need to call DBKernel because the
1245                # syntax of a DELETE-USING varies among DBMSs.
1246                my $target = $pathTables[$#pathTables];
1247                my $stmt = $db->SetUsing(@pathTables);
1248                # Now start the WHERE. The first thing is the ID field from the starting table. That
1249                # starting table will either be the entity relation or one of the entity's
1250                # sub-relations.
1251                $stmt .= " WHERE $pathTables[0].id $qualifier";
1252                # Now we run through the remaining entities in the path, connecting them up.
1253                for (my $i = 1; $i <= $#pathTables; $i += 2) {
1254                    # Connect the current relationship to the preceding entity.
1255                    my ($entity, $rel) = @pathTables[$i-1,$i];
1256                    # The style of connection depends on the direction of the relationship.
1257                    $stmt .= " AND $entity.id = $rel.$keyName";
1258                    if ($i + 1 <= $#pathTables) {
1259                        # Here there's a next entity, so connect that to the relationship's
1260                        # to-link.
1261                        my $entity2 = $pathTables[$i+1];
1262                        $stmt .= " AND $rel.to_link = $entity2.id";
1263                    }
1264                }
1265                # Now we have our desired DELETE statement.
1266                if ($testFlag) {
1267                    # Here the user wants to trace without executing.
1268                    Trace($stmt) if T(0);
1269                          } else {                          } else {
1270                                  # Get the join clause and add it to the WHERE list.                  # Here we can delete. Note that the SQL method dies with a confessing
1271                                  push @joinWhere, $joinTable->{$joinKey};                  # if an error occurs, so we just go ahead and do it.
1272                                  # Save this object as the last object for the next iteration.                  Trace("Executing delete from $target using '$objectID'.") if T(3);
1273                                  $lastObject = $thisObject;                  my $rv = $db->SQL($stmt, 0, $objectID);
1274                    # Accumulate the statistics for this delete. The only rows deleted
1275                    # are from the target table, so we use its name to record the
1276                    # statistic.
1277                    $retVal->Add($target, $rv);
1278                          }                          }
1279                  }                  }
                 # 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;  
1280                  }                  }
1281                  # Add the filter and the join clauses (if any) to the SELECT command.      # Return the result.
1282                  if ($filterString) {      return $retVal;
                         push @joinWhere, "($filterString)";  
1283                  }                  }
1284                  if (@joinWhere) {  
1285                          $command .= " WHERE " . join(' AND ', @joinWhere);  =head3 GetList
1286    
1287    C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>
1288    
1289    Return a list of object descriptors for the specified objects as determined by the
1290    specified filter clause.
1291    
1292    This method is essentially the same as L</Get> except it returns a list of objects rather
1293    than a query object that can be used to get the results one record at a time.
1294    
1295    =over 4
1296    
1297    =item objectNames
1298    
1299    List containing the names of the entity and relationship objects to be retrieved.
1300    
1301    =item filterClause
1302    
1303    WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1304    be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
1305    specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
1306    in the filter clause should be added to the parameter list as additional parameters. The
1307    fields in a filter clause can come from primary entity relations, relationship relations,
1308    or secondary entity relations; however, all of the entities and relationships involved must
1309    be included in the list of object names.
1310    
1311    The filter clause can also specify a sort order. To do this, simply follow the filter string
1312    with an ORDER BY clause. For example, the following filter string gets all genomes for a
1313    particular genus and sorts them by species name.
1314    
1315    C<< "Genome(genus) = ? ORDER BY Genome(species)" >>
1316    
1317    The rules for field references in a sort order are the same as those for field references in the
1318    filter clause in general; however, odd things may happen if a sort field is from a secondary
1319    relation.
1320    
1321    =item params
1322    
1323    Reference to a list of parameter values to be substituted into the filter clause.
1324    
1325    =item RETURN
1326    
1327    Returns a list of B<DBObject>s that satisfy the query conditions.
1328    
1329    =back
1330    
1331    =cut
1332    #: Return Type @%
1333    sub GetList {
1334        # Get the parameters.
1335        my ($self, $objectNames, $filterClause, $params) = @_;
1336        # Declare the return variable.
1337        my @retVal = ();
1338        # Perform the query.
1339        my $query = $self->Get($objectNames, $filterClause, $params);
1340        # Loop through the results.
1341        while (my $object = $query->Fetch) {
1342            push @retVal, $object;
1343                  }                  }
1344                  # Add the sort clause (if any) to the SELECT command.      # Return the result.
1345                  if ($orderClause) {      return @retVal;
                         $command .= " ORDER BY $orderClause";  
1346                  }                  }
1347    
1348    =head3 GetCount
1349    
1350    C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>
1351    
1352    Return the number of rows found by a specified query. This method would
1353    normally be used to count the records in a single table. For example, in a
1354    genetics database
1355    
1356        my $count = $erdb->GetCount(['Genome'], 'Genome(genus-species) LIKE ?', ['homo %']);
1357    
1358    would return the number of genomes for the genus I<homo>. It is conceivable, however,
1359    to use it to return records based on a join. For example,
1360    
1361        my $count = $erdb->GetCount(['Feature', 'Genome'], 'Genome(genus-species) LIKE ?',
1362                                    ['homo %']);
1363    
1364    would return the number of features for genomes in the genus I<homo>. Note that
1365    only the rows from the first table are counted. If the above command were
1366    
1367        my $count = $erdb->GetCount(['Genome', 'Feature'], 'Genome(genus-species) LIKE ?',
1368                                    ['homo %']);
1369    
1370    it would return the number of genomes, not the number of genome/feature pairs.
1371    
1372    =over 4
1373    
1374    =item objectNames
1375    
1376    Reference to a list of the objects (entities and relationships) included in the
1377    query.
1378    
1379    =item filter
1380    
1381    A filter clause for restricting the query. The rules are the same as for the L</Get>
1382    method.
1383    
1384    =item params
1385    
1386    Reference to a list of the parameter values to be substituted for the parameter marks
1387    in the filter.
1388    
1389    =item RETURN
1390    
1391    Returns a count of the number of records in the first table that would satisfy
1392    the query.
1393    
1394    =back
1395    
1396    =cut
1397    
1398    sub GetCount {
1399        # Get the parameters.
1400        my ($self, $objectNames, $filter, $params) = @_;
1401        # Declare the return variable.
1402        my $retVal;
1403        # Create the SQL command suffix to get the desired records.
1404        my ($suffix, $mappedNameListRef, $mappedNameHashRef) = $self->_SetupSQL($objectNames,
1405                                                                                $filter);
1406        # Prefix it with text telling it we want a record count.
1407        my $firstObject = $mappedNameListRef->[0];
1408        my $command = "SELECT COUNT($firstObject.id) $suffix";
1409        # Prepare and execute the command.
1410        my $sth = $self->_GetStatementHandle($command, $params);
1411        # Get the count value.
1412        ($retVal) = $sth->fetchrow_array();
1413        # Check for a problem.
1414        if (! defined($retVal)) {
1415            if ($sth->err) {
1416                # Here we had an SQL error.
1417                Confess("Error retrieving row count: " . $sth->errstr());
1418            } else {
1419                # Here we have no result.
1420                Confess("No result attempting to retrieve row count.");
1421          }          }
1422          Trace("SQL query: $command") if T(2);      }
1423          Trace("PARMS: '" . (join "', '", @params) . "'") if (T(3) && (@params > 0));      # Return the result.
         my $sth = $dbh->prepare_command($command);  
         # 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});  
1424          return $retVal;          return $retVal;
1425  }  }
1426    
1427  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
1428    
1429  C<< my $sentence = $database->ComputeObjectSentence($objectName); >>  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>
1430    
1431  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.
1432    
# Line 761  Line 1446 
1446    
1447  sub ComputeObjectSentence {  sub ComputeObjectSentence {
1448          # Get the parameters.          # Get the parameters.
1449          my $self = shift @_;      my ($self, $objectName) = @_;
         my ($objectName) = @_;  
1450          # Set the default return value.          # Set the default return value.
1451          my $retVal = $objectName;          my $retVal = $objectName;
1452          # Look for the object as a relationship.          # Look for the object as a relationship.
# Line 777  Line 1461 
1461    
1462  =head3 DumpRelations  =head3 DumpRelations
1463    
1464  C<< $database->DumpRelations($outputDirectory); >>  C<< $erdb->DumpRelations($outputDirectory); >>
1465    
1466  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.
1467  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.
# Line 794  Line 1478 
1478    
1479  sub DumpRelations {  sub DumpRelations {
1480          # Get the parameters.          # Get the parameters.
1481          my $self = shift @_;      my ($self, $outputDirectory) = @_;
         my ($outputDirectory) = @_;  
1482          # Now we need to run through all the relations. First, we loop through the entities.          # Now we need to run through all the relations. First, we loop through the entities.
1483          my $metaData = $self->{_metaData};          my $metaData = $self->{_metaData};
1484          my $entities = $metaData->{Entities};          my $entities = $metaData->{Entities};
1485          while (my ($entityName, $entityStructure) = each %{$entities}) {      for my $entityName (keys %{$entities}) {
1486            my $entityStructure = $entities->{$entityName};
1487                  # Get the entity's relations.                  # Get the entity's relations.
1488                  my $relationList = $entityStructure->{Relations};                  my $relationList = $entityStructure->{Relations};
1489                  # Loop through the relations, dumping them.                  # Loop through the relations, dumping them.
1490                  while (my ($relationName, $relation) = each %{$relationList}) {          for my $relationName (keys %{$relationList}) {
1491                my $relation = $relationList->{$relationName};
1492                          $self->_DumpRelation($outputDirectory, $relationName, $relation);                          $self->_DumpRelation($outputDirectory, $relationName, $relation);
1493                  }                  }
1494          }          }
1495          # Next, we loop through the relationships.          # Next, we loop through the relationships.
1496          my $relationships = $metaData->{Relationships};          my $relationships = $metaData->{Relationships};
1497          while (my ($relationshipName, $relationshipStructure) = each %{$relationships}) {      for my $relationshipName (keys %{$relationships}) {
1498            my $relationshipStructure = $relationships->{$relationshipName};
1499                  # Dump this relationship's relation.                  # Dump this relationship's relation.
1500                  $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});                  $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});
1501          }          }
# Line 817  Line 1503 
1503    
1504  =head3 InsertObject  =head3 InsertObject
1505    
1506  C<< my $ok = $database->InsertObject($objectType, \%fieldHash); >>  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>
1507    
1508  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
1509  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.
# Line 826  Line 1512 
1512  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
1513  C<ZP_00210270.1> and C<gi|46206278>.  C<ZP_00210270.1> and C<gi|46206278>.
1514    
1515  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']}); >>
1516    
1517  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
1518  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>.
1519    
1520  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'}); >>
1521    
1522  =over 4  =over 4
1523    
# Line 853  Line 1539 
1539    
1540  sub InsertObject {  sub InsertObject {
1541          # Get the parameters.          # Get the parameters.
1542          my $self = shift @_;      my ($self, $newObjectType, $fieldHash) = @_;
         my ($newObjectType, $fieldHash) = @_;  
1543          # Denote that so far we appear successful.          # Denote that so far we appear successful.
1544          my $retVal = 1;          my $retVal = 1;
1545          # Get the database handle.          # Get the database handle.
# Line 864  Line 1549 
1549          # Loop through the relations. We'll build insert statements for each one. If a relation is          # Loop through the relations. We'll build insert statements for each one. If a relation is
1550          # secondary, we may end up generating multiple insert statements. If an error occurs, we          # secondary, we may end up generating multiple insert statements. If an error occurs, we
1551          # stop the loop.          # stop the loop.
1552          while ($retVal && (my ($relationName, $relationDefinition) = each %{$relationTable})) {      my @relationList = keys %{$relationTable};
1553        for (my $i = 0; $retVal && $i <= $#relationList; $i++) {
1554            my $relationName = $relationList[$i];
1555            my $relationDefinition = $relationTable->{$relationName};
1556                  # Get the relation's fields. For each field we will collect a value in the corresponding                  # Get the relation's fields. For each field we will collect a value in the corresponding
1557                  # position of the @valueList array. If one of the fields is missing, we will add it to the                  # position of the @valueList array. If one of the fields is missing, we will add it to the
1558                  # @missing list.                  # @missing list.
# Line 952  Line 1640 
1640          return $retVal;          return $retVal;
1641  }  }
1642    
1643  =head3 LoadTable  =head3 LoadTable
1644    
1645    C<< my %results = $erdb->LoadTable($fileName, $relationName, $truncateFlag); >>
1646    
1647    Load data from a tab-delimited file into a specified table, optionally re-creating the table
1648    first.
1649    
1650    =over 4
1651    
1652    =item fileName
1653    
1654    Name of the file from which the table data should be loaded.
1655    
1656    =item relationName
1657    
1658    Name of the relation to be loaded. This is the same as the table name.
1659    
1660    =item truncateFlag
1661    
1662    TRUE if the table should be dropped and re-created, else FALSE
1663    
1664    =item RETURN
1665    
1666    Returns a statistical object containing a list of the error messages.
1667    
1668    =back
1669    
1670    =cut
1671    sub LoadTable {
1672        # Get the parameters.
1673        my ($self, $fileName, $relationName, $truncateFlag) = @_;
1674        # Create the statistical return object.
1675        my $retVal = _GetLoadStats();
1676        # Trace the fact of the load.
1677        Trace("Loading table $relationName from $fileName") if T(2);
1678        # Get the database handle.
1679        my $dbh = $self->{_dbh};
1680        # Get the input file size.
1681        my $fileSize = -s $fileName;
1682        # Get the relation data.
1683        my $relation = $self->_FindRelation($relationName);
1684        # Check the truncation flag.
1685        if ($truncateFlag) {
1686            Trace("Creating table $relationName") if T(2);
1687            # Compute the row count estimate. We take the size of the load file,
1688            # divide it by the estimated row size, and then multiply by 1.5 to
1689            # leave extra room. We postulate a minimum row count of 1000 to
1690            # prevent problems with incoming empty load files.
1691            my $rowSize = $self->EstimateRowSize($relationName);
1692            my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);
1693            # Re-create the table without its index.
1694            $self->CreateTable($relationName, 0, $estimate);
1695            # If this is a pre-index DBMS, create the index here.
1696            if ($dbh->{_preIndex}) {
1697                eval {
1698                    $self->CreateIndex($relationName);
1699                };
1700                if ($@) {
1701                    $retVal->AddMessage($@);
1702                }
1703            }
1704        }
1705        # Load the table.
1706        my $rv;
1707        eval {
1708            $rv = $dbh->load_table(file => $fileName, tbl => $relationName);
1709        };
1710        if (!defined $rv) {
1711            $retVal->AddMessage($@) if ($@);
1712            $retVal->AddMessage("Table load failed for $relationName using $fileName.");
1713            Trace("Table load failed for $relationName.") if T(1);
1714        } else {
1715            # Here we successfully loaded the table.
1716            $retVal->Add("tables");
1717            my $size = -s $fileName;
1718            Trace("$size bytes loaded into $relationName.") if T(2);
1719            # If we're rebuilding, we need to create the table indexes.
1720            if ($truncateFlag && ! $dbh->{_preIndex}) {
1721                eval {
1722                    $self->CreateIndex($relationName);
1723                };
1724                if ($@) {
1725                    $retVal->AddMessage($@);
1726                }
1727            }
1728        }
1729        # Analyze the table to improve performance.
1730        $dbh->vacuum_it($relationName);
1731        # Return the statistics.
1732        return $retVal;
1733    }
1734    
1735    =head3 GenerateEntity
1736    
1737    C<< my $fieldHash = $erdb->GenerateEntity($id, $type, \%values); >>
1738    
1739    Generate the data for a new entity instance. This method creates a field hash suitable for
1740    passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest
1741    of the fields are generated using information in the database schema.
1742    
1743    Each data type has a default algorithm for generating random test data. This can be overridden
1744    by including a B<DataGen> element in the field. If this happens, the content of the element is
1745    executed as a PERL program in the context of this module. The element may make use of a C<$this>
1746    variable which contains the field hash as it has been built up to the current point. If any
1747    fields are dependent on other fields, the C<pass> attribute can be used to control the order
1748    in which the fields are generated. A field with a high data pass number will be generated after
1749    a field with a lower one. If any external values are needed, they should be passed in via the
1750    optional third parameter, which will be available to the data generation script under the name
1751    C<$value>. Several useful utility methods are provided for generating random values, including
1752    L</IntGen>, L</StringGen>, L</FloatGen>, and L</DateGen>. Note that dates are stored and generated
1753    in the form of a timestamp number rather than a string.
1754    
1755    =over 4
1756    
1757    =item id
1758    
1759    ID to assign to the new entity.
1760    
1761    =item type
1762    
1763    Type name for the new entity.
1764    
1765    =item values
1766    
1767    Hash containing additional values that might be needed by the data generation methods (optional).
1768    
1769    =back
1770    
1771    =cut
1772    
1773    sub GenerateEntity {
1774        # Get the parameters.
1775        my ($self, $id, $type, $values) = @_;
1776        # Create the return hash.
1777        my $this = { id => $id };
1778        # Get the metadata structure.
1779        my $metadata = $self->{_metaData};
1780        # Get this entity's list of fields.
1781        if (!exists $metadata->{Entities}->{$type}) {
1782            Confess("Unrecognized entity type $type in GenerateEntity.");
1783        } else {
1784            my $entity = $metadata->{Entities}->{$type};
1785            my $fields = $entity->{Fields};
1786            # Generate data from the fields.
1787            _GenerateFields($this, $fields, $type, $values);
1788        }
1789        # Return the hash created.
1790        return $this;
1791    }
1792    
1793    =head3 GetEntity
1794    
1795    C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >>
1796    
1797    Return an object describing the entity instance with a specified ID.
1798    
1799    =over 4
1800    
1801    =item entityType
1802    
1803    Entity type name.
1804    
1805    =item ID
1806    
1807    ID of the desired entity.
1808    
1809    =item RETURN
1810    
1811    Returns a B<DBObject> representing the desired entity instance, or an undefined value if no
1812    instance is found with the specified key.
1813    
1814    =back
1815    
1816    =cut
1817    
1818    sub GetEntity {
1819        # Get the parameters.
1820        my ($self, $entityType, $ID) = @_;
1821        # Create a query.
1822        my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
1823        # Get the first (and only) object.
1824        my $retVal = $query->Fetch();
1825        # Return the result.
1826        return $retVal;
1827    }
1828    
1829    =head3 GetEntityValues
1830    
1831    C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>
1832    
1833    Return a list of values from a specified entity instance.
1834    
1835    =over 4
1836    
1837    =item entityType
1838    
1839    Entity type name.
1840    
1841    =item ID
1842    
1843    ID of the desired entity.
1844    
1845    =item fields
1846    
1847    List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.
1848    
1849    =item RETURN
1850    
1851    Returns a flattened list of the values of the specified fields for the specified entity.
1852    
1853    =back
1854    
1855    =cut
1856    
1857    sub GetEntityValues {
1858        # Get the parameters.
1859        my ($self, $entityType, $ID, $fields) = @_;
1860        # Get the specified entity.
1861        my $entity = $self->GetEntity($entityType, $ID);
1862        # Declare the return list.
1863        my @retVal = ();
1864        # If we found the entity, push the values into the return list.
1865        if ($entity) {
1866            push @retVal, $entity->Values($fields);
1867        }
1868        # Return the result.
1869        return @retVal;
1870    }
1871    
1872    =head3 GetAll
1873    
1874    C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>
1875    
1876    Return a list of values taken from the objects returned by a query. The first three
1877    parameters correspond to the parameters of the L</Get> method. The final parameter is
1878    a list of the fields desired from each record found by the query. The field name
1879    syntax is the standard syntax used for fields in the B<ERDB> system--
1880    B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity
1881    or relationship and I<fieldName> is the name of the field.
1882    
1883    The list returned will be a list of lists. Each element of the list will contain
1884    the values returned for the fields specified in the fourth parameter. If one of the
1885    fields specified returns multiple values, they are flattened in with the rest. For
1886    example, the following call will return a list of the features in a particular
1887    spreadsheet cell, and each feature will be represented by a list containing the
1888    feature ID followed by all of its aliases.
1889    
1890    C<< $query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>
1891    
1892    =over 4
1893    
1894    =item objectNames
1895    
1896    List containing the names of the entity and relationship objects to be retrieved.
1897    
1898    =item filterClause
1899    
1900    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1901    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1902    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1903    parameter list as additional parameters. The fields in a filter clause can come from primary
1904    entity relations, relationship relations, or secondary entity relations; however, all of the
1905    entities and relationships involved must be included in the list of object names.
1906    
1907    =item parameterList
1908    
1909    List of the parameters to be substituted in for the parameters marks in the filter clause.
1910    
1911    =item fields
1912    
1913    List of the fields to be returned in each element of the list returned.
1914    
1915    =item count
1916    
1917    Maximum number of records to return. If omitted or 0, all available records will be returned.
1918    
1919    =item RETURN
1920    
1921    Returns a list of list references. Each element of the return list contains the values for the
1922    fields specified in the B<fields> parameter.
1923    
1924    =back
1925    
1926    =cut
1927    #: Return Type @@;
1928    sub GetAll {
1929        # Get the parameters.
1930        my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
1931        # Translate the parameters from a list reference to a list. If the parameter
1932        # list is a scalar we convert it into a singleton list.
1933        my @parmList = ();
1934        if (ref $parameterList eq "ARRAY") {
1935            Trace("GetAll parm list is an array.") if T(4);
1936            @parmList = @{$parameterList};
1937        } else {
1938            Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
1939            push @parmList, $parameterList;
1940        }
1941        # Insure the counter has a value.
1942        if (!defined $count) {
1943            $count = 0;
1944        }
1945        # Add the row limit to the filter clause.
1946        if ($count > 0) {
1947            $filterClause .= " LIMIT $count";
1948        }
1949        # Create the query.
1950        my $query = $self->Get($objectNames, $filterClause, \@parmList);
1951        # Set up a counter of the number of records read.
1952        my $fetched = 0;
1953        # Loop through the records returned, extracting the fields. Note that if the
1954        # counter is non-zero, we stop when the number of records read hits the count.
1955        my @retVal = ();
1956        while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
1957            my @rowData = $row->Values($fields);
1958            push @retVal, \@rowData;
1959            $fetched++;
1960        }
1961        # Return the resulting list.
1962        return @retVal;
1963    }
1964    
1965    =head3 EstimateRowSize
1966    
1967    C<< my $rowSize = $erdb->EstimateRowSize($relName); >>
1968    
1969    Estimate the row size of the specified relation. The estimated row size is computed by adding
1970    up the average length for each data type.
1971    
1972    =over 4
1973    
1974    =item relName
1975    
1976    Name of the relation whose estimated row size is desired.
1977    
1978    =item RETURN
1979    
1980    Returns an estimate of the row size for the specified relation.
1981    
1982    =back
1983    
1984    =cut
1985    #: Return Type $;
1986    sub EstimateRowSize {
1987        # Get the parameters.
1988        my ($self, $relName) = @_;
1989        # Declare the return variable.
1990        my $retVal = 0;
1991        # Find the relation descriptor.
1992        my $relation = $self->_FindRelation($relName);
1993        # Get the list of fields.
1994        for my $fieldData (@{$relation->{Fields}}) {
1995            # Get the field type and add its length.
1996            my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};
1997            $retVal += $fieldLen;
1998        }
1999        # Return the result.
2000        return $retVal;
2001    }
2002    
2003    =head3 GetFieldTable
2004    
2005    C<< my $fieldHash = $self->GetFieldTable($objectnName); >>
2006    
2007    Get the field structure for a specified entity or relationship.
2008    
2009    =over 4
2010    
2011    =item objectName
2012    
2013    Name of the desired entity or relationship.
2014    
2015    =item RETURN
2016    
2017    The table containing the field descriptors for the specified object.
2018    
2019    =back
2020    
2021    =cut
2022    
2023    sub GetFieldTable {
2024        # Get the parameters.
2025        my ($self, $objectName) = @_;
2026        # Get the descriptor from the metadata.
2027        my $objectData = $self->_GetStructure($objectName);
2028        # Return the object's field table.
2029        return $objectData->{Fields};
2030    }
2031    
2032    =head3 GetUsefulCrossValues
2033    
2034  C<< my %results = $database->LoadTable($fileName, $relationName, $truncateFlag); >>  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>
2035    
2036  Load data from a tab-delimited file into a specified table, optionally re-creating the table first.  Return a list of the useful attributes that would be returned by a B<Cross> call
2037    from an entity of the source entity type through the specified relationship. This
2038    means it will return the fields of the target entity type and the intersection data
2039    fields in the relationship. Only primary table fields are returned. In other words,
2040    the field names returned will be for fields where there is always one and only one
2041    value.
2042    
2043  =over 4  =over 4
2044    
2045  =item fileName  =item sourceEntity
2046    
2047  Name of the file from which the table data should be loaded.  Name of the entity from which the relationship crossing will start.
2048    
2049  =item relationName  =item relationship
2050    
2051  Name of the relation to be loaded. This is the same as the table name.  Name of the relationship being crossed.
2052    
2053  =item truncateFlag  =item RETURN
2054    
2055  TRUE if the table should be dropped and re-created, else FALSE  Returns a list of field names in Sprout field format (I<objectName>C<(>I<fieldName>C<)>.
2056    
2057    =back
2058    
2059    =cut
2060    #: Return Type @;
2061    sub GetUsefulCrossValues {
2062        # Get the parameters.
2063        my ($self, $sourceEntity, $relationship) = @_;
2064        # Declare the return variable.
2065        my @retVal = ();
2066        # Determine the target entity for the relationship. This is whichever entity is not
2067        # the source entity. So, if the source entity is the FROM, we'll get the name of
2068        # the TO, and vice versa.
2069        my $relStructure = $self->_GetStructure($relationship);
2070        my $targetEntityType = ($relStructure->{from} eq $sourceEntity ? "to" : "from");
2071        my $targetEntity = $relStructure->{$targetEntityType};
2072        # Get the field table for the entity.
2073        my $entityFields = $self->GetFieldTable($targetEntity);
2074        # The field table is a hash. The hash key is the field name. The hash value is a structure.
2075        # For the entity fields, the key aspect of the target structure is that the {relation} value
2076        # must match the entity name.
2077        my @fieldList = map { "$targetEntity($_)" } grep { $entityFields->{$_}->{relation} eq $targetEntity }
2078                            keys %{$entityFields};
2079        # Push the fields found onto the return variable.
2080        push @retVal, sort @fieldList;
2081        # Get the field table for the relationship.
2082        my $relationshipFields = $self->GetFieldTable($relationship);
2083        # Here we have a different rule. We want all the fields other than "from-link" and "to-link".
2084        # This may end up being an empty set.
2085        my @fieldList2 = map { "$relationship($_)" } grep { $_ ne "from-link" && $_ ne "to-link" }
2086                            keys %{$relationshipFields};
2087        # Push these onto the return list.
2088        push @retVal, sort @fieldList2;
2089        # Return the result.
2090        return @retVal;
2091    }
2092    
2093    =head2 Internal Utility Methods
2094    
2095    =head3 SetupSQL
2096    
2097    Process a list of object names and a filter clause so that they can be used to
2098    build an SQL statement. This method takes in a reference to a list of object names
2099    and a filter clause. It will return a corrected filter clause, a list of mapped
2100    names and the mapped name hash.
2101    
2102    This is an instance method.
2103    
2104    =over 4
2105    
2106    =item objectNames
2107    
2108    Reference to a list of the object names to be included in the query.
2109    
2110    =item filterClause
2111    
2112    A string containing the WHERE clause for the query (without the C<WHERE>) and also
2113    optionally the C<ORDER BY> and C<LIMIT> clauses.
2114    
2115  =item RETURN  =item RETURN
2116    
2117  Returns a statistical object containing the number of records read and a list of the error messages.  Returns a three-element list. The first element is the SQL statement suffix, beginning
2118    with the FROM clause. The second element is a reference to a list of the names to be
2119    used in retrieving the fields. The third element is a hash mapping the names to the
2120    objects they represent.
2121    
2122  =back  =back
2123    
2124  =cut  =cut
2125  sub LoadTable {  
2126          # Get the parameters.  sub _SetupSQL {
2127          my $self = shift @_;      my ($self, $objectNames, $filterClause) = @_;
2128          my ($fileName, $relationName, $truncateFlag) = @_;      # Adjust the list of object names to account for multiple occurrences of the
2129          # Create the statistical return object.      # same object. We start with a hash table keyed on object name that will
2130          my $retVal = _GetLoadStats();      # return the object suffix. The first time an object is encountered it will
2131          # Trace the fact of the load.      # not be found in the hash. The next time the hash will map the object name
2132          Trace("Loading table $relationName from $fileName") if T(1);      # to 2, then 3, and so forth.
2133          # Get the database handle.      my %objectHash = ();
2134          my $dbh = $self->{_dbh};      # This list will contain the object names as they are to appear in the
2135          # Get the relation data.      # FROM list.
2136          my $relation = $self->_FindRelation($relationName);      my @fromList = ();
2137          # Check the truncation flag.      # This list contains the suffixed object name for each object. It is exactly
2138          if ($truncateFlag) {      # parallel to the list in the $objectNames parameter.
2139                  Trace("Creating table $relationName") if T(1);      my @mappedNameList = ();
2140                  # Re-create the table without its index.      # Finally, this hash translates from a mapped name to its original object name.
2141                  $self->CreateTable($relationName, 0);      my %mappedNameHash = ();
2142        # Now we create the lists. Note that for every single name we push something into
2143        # @fromList and @mappedNameList. This insures that those two arrays are exactly
2144        # parallel to $objectNames.
2145        for my $objectName (@{$objectNames}) {
2146            # Get the next suffix for this object.
2147            my $suffix = $objectHash{$objectName};
2148            if (! $suffix) {
2149                # Here we are seeing the object for the first time. The object name
2150                # is used as is.
2151                push @mappedNameList, $objectName;
2152                push @fromList, $objectName;
2153                $mappedNameHash{$objectName} = $objectName;
2154                # Denote the next suffix will be 2.
2155                $objectHash{$objectName} = 2;
2156            } else {
2157                # Here we've seen the object before. We construct a new name using
2158                # the suffix from the hash and update the hash.
2159                my $mappedName = "$objectName$suffix";
2160                $objectHash{$objectName} = $suffix + 1;
2161                # The FROM list has the object name followed by the mapped name. This
2162                # tells SQL it's still the same table, but we're using a different name
2163                # for it to avoid confusion.
2164                push @fromList, "$objectName $mappedName";
2165                # The mapped-name list contains the real mapped name.
2166                push @mappedNameList, $mappedName;
2167                # Finally, enable us to get back from the mapped name to the object name.
2168                $mappedNameHash{$mappedName} = $objectName;
2169          }          }
2170          # Determine whether or not this is a primary relation. Primary relations have an extra      }
2171          # field indicating whether or not a given object is new or was loaded from the flat files.      # Begin the SELECT suffix. It starts with
2172          my $primary = $self->_IsPrimary($relationName);      #
2173          # Get the number of fields in this relation.      # FROM name1, name2, ... nameN
2174          my @fieldList = @{$relation->{Fields}};      #
2175          my $fieldCount = @fieldList;      my $suffix = "FROM " . join(', ', @fromList);
2176          # Record the number of expected fields.      # Check for a filter clause.
2177          my $expectedFields = $fieldCount + ($primary ? 1 : 0);      if ($filterClause) {
2178          # Start a database transaction.          # Here we have one, so we convert its field names and add it to the query. First,
2179          $dbh->begin_tran;          # We create a copy of the filter string we can work with.
2180          # Open the relation file. We need to create a cleaned-up copy before loading.          my $filterString = $filterClause;
2181          open TABLEIN, '<', $fileName;          # Next, we sort the object names by length. This helps protect us from finding
2182          my $tempName = "$fileName.tbl";          # object names inside other object names when we're doing our search and replace.
2183          open TABLEOUT, '>', $tempName;          my @sortedNames = sort { length($b) - length($a) } @mappedNameList;
2184          # Loop through the file.          # We will also keep a list of conditions to add to the WHERE clause in order to link
2185          while (<TABLEIN>) {          # entities and relationships as well as primary relations to secondary ones.
2186                  # Chop off the new-line character.          my @joinWhere = ();
2187                  my $record = $_;          # The final preparatory step is to create a hash table of relation names. The
2188                  chomp $record;          # table begins with the relation names already in the SELECT command. We may
2189                  # Escape all the backslashes found in the line.          # need to add relations later if there is filtering on a field in a secondary
2190                  $record =~ s/\\/\\\\/g;          # relation. The secondary relations are the ones that contain multiply-
2191                  # If this is a primary relation, add a 0 for the new-record flag (indicating that          # occurring or optional fields.
2192                  # this record is not new, but part of the original load).          my %fromNames = map { $_ => 1 } @sortedNames;
2193                  if ($primary) {          # We are ready to begin. We loop through the object names, replacing each
2194                          $record .= "\t0";          # object name's field references by the corresponding SQL field reference.
2195                  }          # Along the way, if we find a secondary relation, we will need to add it
2196                  # Write the record.          # to the FROM clause.
2197                  print TABLEOUT "$record\n";          for my $mappedName (@sortedNames) {
2198                  # Count the record read.              # Get the length of the object name plus 2. This is the value we add to the
2199                  my $count = $retVal->Add('records');              # size of the field name to determine the size of the field reference as a
2200          }              # whole.
2201          # Close the files.              my $nameLength = 2 + length $mappedName;
2202          close TABLEIN;              # Get the real object name for this mapped name.
2203          close TABLEOUT;              my $objectName = $mappedNameHash{$mappedName};
2204          # Load the table.              Trace("Processing $mappedName for object $objectName.") if T(4);
2205          my $rv;              # Get the object's field list.
2206          eval {              my $fieldList = $self->GetFieldTable($objectName);
2207                  $rv = $dbh->load_table(file => $tempName, tbl => $relationName);              # Find the field references for this object.
2208          };              while ($filterString =~ m/$mappedName\(([^)]*)\)/g) {
2209          if (!defined $rv) {                  # At this point, $1 contains the field name, and the current position
2210                  $retVal->AddMessage("Table load failed for $relationName.");                  # is set immediately after the final parenthesis. We pull out the name of
2211                  Trace("Table load failed for $relationName.") if T(1);                  # the field and the position and length of the field reference as a whole.
2212                    my $fieldName = $1;
2213                    my $len = $nameLength + length $fieldName;
2214                    my $pos = pos($filterString) - $len;
2215                    # Insure the field exists.
2216                    if (!exists $fieldList->{$fieldName}) {
2217                        Confess("Field $fieldName not found for object $objectName.");
2218          } else {          } else {
2219                  # Here we successfully loaded the table. Trace the number of records loaded.                      Trace("Processing $fieldName at position $pos.") if T(4);
2220                  Trace("$retVal->{records} records read for $relationName.") if T(1);                      # Get the field's relation.
2221                  # If we're rebuilding, we need to create the table indexes.                      my $relationName = $fieldList->{$fieldName}->{relation};
2222                  if ($truncateFlag) {                      # Now we have a secondary relation. We need to insure it matches the
2223                          eval {                      # mapped name of the primary relation. First we peel off the suffix
2224                                  $self->CreateIndex($relationName);                      # from the mapped name.
2225                          };                      my $mappingSuffix = substr $mappedName, length($objectName);
2226                          if ($@) {                      # Put the mapping suffix onto the relation name to get the
2227                                  $retVal->AddMessage($@);                      # mapped relation name.
2228                        my $mappedRelationName = "$relationName$mappingSuffix";
2229                        # Insure the relation is in the FROM clause.
2230                        if (!exists $fromNames{$mappedRelationName}) {
2231                            # Add the relation to the FROM clause.
2232                            if ($mappedRelationName eq $relationName) {
2233                                # The name is un-mapped, so we add it without
2234                                # any frills.
2235                                $suffix .= ", $relationName";
2236                                push @joinWhere, "$objectName.id = $relationName.id";
2237                            } else {
2238                                # Here we have a mapping situation.
2239                                $suffix .= ", $relationName $mappedRelationName";
2240                                push @joinWhere, "$mappedRelationName.id = $mappedName.id";
2241                          }                          }
2242                            # Denote we have this relation available for future fields.
2243                            $fromNames{$mappedRelationName} = 1;
2244                  }                  }
2245                        # Form an SQL field reference from the relation name and the field name.
2246                        my $sqlReference = "$mappedRelationName." . _FixName($fieldName);
2247                        # Put it into the filter string in place of the old value.
2248                        substr($filterString, $pos, $len) = $sqlReference;
2249                        # Reposition the search.
2250                        pos $filterString = $pos + length $sqlReference;
2251          }          }
2252          # Commit the database changes.              }
2253          $dbh->commit_tran;          }
2254          # Delete the temporary file.          # The next step is to join the objects together. We only need to do this if there
2255          unlink $tempName;          # is more than one object in the object list. We start with the first object and
2256          # Return the statistics.          # run through the objects after it. Note also that we make a safety copy of the
2257          return $retVal;          # list before running through it.
2258            my @mappedObjectList = @mappedNameList;
2259            my $lastMappedObject = shift @mappedObjectList;
2260            # Get the join table.
2261            my $joinTable = $self->{_metaData}->{Joins};
2262            # Loop through the object list.
2263            for my $thisMappedObject (@mappedObjectList) {
2264                # Look for a join using the real object names.
2265                my $lastObject = $mappedNameHash{$lastMappedObject};
2266                my $thisObject = $mappedNameHash{$thisMappedObject};
2267                my $joinKey = "$lastObject/$thisObject";
2268                if (!exists $joinTable->{$joinKey}) {
2269                    # Here there's no join, so we throw an error.
2270                    Confess("No join exists to connect from $lastMappedObject to $thisMappedObject.");
2271                } else {
2272                    # Get the join clause.
2273                    my $unMappedJoin = $joinTable->{$joinKey};
2274                    # Fix the names.
2275                    $unMappedJoin =~ s/$lastObject/$lastMappedObject/;
2276                    $unMappedJoin =~ s/$thisObject/$thisMappedObject/;
2277                    push @joinWhere, $unMappedJoin;
2278                    # Save this object as the last object for the next iteration.
2279                    $lastMappedObject = $thisMappedObject;
2280                }
2281            }
2282            # Now we need to handle the whole ORDER BY / LIMIT thing. The important part
2283            # here is we want the filter clause to be empty if there's no WHERE filter.
2284            # We'll put the ORDER BY / LIMIT clauses in the following variable.
2285            my $orderClause = "";
2286            # Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy
2287            # operator so that we find the first occurrence of either verb.
2288            if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {
2289                # Here we have an ORDER BY or LIMIT verb. Split it off of the filter string.
2290                my $pos = pos $filterString;
2291                $orderClause = $2 . substr($filterString, $pos);
2292                $filterString = $1;
2293            }
2294            # Add the filter and the join clauses (if any) to the SELECT command.
2295            if ($filterString) {
2296                Trace("Filter string is \"$filterString\".") if T(4);
2297                push @joinWhere, "($filterString)";
2298            }
2299            if (@joinWhere) {
2300                $suffix .= " WHERE " . join(' AND ', @joinWhere);
2301            }
2302            # Add the sort or limit clause (if any) to the SELECT command.
2303            if ($orderClause) {
2304                $suffix .= " $orderClause";
2305            }
2306        }
2307        # Return the suffix, the mapped name list, and the mapped name hash.
2308        return ($suffix, \@mappedNameList, \%mappedNameHash);
2309  }  }
2310    
2311  =head3 GenerateEntity  =head3 GetStatementHandle
   
 C<< my $fieldHash = $database->GenerateEntity($id, $type, \%values); >>  
2312    
2313  Generate the data for a new entity instance. This method creates a field hash suitable for  This method will prepare and execute an SQL query, returning the statement handle.
2314  passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest  The main reason for doing this here is so that everybody who does SQL queries gets
2315  of the fields are generated using information in the database schema.  the benefit of tracing.
2316    
2317  Each data type has a default algorithm for generating random test data. This can be overridden  This is an instance method.
 by including a B<DataGen> element in the field. If this happens, the content of the element is  
 executed as a PERL program in the context of this module. The element may make use of a C<$this>  
 variable which contains the field hash as it has been built up to the current point. If any  
 fields are dependent on other fields, the C<pass> attribute can be used to control the order  
 in which the fields are generated. A field with a high data pass number will be generated after  
 a field with a lower one. If any external values are needed, they should be passed in via the  
 optional third parameter, which will be available to the data generation script under the name  
 C<$value>. Several useful utility methods are provided for generating random values, including  
 L</IntGen>, L</StringGen>, L</FloatGen>, and L</DateGen>. Note that dates are stored and generated  
 in the form of a timestamp number rather than a string.  
2318    
2319  =over 4  =over 4
2320    
2321  =item id  =item command
2322    
2323  ID to assign to the new entity.  Command to prepare and execute.
2324    
2325  =item type  =item params
2326    
2327  Type name for the new entity.  Reference to a list of the values to be substituted in for the parameter marks.
2328    
2329  =item values  =item RETURN
2330    
2331  Hash containing additional values that might be needed by the data generation methods (optional).  Returns a prepared and executed statement handle from which the caller can extract
2332    results.
2333    
2334  =back  =back
2335    
2336  =cut  =cut
2337    
2338  sub GenerateEntity {  sub _GetStatementHandle {
2339          # Get the parameters.          # Get the parameters.
2340          my $self = shift @_;      my ($self, $command, $params) = @_;
2341          my ($id, $type, $values) = @_;      # Trace the query.
2342          # Create the return hash.      Trace("SQL query: $command") if T(SQL => 3);
2343          my $this = { id => $id };      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
2344          # Get the metadata structure.      # Get the database handle.
2345          my $metadata = $self->{_metaData};      my $dbh = $self->{_dbh};
2346          # Get this entity's list of fields.      # Prepare the command.
2347          if (!exists $metadata->{Entities}->{$type}) {      my $sth = $dbh->prepare_command($command);
2348                  Confess("Unrecognized entity type $type in GenerateEntity.");      # Execute it with the parameters bound in.
2349          } else {      $sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr());
2350                  my $entity = $metadata->{Entities}->{$type};      # Return the statement handle.
2351                  my $fields = $entity->{Fields};      return $sth;
                 # Generate data from the fields.  
                 _GenerateFields($this, $fields, $type, $values);  
         }  
         # Return the hash created.  
         return $this;  
2352  }  }
2353    
   
 =head2 Internal Utility Methods  
   
2354  =head3 GetLoadStats  =head3 GetLoadStats
2355    
2356  Return a blank statistics object for use by the load methods.  Return a blank statistics object for use by the load methods.
# Line 1131  Line 2360 
2360  =cut  =cut
2361    
2362  sub _GetLoadStats {  sub _GetLoadStats {
2363          return Stats->new('records');      return Stats->new();
2364  }  }
2365    
2366  =head3 GenerateFields  =head3 GenerateFields
# Line 1234  Line 2463 
2463    
2464  sub _DumpRelation {  sub _DumpRelation {
2465          # Get the parameters.          # Get the parameters.
2466          my $self = shift @_;      my ($self, $outputDirectory, $relationName, $relation) = @_;
         my ($outputDirectory, $relationName, $relation) = @_;  
2467          # Open the output file.          # Open the output file.
2468          my $fileName = "$outputDirectory/$relationName.dtx";          my $fileName = "$outputDirectory/$relationName.dtx";
2469          open(DTXOUT, ">$fileName") || Confess("Could not open dump file $fileName: $!");          open(DTXOUT, ">$fileName") || Confess("Could not open dump file $fileName: $!");
# Line 1281  Line 2509 
2509    
2510  sub _GetStructure {  sub _GetStructure {
2511          # Get the parameters.          # Get the parameters.
2512          my $self = shift @_;      my ($self, $objectName) = @_;
         my ($objectName) = @_;  
2513          # Get the metadata structure.          # Get the metadata structure.
2514          my $metadata = $self->{_metaData};          my $metadata = $self->{_metaData};
2515          # Declare the variable to receive the descriptor.          # Declare the variable to receive the descriptor.
# Line 1321  Line 2548 
2548    
2549  sub _GetRelationTable {  sub _GetRelationTable {
2550          # Get the parameters.          # Get the parameters.
2551          my $self = shift @_;      my ($self, $objectName) = @_;
         my ($objectName) = @_;  
2552          # Get the descriptor from the metadata.          # Get the descriptor from the metadata.
2553          my $objectData = $self->_GetStructure($objectName);          my $objectData = $self->_GetStructure($objectName);
2554          # Return the object's relation list.          # Return the object's relation list.
2555          return $objectData->{Relations};          return $objectData->{Relations};
2556  }  }
2557    
 =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 = shift @_;  
         my ($objectName) = @_;  
         # Get the descriptor from the metadata.  
         my $objectData = $self->_GetStructure($objectName);  
         # Return the object's field table.  
         return $objectData->{Fields};  
 }  
   
2558  =head3 ValidateFieldNames  =head3 ValidateFieldNames
2559    
2560  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
# Line 1449  Line 2645 
2645    
2646  sub _LoadRelation {  sub _LoadRelation {
2647          # Get the parameters.          # Get the parameters.
2648          my $self = shift @_;      my ($self, $directoryName, $relationName, $rebuild) = @_;
         my ($directoryName, $relationName, $rebuild) = @_;  
2649          # Create the file name.          # Create the file name.
2650          my $fileName = "$directoryName/$relationName";          my $fileName = "$directoryName/$relationName";
2651          # If the file doesn't exist, try adding the .dtx suffix.          # If the file doesn't exist, try adding the .dtx suffix.
# Line 1500  Line 2695 
2695  sub _LoadMetaData {  sub _LoadMetaData {
2696          # Get the parameters.          # Get the parameters.
2697          my ($filename) = @_;          my ($filename) = @_;
2698        Trace("Reading Sprout DBD from $filename.") if T(2);
2699          # 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
2700          # get the exact structure we want.          # get the exact structure we want.
2701          my $metadata = XML::Simple::XMLin($filename,          my $metadata = XML::Simple::XMLin($filename,
# Line 1524  Line 2720 
2720          my %masterRelationTable = ();          my %masterRelationTable = ();
2721          # Loop through the entities.          # Loop through the entities.
2722          my $entityList = $metadata->{Entities};          my $entityList = $metadata->{Entities};
2723          while (my ($entityName, $entityStructure) = each %{$entityList}) {      for my $entityName (keys %{$entityList}) {
2724            my $entityStructure = $entityList->{$entityName};
2725                  #                  #
2726                  # 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,
2727                  # 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,
2728                  # 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>
2729                  # 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
# Line 1572  Line 2769 
2769                  # to a list of fields. First, we need the ID field itself.                  # to a list of fields. First, we need the ID field itself.
2770                  my $idField = $fieldList->{id};                  my $idField = $fieldList->{id};
2771                  # Loop through the relations.                  # Loop through the relations.
2772                  while (my ($relationName, $relation) = each %{$relationTable}) {          for my $relationName (keys %{$relationTable}) {
2773                my $relation = $relationTable->{$relationName};
2774                          # Get the relation's field list.                          # Get the relation's field list.
2775                          my $relationFieldList = $relation->{Fields};                          my $relationFieldList = $relation->{Fields};
2776                          # Add the ID field to it. If the field's already there, it will not make any                          # Add the ID field to it. If the field's already there, it will not make any
# Line 1622  Line 2820 
2820                  # The next step is to insure that each relation has at least one index that begins with the ID field.                  # The next step is to insure that each relation has at least one index that begins with the ID field.
2821                  # After that, we convert each relation's index list to an index table. We first need to loop through                  # After that, we convert each relation's index list to an index table. We first need to loop through
2822                  # the relations.                  # the relations.
2823                  while (my ($relationName, $relation) = each %{$relationTable}) {          for my $relationName (keys %{$relationTable}) {
2824                my $relation = $relationTable->{$relationName};
2825                          # Get the relation's index list.                          # Get the relation's index list.
2826                          my $indexList = $relation->{Indexes};                          my $indexList = $relation->{Indexes};
2827                          # Insure this relation has an ID index.                          # Insure this relation has an ID index.
# Line 1653  Line 2852 
2852          # Loop through the relationships. Relationships actually turn out to be much simpler than entities.          # Loop through the relationships. Relationships actually turn out to be much simpler than entities.
2853          # For one thing, there is only a single constituent relation.          # For one thing, there is only a single constituent relation.
2854          my $relationshipList = $metadata->{Relationships};          my $relationshipList = $metadata->{Relationships};
2855          while (my ($relationshipName, $relationshipStructure) = each %{$relationshipList}) {      for my $relationshipName (keys %{$relationshipList}) {
2856            my $relationshipStructure = $relationshipList->{$relationshipName};
2857                  # Fix up this relationship.                  # Fix up this relationship.
2858                  _FixupFields($relationshipStructure, $relationshipName, 2, 3);                  _FixupFields($relationshipStructure, $relationshipName, 2, 3);
2859                  # Format a description for the FROM field.                  # Format a description for the FROM field.
# Line 1702  Line 2902 
2902                  my @fromList = ();                  my @fromList = ();
2903                  my @toList = ();                  my @toList = ();
2904                  my @bothList = ();                  my @bothList = ();
2905                  while (my ($relationshipName, $relationship) = each %{$relationshipList}) {          Trace("Join table build for $entityName.") if T(metadata => 4);
2906            for my $relationshipName (keys %{$relationshipList}) {
2907                my $relationship = $relationshipList->{$relationshipName};
2908                          # 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.
2909                          if ($relationship->{from} eq $entityName) {              my $fromEntity = $relationship->{from};
2910                                  if ($relationship->{to} eq $entityName) {              my $toEntity = $relationship->{to};
2911                Trace("Join check for relationship $relationshipName from $fromEntity to $toEntity.") if T(Joins => 4);
2912                if ($fromEntity eq $entityName) {
2913                    if ($toEntity eq $entityName) {
2914                                          # Here the relationship is recursive.                                          # Here the relationship is recursive.
2915                                          push @bothList, $relationshipName;                                          push @bothList, $relationshipName;
2916                        Trace("Relationship $relationshipName put in both-list.") if T(metadata => 4);
2917                                  } else {                                  } else {
2918                                          # Here the relationship comes from the entity.                                          # Here the relationship comes from the entity.
2919                                          push @fromList, $relationshipName;                                          push @fromList, $relationshipName;
2920                        Trace("Relationship $relationshipName put in from-list.") if T(metadata => 4);
2921                                  }                                  }
2922                          } elsif ($relationship->{to} eq $entityName) {              } elsif ($toEntity eq $entityName) {
2923                                  # Here the relationship goes to the entity.                                  # Here the relationship goes to the entity.
2924                                  push @toList, $relationshipName;                                  push @toList, $relationshipName;
2925                    Trace("Relationship $relationshipName put in to-list.") if T(metadata => 4);
2926                          }                          }
2927                  }                  }
2928                  # Create the nonrecursive joins. Note that we build two hashes for running                  # Create the nonrecursive joins. Note that we build two hashes for running
# Line 1723  Line 2931 
2931                  # hash table at the same time.                  # hash table at the same time.
2932                  my %directRelationships = ( from => \@fromList, to => \@toList );                  my %directRelationships = ( from => \@fromList, to => \@toList );
2933                  my %otherRelationships = ( from => \@fromList, to => \@toList );                  my %otherRelationships = ( from => \@fromList, to => \@toList );
2934                  while (my ($linkType, $relationships) = each %directRelationships) {          for my $linkType (keys %directRelationships) {
2935                my $relationships = $directRelationships{$linkType};
2936                          # Loop through all the relationships.                          # Loop through all the relationships.
2937                          for my $relationshipName (@{$relationships}) {                          for my $relationshipName (@{$relationships}) {
2938                                  # Create joins between the entity and this relationship.                                  # Create joins between the entity and this relationship.
2939                                  my $linkField = "$relationshipName.${linkType}_link";                                  my $linkField = "$relationshipName.${linkType}_link";
2940                                  my $joinClause = "$entityName.id = $linkField";                                  my $joinClause = "$entityName.id = $linkField";
2941                    Trace("Entity join clause is $joinClause for $entityName and $relationshipName.") if T(metadata => 4);
2942                                  $joinTable{"$entityName/$relationshipName"} = $joinClause;                                  $joinTable{"$entityName/$relationshipName"} = $joinClause;
2943                                  $joinTable{"$relationshipName/$entityName"} = $joinClause;                                  $joinTable{"$relationshipName/$entityName"} = $joinClause;
2944                                  # Create joins between this relationship and the other relationships.                                  # Create joins between this relationship and the other relationships.
2945                                  while (my ($otherType, $otherships) = each %otherRelationships) {                  for my $otherType (keys %otherRelationships) {
2946                        my $otherships = $otherRelationships{$otherType};
2947                                          for my $otherName (@{$otherships}) {                                          for my $otherName (@{$otherships}) {
2948                                                  # Get the key for this join.                                                  # Get the key for this join.
2949                                                  my $joinKey = "$otherName/$relationshipName";                                                  my $joinKey = "$otherName/$relationshipName";
# Line 1742  Line 2953 
2953                                                          # path is ambiguous. We delete the join from the join                                                          # path is ambiguous. We delete the join from the join
2954                                                          # table to prevent it from being used.                                                          # table to prevent it from being used.
2955                                                          delete $joinTable{$joinKey};                                                          delete $joinTable{$joinKey};
2956                                Trace("Deleting ambiguous join $joinKey.") if T(4);
2957                                                  } elsif ($otherName ne $relationshipName) {                                                  } elsif ($otherName ne $relationshipName) {
2958                                                          # Here we have a valid join. Note that joins between a                                                          # Here we have a valid join. Note that joins between a
2959                                                          # relationship and itself are prohibited.                                                          # relationship and itself are prohibited.
2960                                                          $joinTable{$joinKey} = "$otherName.${otherType}_link = $linkField";                              my $relJoinClause = "$otherName.${otherType}_link = $linkField";
2961                                $joinTable{$joinKey} = $relJoinClause;
2962                                Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(metadata => 4);
2963                                                  }                                                  }
2964                                          }                                          }
2965                                  }                                  }
# Line 1754  Line 2968 
2968                                  # relationship can only be ambiguous with another recursive relationship,                                  # relationship can only be ambiguous with another recursive relationship,
2969                                  # and the incoming relationship from the outer loop is never recursive.                                  # and the incoming relationship from the outer loop is never recursive.
2970                                  for my $otherName (@bothList) {                                  for my $otherName (@bothList) {
2971                        Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(metadata => 4);
2972                                          # Join from the left.                                          # Join from the left.
2973                                          $joinTable{"$relationshipName/$otherName"} =                                          $joinTable{"$relationshipName/$otherName"} =
2974                                                  "$linkField = $otherName.from_link";                                                  "$linkField = $otherName.from_link";
# Line 1768  Line 2983 
2983                  # 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
2984                  # possible to get the same effect using multiple queries.                  # possible to get the same effect using multiple queries.
2985                  for my $relationshipName (@bothList) {                  for my $relationshipName (@bothList) {
2986                Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(metadata => 4);
2987                          # Join to the entity from each direction.                          # Join to the entity from each direction.
2988                          $joinTable{"$entityName/$relationshipName"} =                          $joinTable{"$entityName/$relationshipName"} =
2989                                  "$entityName.id = $relationshipName.from_link";                                  "$entityName.id = $relationshipName.from_link";
# Line 1781  Line 2997 
2997          return $metadata;          return $metadata;
2998  }  }
2999    
3000    =head3 SortNeeded
3001    
3002    C<< my $flag = $erdb->SortNeeded($relationName); >>
3003    
3004    Return TRUE if the specified relation should be sorted during loading to remove duplicate keys,
3005    else FALSE.
3006    
3007    =over 4
3008    
3009    =item relationName
3010    
3011    Name of the relation to be examined.
3012    
3013    =item RETURN
3014    
3015    Returns TRUE if the relation needs a sort, else FALSE.
3016    
3017    =back
3018    
3019    =cut
3020    #: Return Type $;
3021    sub SortNeeded {
3022        # Get the parameters.
3023        my ($self, $relationName) = @_;
3024        # Declare the return variable.
3025        my $retVal = 0;
3026        # Find out if the relation is a primary entity relation.
3027        my $entityTable = $self->{_metaData}->{Entities};
3028        if (exists $entityTable->{$relationName}) {
3029            my $keyType = $entityTable->{$relationName}->{keyType};
3030            Trace("Relation $relationName found in entity table with key type $keyType.") if T(3);
3031            # If the key is not a hash string, we must do the sort.
3032            if ($keyType ne 'hash-string') {
3033                $retVal = 1;
3034            }
3035        }
3036        # Return the result.
3037        return $retVal;
3038    }
3039    
3040  =head3 CreateRelationshipIndex  =head3 CreateRelationshipIndex
3041    
3042  Create an index for a relationship's relation.  Create an index for a relationship's relation.
# Line 1818  Line 3074 
3074          # 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
3075          # the field to it.          # the field to it.
3076          unshift @{$newIndex->{IndexFields}}, $firstField;          unshift @{$newIndex->{IndexFields}}, $firstField;
3077        # If this is a one-to-many relationship, the "To" index is unique.
3078        if ($relationshipStructure->{arity} eq "1M" && $indexKey eq "To") {
3079            $newIndex->{Unique} = 'true';
3080        }
3081          # Add the index to the relation.          # Add the index to the relation.
3082          _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);          _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);
3083  }  }
# Line 1907  Line 3167 
3167                  $structure->{Fields} = { };                  $structure->{Fields} = { };
3168          } else {          } else {
3169                  # Here we have a field list. Loop through its fields.                  # Here we have a field list. Loop through its fields.
3170                  while (my ($fieldName, $fieldData) = each %{$structure->{Fields}}) {          my $fieldStructures = $structure->{Fields};
3171            for my $fieldName (keys %{$fieldStructures}) {
3172                Trace("Processing field $fieldName of $defaultRelationName.") if T(4);
3173                my $fieldData = $fieldStructures->{$fieldName};
3174                          # Get the field type.                          # Get the field type.
3175                          my $type = $fieldData->{type};                          my $type = $fieldData->{type};
3176                          # Plug in a relation name if it is needed.                          # Plug in a relation name if it is needed.
# Line 2104  Line 3367 
3367    
3368  sub _IsPrimary {  sub _IsPrimary {
3369          # Get the parameters.          # Get the parameters.
3370          my $self = shift @_;      my ($self, $relationName) = @_;
         my ($relationName) = @_;  
3371          # Check for the relation in the entity table.          # Check for the relation in the entity table.
3372          my $entityTable = $self->{_metaData}->{Entities};          my $entityTable = $self->{_metaData}->{Entities};
3373          my $retVal = exists $entityTable->{$relationName};          my $retVal = exists $entityTable->{$relationName};
# Line 2139  Line 3401 
3401  =cut  =cut
3402  sub _FindRelation {  sub _FindRelation {
3403          # Get the parameters.          # Get the parameters.
3404          my $self = shift @_;      my ($self, $relationName) = @_;
         my ($relationName) = @_;  
3405          # Get the relation's structure from the master relation table in the metadata structure.          # Get the relation's structure from the master relation table in the metadata structure.
3406          my $metaData = $self->{_metaData};          my $metaData = $self->{_metaData};
3407          my $retVal = $metaData->{RelationTable}->{$relationName};          my $retVal = $metaData->{RelationTable}->{$relationName};
# Line 2268  Line 3529 
3529                  my $indexData = $indexTable->{$indexName};                  my $indexData = $indexTable->{$indexName};
3530                  # Determine whether or not the index is unique.                  # Determine whether or not the index is unique.
3531                  my $fullName = $indexName;                  my $fullName = $indexName;
3532                  if ($indexData->{Unique} eq "true") {          if (exists $indexData->{Unique} && $indexData->{Unique} eq "true") {
3533                          $fullName .= " (unique)";                          $fullName .= " (unique)";
3534                  }                  }
3535                  # Start an HTML list item for this index.                  # Start an HTML list item for this index.

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.45

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3