[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.3, Wed Jan 26 22:26:09 2005 UTC revision 1.69, Fri Sep 29 15:06:17 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 counter
95    
96    32-bit unsigned integer
97    
98    =item date
99    
100    64-bit unsigned integer, representing a PERL date/time value
101    
102    =item text
103    
104    long string; Text fields cannot be used in indexes or sorting and do not support the
105    normal syntax of filter clauses, but can be up to a billion character in length
106    
107    =item float
108    
109    double-precision floating-point number
110    
111    =item boolean
112    
113    single-bit numeric value; The value is stored as a 16-bit signed integer (for
114    compatability with certain database packages), but the only values supported are
115    0 and 1.
116    
117    =item id-string
118    
119    variable-length string, maximum 25 characters
120    
121    =item key-string
122    
123    variable-length string, maximum 40 characters
124    
125    =item name-string
126    
127    variable-length string, maximum 80 characters
128    
129    =item medium-string
130    
131    variable-length string, maximum 160 characters
132    
133    =item string
134    
135    variable-length string, maximum 255 characters
136    
137    =item hash-string
138    
139    variable-length string, maximum 22 characters
140    
141    =back
142    
143    The hash-string data type has a special meaning. The actual key passed into the loader will
144    be a string, but it will be digested into a 22-character MD5 code to save space. Although the
145    MD5 algorithm is not perfect, it is extremely unlikely two strings will have the same
146    digest. Therefore, it is presumed the keys will be unique. When the database is actually
147    in use, the hashed keys will be presented rather than the original values. For this reason,
148    they should not be used for entities where the key is meaningful.
149    
150    =head3 Global Tags
151    
152    The entire database definition must be inside a B<Database> tag. The display name of
153    the database is given by the text associated with the B<Title> tag. The display name
154    is only used in the automated documentation. It has no other effect. The entities and
155    relationships are listed inside the B<Entities> and B<Relationships> tags,
156    respectively. None of these tags have attributes.
157    
158        <Database>
159            <Title>... display title here...</Title>
160            <Entities>
161                ... entity definitions here ...
162            </Entities>
163            <Relationships>
164                ... relationship definitions here...
165            </Relationships>
166        </Database>
167    
168    Entities, relationships, indexes, and fields all allow a text tag called B<Notes>.
169    The text inside the B<Notes> tag contains comments that will appear when the database
170    documentation is generated. Within a B<Notes> tag, you may use C<[i]> and C<[/i]> for
171    italics, C<[b]> and C<[/b]> for bold, and C<[p]> for a new paragraph.
172    
173    =head3 Fields
174    
175    Both entities and relationships have fields described by B<Field> tags. A B<Field>
176    tag can have B<Notes> associated with it. The complete set of B<Field> tags for an
177    object mus be inside B<Fields> tags.
178    
179        <Entity ... >
180            <Fields>
181                ... Field tags ...
182            </Fields>
183        </Entity>
184    
185    The attributes for the B<Field> tag are as follows.
186    
187    =over 4
188    
189    =item name
190    
191    Name of the field. The field name should contain only letters, digits, and hyphens (C<->),
192    and the first character should be a letter. Most underlying databases are case-insensitive
193    with the respect to field names, so a best practice is to use lower-case letters only.
194    
195    =item type
196    
197    Data type of the field. The legal data types are given above.
198    
199    =item relation
200    
201    Name of the relation containing the field. This should only be specified for entity
202    fields. The ERDB system does not support optional fields or multi-occurring fields
203    in the primary relation of an entity. Instead, they are put into secondary relations.
204    So, for example, in the C<Genome> entity, the C<group-name> field indicates a special
205    grouping used to select a subset of the genomes. A given genome may not be in any
206    groups or may be in multiple groups. Therefore, C<group-name> specifies a relation
207    value. The relation name specified must be a valid table name. By convention, it is
208    usually the entity name followed by a qualifying word (e.g. C<GenomeGroup>). In an
209    entity, the fields without a relation attribute are said to belong to the
210    I<primary relation>. This relation has the same name as the entity itself.
211    
212    =back
213    
214    =head3 Indexes
215    
216    An entity can have multiple alternate indexes associated with it. The fields must
217    be from the primary relation. The alternate indexes assist in ordering results
218    from a query. A relationship can have up to two indexes-- a I<to-index> and a
219    I<from-index>. These order the results when crossing the relationship. For
220    example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the
221    from-index would order the contigs of a ganome, and the to-index would order
222    the genomes of a contig. A relationship's index must specify only fields in
223    the relationship.
224    
225    The indexes for an entity must be listed inside the B<Indexes> tag. The from-index
226    of a relationship is specified using the B<FromIndex> tag; the to-index is specified
227    using the B<ToIndex> tag.
228    
229    Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields>
230    tag containing the B<IndexField> tags. These specify, in order, the fields used in
231    the index. The attributes of an B<IndexField> tag are as follows.
232    
233    =over 4
234    
235    =item name
236    
237    Name of the field.
238    
239    =item order
240    
241    Sort order of the field-- C<ascending> or C<descending>.
242    
243    =back
244    
245    The B<Index>, B<FromIndex>, and B<ToIndex> tags themselves have no attributes.
246    
247    =head3 Object and Field Names
248    
249    By convention entity and relationship names use capital casing (e.g. C<Genome> or
250    C<HasRegionsIn>. Most underlying databases, however, are aggressively case-insensitive
251    with respect to relation names, converting them internally to all-upper case or
252    all-lower case.
253    
254    If syntax or parsing errors occur when you try to load or use an ERDB database, the
255    most likely reason is that one of your objects has an SQL reserved word as its name.
256    The list of SQL reserved words keeps increasing; however, most are unlikely to show
257    up as a noun or declarative verb phrase. The exceptions are C<Group>, C<User>,
258    C<Table>, C<Index>, C<Object>, C<Date>, C<Number>, C<Update>, C<Time>, C<Percent>,
259    C<Memo>, C<Order>, and C<Sum>. This problem can crop up in field names as well.
260    
261    Every entity has a field called C<id> that acts as its primary key. Every relationship
262    has fields called C<from-link> and C<to-link> that contain copies of the relevant
263    entity IDs. These are essentially ERDB's reserved words, and should not be used
264    for user-defined field names.
265    
266    =head3 Entities
267    
268    An entity is described by the B<Entity> tag. The entity can contain B<Notes>, an
269    B<Indexes> tag containing one or more secondary indexes, and a B<Fields> tag
270    containing one or more fields. The attributes of the B<Entity> tag are as follows.
271    
272    =over 4
273    
274    =item name
275    
276    Name of the entity. The entity name, by convention, uses capital casing (e.g. C<Genome>
277    or C<GroupBlock>) and should be a noun or noun phrase.
278    
279    =item keyType
280    
281    Data type of the primary key. The primary key is always named C<id>.
282    
283    =back
284    
285    =head3 Relationships
286    
287    A relationship is described by the C<Relationship> tag. Within a relationship,
288    there can be a C<Notes> tag, a C<Fields> tag containing the intersection data
289    fields, a C<FromIndex> tag containing the from-index, and a C<ToIndex> tag containing
290    the to-index.
291    
292    The C<Relationship> tag has the following attributes.
293    
294    =over 4
295    
296    =item name
297    
298    Name of the relationship. The relationship name, by convention, uses capital casing
299    (e.g. C<ContainsRegionIn> or C<HasContig>), and should be a declarative verb
300    phrase, designed to fit between the from-entity and the to-entity (e.g.
301    Block C<ContainsRegionIn> Genome).
302    
303    =item from
304    
305    Name of the entity from which the relationship starts.
306    
307    =item to
308    
309    Name of the entity to which the relationship proceeds.
310    
311    =item arity
312    
313    Relationship type: C<1M> for one-to-many and C<MM> for many-to-many.
314    
315    =back
316    
317  =cut  =cut
318    
# Line 76  Line 321 
321  # 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.
322  # "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
323  # 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
324   #string is specified in the field definition.  # string is specified in the field definition. "avgLen" is the average byte length for estimating
325  my %TypeTable = ( char =>        { sqlType => 'CHAR(1)',                        maxLen => 1,                    dataGen => "StringGen('A')" },  # record sizes. "sort" is the key modifier for the sort command.
326                                    int =>         { sqlType => 'INTEGER',                        maxLen => 20,                   dataGen => "IntGen(0, 99999999)" },  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, sort => "",  dataGen => "StringGen('A')" },
327                                    string =>  { sqlType => 'VARCHAR(255)',               maxLen => 255,                  dataGen => "StringGen(IntGen(10,250))" },                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, sort => "n", dataGen => "IntGen(0, 99999999)" },
328                                    text =>        { sqlType => 'TEXT',                           maxLen => 1000000000,   dataGen => "StringGen(IntGen(80,1000))" },                    counter => { sqlType => 'INTEGER UNSIGNED',   maxLen => 20,           avgLen =>   4, sort => "n", dataGen => "IntGen(0, 99999999)" },
329                                    date =>        { sqlType => 'BIGINT',                         maxLen => 80,                   dataGen => "DateGen(-7, 7, IntGen(0,1400))" },                    string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          avgLen => 100, sort => "",  dataGen => "StringGen(IntGen(10,250))" },
330                                    float =>       { sqlType => 'DOUBLE PRECISION',       maxLen => 40,                   dataGen => "FloatGen(0.0, 100.0)" },                    text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, sort => "",  dataGen => "StringGen(IntGen(80,1000))" },
331                                    boolean => { sqlType => 'SMALLINT',                   maxLen => 1,                    dataGen => "IntGen(0, 1)" },                    date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, sort => "n", dataGen => "DateGen(-7, 7, IntGen(0,1400))" },
332                      float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, sort => "g", dataGen => "FloatGen(0.0, 100.0)" },
333                      boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   1, sort => "n", dataGen => "IntGen(0, 1)" },
334                     'hash-string' =>
335                                 { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, sort => "",  dataGen => "SringGen(22)" },
336                     'id-string' =>
337                                 { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, sort => "",  dataGen => "SringGen(22)" },
338                               'key-string' =>                               'key-string' =>
339                                                           { sqlType => 'VARCHAR(40)',            maxLen => 40,                   dataGen => "StringGen(IntGen(10,40))" },                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, sort => "",  dataGen => "StringGen(IntGen(10,40))" },
340                                   'name-string' =>                                   'name-string' =>
341                                                           { sqlType => 'VARCHAR(80)',            maxLen => 80,                   dataGen => "StringGen(IntGen(10,80))" },                               { sqlType => 'VARCHAR(80)',        maxLen => 80,           avgLen =>  40, sort => "",  dataGen => "StringGen(IntGen(10,80))" },
342                                   'medium-string' =>                                   'medium-string' =>
343                                                           { sqlType => 'VARCHAR(160)',           maxLen => 160,                  dataGen => "StringGen(IntGen(10,160))" },                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",  dataGen => "StringGen(IntGen(10,160))" },
344                                  );                                  );
345    
346  # Table translating arities into natural language.  # Table translating arities into natural language.
# Line 111  Line 362 
362    
363  =head3 new  =head3 new
364    
365  C<< my $database = ERDB::new($dbh, $metaFileName); >>  C<< my $database = ERDB->new($dbh, $metaFileName); >>
366    
367  Create a new ERDB object.  Create a new ERDB object.
368    
# Line 136  Line 387 
387          my $metaData = _LoadMetaData($metaFileName);          my $metaData = _LoadMetaData($metaFileName);
388          # Create the object.          # Create the object.
389          my $self = { _dbh => $dbh,          my $self = { _dbh => $dbh,
390                                   _metaData => $metaData,                   _metaData => $metaData
                                  _options => $options,  
391                             };                             };
392          # Bless and return it.          # Bless and return it.
393          bless $self;      bless $self, $class;
394          return $self;          return $self;
395  }  }
396    
397  =head3 ShowMetaData  =head3 ShowMetaData
398    
399  C<< $database->ShowMetaData($fileName); >>  C<< $erdb->ShowMetaData($fileName); >>
400    
401  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
402  the data to be loaded into the relations.  the data to be loaded into the relations.
# Line 163  Line 413 
413    
414  sub ShowMetaData {  sub ShowMetaData {
415          # Get the parameters.          # Get the parameters.
416          my $self = shift @_;      my ($self, $filename) = @_;
         my ($filename) = @_;  
417          # Get the metadata and the title string.          # Get the metadata and the title string.
418          my $metadata = $self->{_metaData};          my $metadata = $self->{_metaData};
419          # Get the title string.          # Get the title string.
# Line 174  Line 423 
423          my $relationshipList = $metadata->{Relationships};          my $relationshipList = $metadata->{Relationships};
424          # Open the output file.          # Open the output file.
425          open(HTMLOUT, ">$filename") || Confess("Could not open MetaData display file $filename: $!");          open(HTMLOUT, ">$filename") || Confess("Could not open MetaData display file $filename: $!");
426        Trace("Building MetaData table of contents.") if T(4);
427          # Write the HTML heading stuff.          # Write the HTML heading stuff.
428          print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";          print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";
429          print HTMLOUT "</head>\n<body>\n";          print HTMLOUT "</head>\n<body>\n";
430        # Write the documentation.
431        print HTMLOUT $self->DisplayMetaData();
432        # Close the document.
433        print HTMLOUT "</body>\n</html>\n";
434        # Close the file.
435        close HTMLOUT;
436    }
437    
438    =head3 DisplayMetaData
439    
440    C<< my $html = $erdb->DisplayMetaData(); >>
441    
442    Return an HTML description of the database. This description can be used to help users create
443    the data to be loaded into the relations and form queries. The output is raw includable HTML
444    without any HEAD or BODY tags.
445    
446    =over 4
447    
448    =item filename
449    
450    The name of the output file.
451    
452    =back
453    
454    =cut
455    
456    sub DisplayMetaData {
457        # Get the parameters.
458        my ($self) = @_;
459        # Get the metadata and the title string.
460        my $metadata = $self->{_metaData};
461        # Get the title string.
462        my $title = $metadata->{Title};
463        # Get the entity and relationship lists.
464        my $entityList = $metadata->{Entities};
465        my $relationshipList = $metadata->{Relationships};
466        # Declare the return variable.
467        my $retVal = "";
468        # Open the output file.
469        Trace("Building MetaData table of contents.") if T(4);
470          # 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
471          # section contains an ordered list of entity or relationship subsections.          # section contains an ordered list of entity or relationship subsections.
472          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";
473          # Loop through the Entities, displaying a list item for each.          # Loop through the Entities, displaying a list item for each.
474          foreach my $key (sort keys %{$entityList}) {          foreach my $key (sort keys %{$entityList}) {
475                  # Display this item.                  # Display this item.
476                  print HTMLOUT "<li><a href=\"#$key\">$key</a></li>\n";          $retVal .= "<li><a href=\"#$key\">$key</a></li>\n";
477          }          }
478          # Close off the entity section and start the relationship section.          # Close off the entity section and start the relationship section.
479          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";
480          # Loop through the Relationships.          # Loop through the Relationships.
481          foreach my $key (sort keys %{$relationshipList}) {          foreach my $key (sort keys %{$relationshipList}) {
482                  # Display this item.                  # Display this item.
483                  my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});                  my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});
484                  print HTMLOUT "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";          $retVal .= "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";
485          }          }
486          # Close off the relationship section and list the join table section.          # Close off the relationship section and list the join table section.
487          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";
488          # Close off the table of contents itself.          # Close off the table of contents itself.
489          print HTMLOUT "</ul>\n";      $retVal .=  "</ul>\n";
490          # 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.
491          print HTMLOUT "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";      $retVal .= "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";
492          # Loop through the entities.          # Loop through the entities.
493          for my $key (sort keys %{$entityList}) {          for my $key (sort keys %{$entityList}) {
494            Trace("Building MetaData entry for $key entity.") if T(4);
495                  # Create the entity header. It contains a bookmark and the entity name.                  # Create the entity header. It contains a bookmark and the entity name.
496                  print HTMLOUT "<a name=\"$key\"></a><h3>$key</h3>\n";          $retVal .= "<a name=\"$key\"></a><h3>$key</h3>\n";
497                  # Get the entity data.                  # Get the entity data.
498                  my $entityData = $entityList->{$key};                  my $entityData = $entityList->{$key};
499                  # If there's descriptive text, display it.                  # If there's descriptive text, display it.
500                  if (my $notes = $entityData->{Notes}) {                  if (my $notes = $entityData->{Notes}) {
501                          print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";
502                  }                  }
503                  # 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.
504                  print HTMLOUT "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";          $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";
505                  # Loop through the relationships.                  # Loop through the relationships.
506                  for my $relationship (sort keys %{$relationshipList}) {                  for my $relationship (sort keys %{$relationshipList}) {
507                          # Get the relationship data.                          # Get the relationship data.
# Line 220  Line 511 
511                                  # Get the relationship sentence and append the arity.                                  # Get the relationship sentence and append the arity.
512                                  my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);                                  my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);
513                                  # Display the relationship data.                                  # Display the relationship data.
514                                  print HTMLOUT "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";                  $retVal .= "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";
515                          }                          }
516                  }                  }
517                  # Close off the relationship list.                  # Close off the relationship list.
518                  print HTMLOUT "</ul>\n";          $retVal .= "</ul>\n";
519                  # Get the entity's relations.                  # Get the entity's relations.
520                  my $relationList = $entityData->{Relations};                  my $relationList = $entityData->{Relations};
521                  # Create a header for the relation subsection.                  # Create a header for the relation subsection.
522                  print HTMLOUT "<h4>Relations for <b>$key</b></h4>\n";          $retVal .= "<h4>Relations for <b>$key</b></h4>\n";
523                  # Loop through the relations, displaying them.                  # Loop through the relations, displaying them.
524                  for my $relation (sort keys %{$relationList}) {                  for my $relation (sort keys %{$relationList}) {
525                          my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});                          my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});
526                          print HTMLOUT $htmlString;              $retVal .= $htmlString;
527                  }                  }
528          }          }
529          # Denote we're starting the relationship section.          # Denote we're starting the relationship section.
530          print HTMLOUT "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";      $retVal .= "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";
531          # Loop through the relationships.          # Loop through the relationships.
532          for my $key (sort keys %{$relationshipList}) {          for my $key (sort keys %{$relationshipList}) {
533            Trace("Building MetaData entry for $key relationship.") if T(4);
534                  # Get the relationship's structure.                  # Get the relationship's structure.
535                  my $relationshipStructure = $relationshipList->{$key};                  my $relationshipStructure = $relationshipList->{$key};
536                  # Create the relationship header.                  # Create the relationship header.
537                  my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);                  my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);
538                  print HTMLOUT "<h3><a name=\"$key\"></a>$headerText</h3>\n";          $retVal .= "<h3><a name=\"$key\"></a>$headerText</h3>\n";
539                  # Get the entity names.                  # Get the entity names.
540                  my $fromEntity = $relationshipStructure->{from};                  my $fromEntity = $relationshipStructure->{from};
541                  my $toEntity = $relationshipStructure->{to};                  my $toEntity = $relationshipStructure->{to};
# Line 253  Line 545 
545                  # since both sentences will say the same thing.                  # since both sentences will say the same thing.
546                  my $arity = $relationshipStructure->{arity};                  my $arity = $relationshipStructure->{arity};
547                  if ($arity eq "11") {                  if ($arity eq "11") {
548                          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";
549                  } else {                  } else {
550                          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";
551                          if ($arity eq "MM" && $fromEntity ne $toEntity) {                          if ($arity eq "MM" && $fromEntity ne $toEntity) {
552                                  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";
553                          }                          }
554                  }                  }
555                  print HTMLOUT "</p>\n";          $retVal .= "</p>\n";
556                  # If there are notes on this relationship, display them.                  # If there are notes on this relationship, display them.
557                  if (my $notes = $relationshipStructure->{Notes}) {                  if (my $notes = $relationshipStructure->{Notes}) {
558                          print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";
559                  }                  }
560                  # Generate the relationship's relation table.                  # Generate the relationship's relation table.
561                  my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});                  my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});
562                  print HTMLOUT $htmlString;          $retVal .= $htmlString;
563          }          }
564        Trace("Building MetaData join table.") if T(4);
565          # Denote we're starting the join table.          # Denote we're starting the join table.
566          print HTMLOUT "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";      $retVal .= "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";
567          # Create a table header.          # Create a table header.
568          print HTMLOUT _OpenTable("Join Table", "Source", "Target", "Join Condition");      $retVal .= _OpenTable("Join Table", "Source", "Target", "Join Condition");
569          # Loop through the joins.          # Loop through the joins.
570          my $joinTable = $metadata->{Joins};          my $joinTable = $metadata->{Joins};
571          for my $joinKey (sort keys %{$joinTable}) {      my @joinKeys = keys %{$joinTable};
572        for my $joinKey (sort @joinKeys) {
573                  # Separate out the source, the target, and the join clause.                  # Separate out the source, the target, and the join clause.
574                  $joinKey =~ m!([^/]*)/(.*)$!;          $joinKey =~ m!^([^/]+)/(.+)$!;
575                  my ($source, $target, $clause) = ($self->ComputeObjectSentence($1),          my ($sourceRelation, $targetRelation) = ($1, $2);
576                                                                                    $self->ComputeObjectSentence($2),          Trace("Join with key $joinKey is from $sourceRelation to $targetRelation.") if T(Joins => 4);
577                                                                                    $joinTable->{$joinKey});          my $source = $self->ComputeObjectSentence($sourceRelation);
578            my $target = $self->ComputeObjectSentence($targetRelation);
579            my $clause = $joinTable->{$joinKey};
580                  # Display them in a table row.                  # Display them in a table row.
581                  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";
582          }          }
583          # Close the table.          # Close the table.
584          print HTMLOUT _CloseTable();      $retVal .= _CloseTable();
585          # Close the document.      Trace("Built MetaData HTML.") if T(3);
586          print HTMLOUT "</body>\n</html>\n";      # Return the HTML.
587          # Close the file.      return $retVal;
         close HTMLOUT;  
588  }  }
589    
590  =head3 DumpMetaData  =head3 DumpMetaData
591    
592  C<< $database->DumpMetaData(); >>  C<< $erdb->DumpMetaData(); >>
593    
594  Return a dump of the metadata structure.  Return a dump of the metadata structure.
595    
# Line 302  Line 597 
597    
598  sub DumpMetaData {  sub DumpMetaData {
599          # Get the parameters.          # Get the parameters.
600          my $self = shift @_;      my ($self) = @_;
601          # Dump the meta-data.          # Dump the meta-data.
602          return Data::Dumper::Dumper($self->{_metaData});          return Data::Dumper::Dumper($self->{_metaData});
603  }  }
604    
605  =head3 CreateTables  =head3 CreateTables
606    
607  C<< $datanase->CreateTables(); >>  C<< $erdb->CreateTables(); >>
608    
609  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
610  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 615 
615    
616  sub CreateTables {  sub CreateTables {
617          # Get the parameters.          # Get the parameters.
618          my $self = shift @_;      my ($self) = @_;
619          my $metadata = $self->{_metaData};      # Get the relation names.
620          my $dbh = $self->{_dbh};      my @relNames = $self->GetTableNames();
621          # Loop through the entities.      # Loop through the relations.
622          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}}) {  
623                          # Create a table for this relation.                          # Create a table for this relation.
624                          $self->CreateTable($relationName);                          $self->CreateTable($relationName);
625                          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);  
626          }          }
627  }  }
628    
629  =head3 CreateTable  =head3 CreateTable
630    
631  C<< $database->CreateTable($tableName, $indexFlag); >>  C<< $erdb->CreateTable($tableName, $indexFlag, $estimatedRows); >>
632    
633  Create the table for a relation and optionally create its indexes.  Create the table for a relation and optionally create its indexes.
634    
# Line 355  Line 638 
638    
639  Name of the relation (which will also be the table name).  Name of the relation (which will also be the table name).
640    
641  =item $indexFlag  =item indexFlag
642    
643  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,
644  L</CreateIndexes> must be called later to bring the indexes into existence.  L</CreateIndexes> must be called later to bring the indexes into existence.
645    
646    =item estimatedRows (optional)
647    
648    If specified, the estimated maximum number of rows for the relation. This
649    information allows the creation of tables using storage engines that are
650    faster but require size estimates, such as MyISAM.
651    
652  =back  =back
653    
654  =cut  =cut
655    
656  sub CreateTable {  sub CreateTable {
657          # Get the parameters.          # Get the parameters.
658          my $self = shift @_;      my ($self, $relationName, $indexFlag, $estimatedRows) = @_;
         my ($relationName, $indexFlag) = @_;  
659          # Get the database handle.          # Get the database handle.
660          my $dbh = $self->{_dbh};          my $dbh = $self->{_dbh};
661          # 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 679 
679          # Insure the table is not already there.          # Insure the table is not already there.
680          $dbh->drop_table(tbl => $relationName);          $dbh->drop_table(tbl => $relationName);
681          Trace("Table $relationName dropped.") if T(2);          Trace("Table $relationName dropped.") if T(2);
682        # If there are estimated rows, create an estimate so we can take advantage of
683        # faster DB technologies.
684        my $estimation = undef;
685        if ($estimatedRows) {
686            $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];
687        }
688          # Create the table.          # Create the table.
689          Trace("Creating table $relationName: $fieldThing") if T(2);          Trace("Creating table $relationName: $fieldThing") if T(2);
690          $dbh->create_table(tbl => $relationName, flds => $fieldThing);      $dbh->create_table(tbl => $relationName, flds => $fieldThing, estimates => $estimation);
691          Trace("Relation $relationName created in database.") if T(2);          Trace("Relation $relationName created in database.") if T(2);
692          # If we want to build the indexes, we do it here.          # If we want to build the indexes, we do it here.
693          if ($indexFlag) {          if ($indexFlag) {
# Line 401  Line 695 
695          }          }
696  }  }
697    
698    =head3 VerifyFields
699    
700    C<< my $count = $erdb->VerifyFields($relName, \@fieldList); >>
701    
702    Run through the list of proposed field values, insuring that all the character fields are
703    below the maximum length. If any fields are too long, they will be truncated in place.
704    
705    =over 4
706    
707    =item relName
708    
709    Name of the relation for which the specified fields are destined.
710    
711    =item fieldList
712    
713    Reference to a list, in order, of the fields to be put into the relation.
714    
715    =item RETURN
716    
717    Returns the number of fields truncated.
718    
719    =back
720    
721    =cut
722    
723    sub VerifyFields {
724        # Get the parameters.
725        my ($self, $relName, $fieldList) = @_;
726        # Initialize the return value.
727        my $retVal = 0;
728        # Get the relation definition.
729        my $relData = $self->_FindRelation($relName);
730        # Get the list of field descriptors.
731        my $fieldTypes = $relData->{Fields};
732        my $fieldCount = scalar @{$fieldTypes};
733        # Loop through the two lists.
734        for (my $i = 0; $i < $fieldCount; $i++) {
735            # Get the type of the current field.
736            my $fieldType = $fieldTypes->[$i]->{type};
737            # If it's a character field, verify the length.
738            if ($fieldType =~ /string/) {
739                my $maxLen = $TypeTable{$fieldType}->{maxLen};
740                my $oldString = $fieldList->[$i];
741                if (length($oldString) > $maxLen) {
742                    # Here it's too big, so we truncate it.
743                    Trace("Truncating field $i in relation $relName to $maxLen characters from \"$oldString\".") if T(1);
744                    $fieldList->[$i] = substr $oldString, 0, $maxLen;
745                    $retVal++;
746                }
747            }
748        }
749        # Return the truncation count.
750        return $retVal;
751    }
752    
753    =head3 DigestFields
754    
755    C<< $erdb->DigestFields($relName, $fieldList); >>
756    
757    Digest the strings in the field list that correspond to data type C<hash-string> in the
758    specified relation.
759    
760    =over 4
761    
762    =item relName
763    
764    Name of the relation to which the fields belong.
765    
766    =item fieldList
767    
768    List of field contents to be loaded into the relation.
769    
770    =back
771    
772    =cut
773    #: Return Type ;
774    sub DigestFields {
775        # Get the parameters.
776        my ($self, $relName, $fieldList) = @_;
777        # Get the relation definition.
778        my $relData = $self->_FindRelation($relName);
779        # Get the list of field descriptors.
780        my $fieldTypes = $relData->{Fields};
781        my $fieldCount = scalar @{$fieldTypes};
782        # Loop through the two lists.
783        for (my $i = 0; $i < $fieldCount; $i++) {
784            # Get the type of the current field.
785            my $fieldType = $fieldTypes->[$i]->{type};
786            # If it's a hash string, digest it in place.
787            if ($fieldType eq 'hash-string') {
788                $fieldList->[$i] = $self->DigestKey($fieldList->[$i]);
789            }
790        }
791    }
792    
793    =head3 DigestKey
794    
795    C<< my $digested = $erdb->DigestKey($keyValue); >>
796    
797    Return the digested value of a symbolic key. The digested value can then be plugged into a
798    key-based search into a table with key-type hash-string.
799    
800    Currently the digesting process is independent of the database structure, but that may not
801    always be the case, so this is an instance method instead of a static method.
802    
803    =over 4
804    
805    =item keyValue
806    
807    Key value to digest.
808    
809    =item RETURN
810    
811    Digested value of the key.
812    
813    =back
814    
815    =cut
816    
817    sub DigestKey {
818        # Get the parameters.
819        my ($self, $keyValue) = @_;
820        # Compute the digest.
821        my $retVal = md5_base64($keyValue);
822        # Return the result.
823        return $retVal;
824    }
825    
826  =head3 CreateIndex  =head3 CreateIndex
827    
828  C<< $database->CreateIndex($relationName); >>  C<< $erdb->CreateIndex($relationName); >>
829    
830  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
831  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.
832  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
833  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.
834    
835  =cut  =cut
836    
837  sub CreateIndex {  sub CreateIndex {
838          # Get the parameters.          # Get the parameters.
839          my $self = shift @_;      my ($self, $relationName) = @_;
         my ($relationName) = @_;  
840          # Get the relation's descriptor.          # Get the relation's descriptor.
841          my $relationData = $self->_FindRelation($relationName);          my $relationData = $self->_FindRelation($relationName);
842          # Get the database handle.          # Get the database handle.
843          my $dbh = $self->{_dbh};          my $dbh = $self->{_dbh};
844          # 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.
845          while (my ($indexName, $indexData) = each %{$relationData->{Indexes}}) {      my $indexHash = $relationData->{Indexes};
846        for my $indexName (keys %{$indexHash}) {
847            my $indexData = $indexHash->{$indexName};
848                  # Get the index's field list.                  # Get the index's field list.
849                  my @fieldList = _FixNames(@{$indexData->{IndexFields}});                  my @fieldList = _FixNames(@{$indexData->{IndexFields}});
850                  my $flds = join(', ', @fieldList);                  my $flds = join(', ', @fieldList);
851                  # Get the index's uniqueness flag.                  # Get the index's uniqueness flag.
852                  my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');                  my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');
853                  # Create the index.                  # Create the index.
854                  $dbh->create_index(idx => $indexName, tbl => $relationName, flds => $flds, unique => $unique);          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,
855                                        flds => $flds, unique => $unique);
856            if ($rv) {
857                  Trace("Index created: $indexName for $relationName ($flds)") if T(1);                  Trace("Index created: $indexName for $relationName ($flds)") if T(1);
858            } else {
859                Confess("Error creating index $indexName for $relationName using ($flds): " . $dbh->error_message());
860            }
861          }          }
862  }  }
863    
864  =head3 LoadTables  =head3 LoadTables
865    
866  C<< my $stats = $database->LoadTables($directoryName, $rebuild); >>  C<< my $stats = $erdb->LoadTables($directoryName, $rebuild); >>
867    
868  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
869  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 899 
899    
900  sub LoadTables {  sub LoadTables {
901          # Get the parameters.          # Get the parameters.
902          my $self = shift @_;      my ($self, $directoryName, $rebuild) = @_;
         my ($directoryName, $rebuild) = @_;  
903          # Start the timer.          # Start the timer.
904          my $startTime = gettimeofday;          my $startTime = gettimeofday;
905          # Clean any trailing slash from the directory name.          # Clean any trailing slash from the directory name.
906          $directoryName =~ s!/\\$!!;          $directoryName =~ s!/\\$!!;
907          # Declare the return variable.          # Declare the return variable.
908          my $retVal = Stats->new();          my $retVal = Stats->new();
909          # Get the metadata structure.      # Get the relation names.
910          my $metaData = $self->{_metaData};      my @relNames = $self->GetTableNames();
911          # 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}}) {  
912                          # Try to load this relation.                          # Try to load this relation.
913                          my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);                          my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);
914                          # Accumulate the statistics.                          # Accumulate the statistics.
915                          $retVal->Accumulate($result);                          $retVal->Accumulate($result);
916                  }                  }
         }  
         # 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);  
         }  
917          # Add the duration of the load to the statistical object.          # Add the duration of the load to the statistical object.
918          $retVal->Add('duration', gettimeofday - $startTime);          $retVal->Add('duration', gettimeofday - $startTime);
919          # Return the accumulated statistics.          # Return the accumulated statistics.
920          return $retVal;          return $retVal;
921  }  }
922    
923    
924  =head3 GetTableNames  =head3 GetTableNames
925    
926  C<< my @names = $database->GetTableNames; >>  C<< my @names = $erdb->GetTableNames; >>
927    
928  Return a list of the relations required to implement this database.  Return a list of the relations required to implement this database.
929    
# Line 514  Line 931 
931    
932  sub GetTableNames {  sub GetTableNames {
933          # Get the parameters.          # Get the parameters.
934          my $self = shift @_;      my ($self) = @_;
935          # Get the relation list from the metadata.          # Get the relation list from the metadata.
936          my $relationTable = $self->{_metaData}->{RelationTable};          my $relationTable = $self->{_metaData}->{RelationTable};
937          # Return the relation names.          # Return the relation names.
# Line 523  Line 940 
940    
941  =head3 GetEntityTypes  =head3 GetEntityTypes
942    
943  C<< my @names = $database->GetEntityTypes; >>  C<< my @names = $erdb->GetEntityTypes; >>
944    
945  Return a list of the entity type names.  Return a list of the entity type names.
946    
# Line 531  Line 948 
948    
949  sub GetEntityTypes {  sub GetEntityTypes {
950          # Get the database object.          # Get the database object.
951          my $self = shift @_;      my ($self) = @_;
952          # Get the entity list from the metadata object.          # Get the entity list from the metadata object.
953          my $entityList = $self->{_metaData}->{Entities};          my $entityList = $self->{_metaData}->{Entities};
954          # Return the list of entity names in alphabetical order.          # Return the list of entity names in alphabetical order.
955          return sort keys %{$entityList};          return sort keys %{$entityList};
956  }  }
957    
958    =head3 IsEntity
959    
960    C<< my $flag = $erdb->IsEntity($entityName); >>
961    
962    Return TRUE if the parameter is an entity name, else FALSE.
963    
964    =over 4
965    
966    =item entityName
967    
968    Object name to be tested.
969    
970    =item RETURN
971    
972    Returns TRUE if the specified string is an entity name, else FALSE.
973    
974    =back
975    
976    =cut
977    
978    sub IsEntity {
979        # Get the parameters.
980        my ($self, $entityName) = @_;
981        # Test to see if it's an entity.
982        return exists $self->{_metaData}->{Entities}->{$entityName};
983    }
984    
985  =head3 Get  =head3 Get
986    
987  C<< my $query = $database->Get(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>  C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>
988    
989  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.
990  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 992 
992  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
993  $genus.  $genus.
994    
995  C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", $genus); >>  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>
996    
997  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
998  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
999    
1000  C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>
1001    
1002  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
1003  characters inside the variable C<$genus>.  characters inside the variable C<$genus>.
# Line 565  Line 1009 
1009  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
1010  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,
1011    
1012  C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", $genus); >>  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>
1013    
1014  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
1015  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.
1016  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
1017  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
1018  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  
1019  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,
1020  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.
1021    
1022    If an entity or relationship is mentioned twice, the name for the second occurrence will
1023    be suffixed with C<2>, the third occurrence will be suffixed with C<3>, and so forth. So,
1024    for example, if we have C<['Feature', 'HasContig', 'Contig', 'HasContig']>, then the
1025    B<to-link> field of the first B<HasContig> is specified as C<HasContig(to-link)>, while
1026    the B<to-link> field of the second B<HasContig> is specified as C<HasContig2(to-link)>.
1027    
1028  =over 4  =over 4
1029    
1030  =item objectNames  =item objectNames
# Line 598  Line 1047 
1047    
1048  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>
1049    
1050    Note that the case is important. Only an uppercase "ORDER BY" with a single space will
1051    be processed. The idea is to make it less likely to find the verb by accident.
1052    
1053  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
1054  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
1055  relation.  relation.
1056    
1057  =item param1, param2, ..., paramN  Finally, you can limit the number of rows returned by adding a LIMIT clause. The LIMIT must
1058    be the last thing in the filter clause, and it contains only the word "LIMIT" followed by
1059    a positive number. So, for example
1060    
1061  Parameter values to be substituted into the filter clause.  C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>
1062    
1063    will only return the first ten genomes for the specified genus. The ORDER BY clause is not
1064    required. For example, to just get the first 10 genomes in the B<Genome> table, you could
1065    use
1066    
1067    C<< "LIMIT 10" >>
1068    
1069    =item params
1070    
1071    Reference to a list of parameter values to be substituted into the filter clause.
1072    
1073  =item RETURN  =item RETURN
1074    
# Line 616  Line 1080 
1080    
1081  sub Get {  sub Get {
1082          # Get the parameters.          # Get the parameters.
1083          my $self = shift @_;      my ($self, $objectNames, $filterClause, $params) = @_;
1084          my ($objectNames, $filterClause, @params) = @_;      # Process the SQL stuff.
1085          # Construct the SELECT statement. The general pattern is      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1086          #          $self->_SetupSQL($objectNames, $filterClause);
1087          # SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN      # Create the query.
1088          #      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .
1089          my $dbh = $self->{_dbh};          ".* $suffix";
1090          my $command = "SELECT DISTINCT " . join('.*, ', @{$objectNames}) . ".* FROM " .      my $sth = $self->_GetStatementHandle($command, $params);
1091                                  join(', ', @{$objectNames});      # Now we create the relation map, which enables DBQuery to determine the order, name
1092          # Check for a filter clause.      # and mapped name for each object in the query.
1093          if ($filterClause) {      my @relationMap = ();
1094                  # Here we have one, so we convert its field names and add it to the query. First,      for my $mappedName (@{$mappedNameListRef}) {
1095                  # 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;  
1096                  }                  }
1097                  # We are ready to begin. We loop through the object names, replacing each      # Return the statement object.
1098                  # object name's field references by the corresponding SQL field reference.      my $retVal = DBQuery::_new($self, $sth, \@relationMap);
1099                  # Along the way, if we find a secondary relation, we will need to add it      return $retVal;
1100                  # to the FROM clause.  }
1101                  for my $objectName (@sortedNames) {  
1102                          # Get the length of the object name plus 2. This is the value we add to the  =head3 GetFlat
1103                          # size of the field name to determine the size of the field reference as a  
1104                          # whole.  C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>
1105                          my $nameLength = 2 + length $objectName;  
1106                          # Get the object's field list.  This is a variation of L</GetAll> that asks for only a single field per record and
1107                          my $fieldList = $self->_GetFieldTable($objectName);  returns a single flattened list.
1108                          # Find the field references for this object.  
1109                          while ($filterString =~ m/$objectName\(([^)]*)\)/g) {  =over 4
1110                                  # At this point, $1 contains the field name, and the current position  
1111                                  # is set immediately after the final parenthesis. We pull out the name of  =item objectNames
1112                                  # the field and the position and length of the field reference as a whole.  
1113                                  my $fieldName = $1;  List containing the names of the entity and relationship objects to be retrieved.
1114                                  my $len = $nameLength + length $fieldName;  
1115                                  my $pos = pos($filterString) - $len;  =item filterClause
1116                                  # Insure the field exists.  
1117                                  if (!exists $fieldList->{$fieldName}) {  WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1118                                          Confess("Field $fieldName not found for object $objectName.");  be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1119    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1120    parameter list as additional parameters. The fields in a filter clause can come from primary
1121    entity relations, relationship relations, or secondary entity relations; however, all of the
1122    entities and relationships involved must be included in the list of object names.
1123    
1124    =item parameterList
1125    
1126    List of the parameters to be substituted in for the parameters marks in the filter clause.
1127    
1128    =item field
1129    
1130    Name of the field to be used to get the elements of the list returned.
1131    
1132    =item RETURN
1133    
1134    Returns a list of values.
1135    
1136    =back
1137    
1138    =cut
1139    #: Return Type @;
1140    sub GetFlat {
1141        # Get the parameters.
1142        my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
1143        # Construct the query.
1144        my $query = $self->Get($objectNames, $filterClause, $parameterList);
1145        # Create the result list.
1146        my @retVal = ();
1147        # Loop through the records, adding the field values found to the result list.
1148        while (my $row = $query->Fetch()) {
1149            push @retVal, $row->Value($field);
1150        }
1151        # Return the list created.
1152        return @retVal;
1153    }
1154    
1155    =head3 Delete
1156    
1157    C<< my $stats = $erdb->Delete($entityName, $objectID); >>
1158    
1159    Delete an entity instance from the database. The instance is deleted along with all entity and
1160    relationship instances dependent on it. The idea of dependence here is recursive. An object is
1161    always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many
1162    relationship connected to a dependent entity or the "to" entity connected to a 1-to-many
1163    dependent relationship.
1164    
1165    =over 4
1166    
1167    =item entityName
1168    
1169    Name of the entity type for the instance being deleted.
1170    
1171    =item objectID
1172    
1173    ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),
1174    then it is presumed to by a LIKE pattern.
1175    
1176    =item testFlag
1177    
1178    If TRUE, the delete statements will be traced without being executed.
1179    
1180    =item RETURN
1181    
1182    Returns a statistics object indicating how many records of each particular table were
1183    deleted.
1184    
1185    =back
1186    
1187    =cut
1188    #: Return Type $%;
1189    sub Delete {
1190        # Get the parameters.
1191        my ($self, $entityName, $objectID, $testFlag) = @_;
1192        # Declare the return variable.
1193        my $retVal = Stats->new();
1194        # Get the DBKernel object.
1195        my $db = $self->{_dbh};
1196        # We're going to generate all the paths branching out from the starting entity. One of
1197        # the things we have to be careful about is preventing loops. We'll use a hash to
1198        # determine if we've hit a loop.
1199        my %alreadyFound = ();
1200        # These next lists will serve as our result stack. We start by pushing object lists onto
1201        # the stack, and then popping them off to do the deletes. This means the deletes will
1202        # start with the longer paths before getting to the shorter ones. That, in turn, makes
1203        # sure we don't delete records that might be needed to forge relationships back to the
1204        # original item. We have two lists-- one for TO-relationships, and one for
1205        # FROM-relationships and entities.
1206        my @fromPathList = ();
1207        my @toPathList = ();
1208        # This final hash is used to remember what work still needs to be done. We push paths
1209        # onto the list, then pop them off to extend the paths. We prime it with the starting
1210        # point. Note that we will work hard to insure that the last item on a path in the
1211        # TODO list is always an entity.
1212        my @todoList = ([$entityName]);
1213        while (@todoList) {
1214            # Get the current path.
1215            my $current = pop @todoList;
1216            # Copy it into a list.
1217            my @stackedPath = @{$current};
1218            # Pull off the last item on the path. It will always be an entity.
1219            my $entityName = pop @stackedPath;
1220            # Add it to the alreadyFound list.
1221            $alreadyFound{$entityName} = 1;
1222            # Get the entity data.
1223            my $entityData = $self->_GetStructure($entityName);
1224            # The first task is to loop through the entity's relation. A DELETE command will
1225            # be needed for each of them.
1226            my $relations = $entityData->{Relations};
1227            for my $relation (keys %{$relations}) {
1228                my @augmentedList = (@stackedPath, $relation);
1229                push @fromPathList, \@augmentedList;
1230            }
1231            # Now we need to look for relationships connected to this entity.
1232            my $relationshipList = $self->{_metaData}->{Relationships};
1233            for my $relationshipName (keys %{$relationshipList}) {
1234                my $relationship = $relationshipList->{$relationshipName};
1235                # Check the FROM field. We're only interested if it's us.
1236                if ($relationship->{from} eq $entityName) {
1237                    # Add the path to this relationship.
1238                    my @augmentedList = (@stackedPath, $entityName, $relationshipName);
1239                    push @fromPathList, \@augmentedList;
1240                    # Check the arity. If it's MM we're done. If it's 1M
1241                    # and the target hasn't been seen yet, we want to
1242                    # stack the entity for future processing.
1243                    if ($relationship->{arity} eq '1M') {
1244                        my $toEntity = $relationship->{to};
1245                        if (! exists $alreadyFound{$toEntity}) {
1246                            # Here we have a new entity that's dependent on
1247                            # the current entity, so we need to stack it.
1248                            my @stackList = (@augmentedList, $toEntity);
1249                            push @fromPathList, \@stackList;
1250                                  } else {                                  } else {
1251                                          # Get the field's relation.                          Trace("$toEntity ignored because it occurred previously.") if T(4);
                                         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;  
1252                                          }                                          }
                                         # Form an SQL field reference from the relation name and the field name.  
                                         my $sqlReference = "$relationName." . _FixName($fieldName);  
                                         # Put it into the filter string in place of the old value.  
                                         substr($filterString, $pos, $len) = $sqlReference;  
                                         # Reposition the search.  
                                         pos $filterString = $pos + length $sqlReference;  
1253                                  }                                  }
1254                          }                          }
1255                # Now check the TO field. In this case only the relationship needs
1256                # deletion.
1257                if ($relationship->{to} eq $entityName) {
1258                    my @augmentedList = (@stackedPath, $entityName, $relationshipName);
1259                    push @toPathList, \@augmentedList;
1260                  }                  }
1261                  # The next step is to join the objects together. We only need to do this if there          }
1262                  # is more than one object in the object list. We start with the first object and      }
1263                  # run through the objects after it. Note also that we make a safety copy of the      # Create the first qualifier for the WHERE clause. This selects the
1264                  # list before running through it.      # keys of the primary entity records to be deleted. When we're deleting
1265                  my @objectList = @{$objectNames};      # from a dependent table, we construct a join page from the first qualifier
1266                  my $lastObject = shift @objectList;      # to the table containing the dependent records to delete.
1267                  # Get the join table.      my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");
1268                  my $joinTable = $self->{_metaData}->{Joins};      # We need to make two passes. The first is through the to-list, and
1269                  # Loop through the object list.      # the second through the from-list. The from-list is second because
1270                  for my $thisObject (@objectList) {      # the to-list may need to pass through some of the entities the
1271                          # Look for a join.      # from-list would delete.
1272                          my $joinKey = "$lastObject/$thisObject";      my %stackList = ( from_link => \@fromPathList, to_link => \@toPathList );
1273                          if (!exists $joinTable->{$joinKey}) {      # Now it's time to do the deletes. We do it in two passes.
1274                                  # Here there's no join, so we throw an error.      for my $keyName ('to_link', 'from_link') {
1275                                  Confess("No join exists to connect from $lastObject to $thisObject.");          # Get the list for this key.
1276            my @pathList = @{$stackList{$keyName}};
1277            Trace(scalar(@pathList) . " entries in path list for $keyName.") if T(3);
1278            # Loop through this list.
1279            while (my $path = pop @pathList) {
1280                # Get the table whose rows are to be deleted.
1281                my @pathTables = @{$path};
1282                # Start the DELETE statement. We need to call DBKernel because the
1283                # syntax of a DELETE-USING varies among DBMSs.
1284                my $target = $pathTables[$#pathTables];
1285                my $stmt = $db->SetUsing(@pathTables);
1286                # Now start the WHERE. The first thing is the ID field from the starting table. That
1287                # starting table will either be the entity relation or one of the entity's
1288                # sub-relations.
1289                $stmt .= " WHERE $pathTables[0].id $qualifier";
1290                # Now we run through the remaining entities in the path, connecting them up.
1291                for (my $i = 1; $i <= $#pathTables; $i += 2) {
1292                    # Connect the current relationship to the preceding entity.
1293                    my ($entity, $rel) = @pathTables[$i-1,$i];
1294                    # The style of connection depends on the direction of the relationship.
1295                    $stmt .= " AND $entity.id = $rel.$keyName";
1296                    if ($i + 1 <= $#pathTables) {
1297                        # Here there's a next entity, so connect that to the relationship's
1298                        # to-link.
1299                        my $entity2 = $pathTables[$i+1];
1300                        $stmt .= " AND $rel.to_link = $entity2.id";
1301                    }
1302                }
1303                # Now we have our desired DELETE statement.
1304                if ($testFlag) {
1305                    # Here the user wants to trace without executing.
1306                    Trace($stmt) if T(0);
1307                          } else {                          } else {
1308                                  # Get the join clause and add it to the WHERE list.                  # Here we can delete. Note that the SQL method dies with a confessing
1309                                  push @joinWhere, $joinTable->{$joinKey};                  # if an error occurs, so we just go ahead and do it.
1310                                  # Save this object as the last object for the next iteration.                  Trace("Executing delete from $target using '$objectID'.") if T(3);
1311                                  $lastObject = $thisObject;                  my $rv = $db->SQL($stmt, 0, $objectID);
1312                    # Accumulate the statistics for this delete. The only rows deleted
1313                    # are from the target table, so we use its name to record the
1314                    # statistic.
1315                    $retVal->Add($target, $rv);
1316                          }                          }
1317                  }                  }
                 # 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;  
1318                  }                  }
1319                  # Add the filter and the join clauses (if any) to the SELECT command.      # Return the result.
1320                  if ($filterString) {      return $retVal;
                         push @joinWhere, "($filterString)";  
1321                  }                  }
1322                  if (@joinWhere) {  
1323                          $command .= " WHERE " . join(' AND ', @joinWhere);  =head3 GetList
1324    
1325    C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>
1326    
1327    Return a list of object descriptors for the specified objects as determined by the
1328    specified filter clause.
1329    
1330    This method is essentially the same as L</Get> except it returns a list of objects rather
1331    than a query object that can be used to get the results one record at a time.
1332    
1333    =over 4
1334    
1335    =item objectNames
1336    
1337    List containing the names of the entity and relationship objects to be retrieved.
1338    
1339    =item filterClause
1340    
1341    WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1342    be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
1343    specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
1344    in the filter clause should be added to the parameter list as additional parameters. The
1345    fields in a filter clause can come from primary entity relations, relationship relations,
1346    or secondary entity relations; however, all of the entities and relationships involved must
1347    be included in the list of object names.
1348    
1349    The filter clause can also specify a sort order. To do this, simply follow the filter string
1350    with an ORDER BY clause. For example, the following filter string gets all genomes for a
1351    particular genus and sorts them by species name.
1352    
1353    C<< "Genome(genus) = ? ORDER BY Genome(species)" >>
1354    
1355    The rules for field references in a sort order are the same as those for field references in the
1356    filter clause in general; however, odd things may happen if a sort field is from a secondary
1357    relation.
1358    
1359    =item params
1360    
1361    Reference to a list of parameter values to be substituted into the filter clause.
1362    
1363    =item RETURN
1364    
1365    Returns a list of B<DBObject>s that satisfy the query conditions.
1366    
1367    =back
1368    
1369    =cut
1370    #: Return Type @%
1371    sub GetList {
1372        # Get the parameters.
1373        my ($self, $objectNames, $filterClause, $params) = @_;
1374        # Declare the return variable.
1375        my @retVal = ();
1376        # Perform the query.
1377        my $query = $self->Get($objectNames, $filterClause, $params);
1378        # Loop through the results.
1379        while (my $object = $query->Fetch) {
1380            push @retVal, $object;
1381                  }                  }
1382                  # Add the sort clause (if any) to the SELECT command.      # Return the result.
1383                  if ($orderClause) {      return @retVal;
1384                          $command .= " ORDER BY $orderClause";  }
1385    
1386    =head3 GetCount
1387    
1388    C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>
1389    
1390    Return the number of rows found by a specified query. This method would
1391    normally be used to count the records in a single table. For example, in a
1392    genetics database
1393    
1394        my $count = $erdb->GetCount(['Genome'], 'Genome(genus-species) LIKE ?', ['homo %']);
1395    
1396    would return the number of genomes for the genus I<homo>. It is conceivable, however,
1397    to use it to return records based on a join. For example,
1398    
1399        my $count = $erdb->GetCount(['HasFeature', 'Genome'], 'Genome(genus-species) LIKE ?',
1400                                    ['homo %']);
1401    
1402    would return the number of features for genomes in the genus I<homo>. Note that
1403    only the rows from the first table are counted. If the above command were
1404    
1405        my $count = $erdb->GetCount(['Genome', 'Feature'], 'Genome(genus-species) LIKE ?',
1406                                    ['homo %']);
1407    
1408    it would return the number of genomes, not the number of genome/feature pairs.
1409    
1410    =over 4
1411    
1412    =item objectNames
1413    
1414    Reference to a list of the objects (entities and relationships) included in the
1415    query.
1416    
1417    =item filter
1418    
1419    A filter clause for restricting the query. The rules are the same as for the L</Get>
1420    method.
1421    
1422    =item params
1423    
1424    Reference to a list of the parameter values to be substituted for the parameter marks
1425    in the filter.
1426    
1427    =item RETURN
1428    
1429    Returns a count of the number of records in the first table that would satisfy
1430    the query.
1431    
1432    =back
1433    
1434    =cut
1435    
1436    sub GetCount {
1437        # Get the parameters.
1438        my ($self, $objectNames, $filter, $params) = @_;
1439        # Insure the params argument is an array reference if the caller left it off.
1440        if (! defined($params)) {
1441            $params = [];
1442        }
1443        # Declare the return variable.
1444        my $retVal;
1445        # Find out if we're counting an entity or a relationship.
1446        my $countedField;
1447        if ($self->IsEntity($objectNames->[0])) {
1448            $countedField = "id";
1449        } else {
1450            # For a relationship we count the to-link because it's usually more
1451            # numerous. Note we're automatically converting to the SQL form
1452            # of the field name (to_link vs. to-link).
1453            $countedField = "to_link";
1454        }
1455        # Create the SQL command suffix to get the desired records.
1456        my ($suffix, $mappedNameListRef, $mappedNameHashRef) = $self->_SetupSQL($objectNames,
1457                                                                                $filter);
1458        # Prefix it with text telling it we want a record count.
1459        my $firstObject = $mappedNameListRef->[0];
1460        my $command = "SELECT COUNT($firstObject.$countedField) $suffix";
1461        # Prepare and execute the command.
1462        my $sth = $self->_GetStatementHandle($command, $params);
1463        # Get the count value.
1464        ($retVal) = $sth->fetchrow_array();
1465        # Check for a problem.
1466        if (! defined($retVal)) {
1467            if ($sth->err) {
1468                # Here we had an SQL error.
1469                Confess("Error retrieving row count: " . $sth->errstr());
1470            } else {
1471                # Here we have no result.
1472                Confess("No result attempting to retrieve row count.");
1473                  }                  }
1474          }          }
1475          Trace("SQL query: $command") if T(2);      # Return the result.
         Trace("PARMS: '" . (join "', '", @params) . "'") if (T(3) && (@params > 0));  
         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});  
1476          return $retVal;          return $retVal;
1477  }  }
1478    
1479  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
1480    
1481  C<< my $sentence = $database->ComputeObjectSentence($objectName); >>  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>
1482    
1483  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.
1484    
# Line 761  Line 1498 
1498    
1499  sub ComputeObjectSentence {  sub ComputeObjectSentence {
1500          # Get the parameters.          # Get the parameters.
1501          my $self = shift @_;      my ($self, $objectName) = @_;
         my ($objectName) = @_;  
1502          # Set the default return value.          # Set the default return value.
1503          my $retVal = $objectName;          my $retVal = $objectName;
1504          # Look for the object as a relationship.          # Look for the object as a relationship.
# Line 777  Line 1513 
1513    
1514  =head3 DumpRelations  =head3 DumpRelations
1515    
1516  C<< $database->DumpRelations($outputDirectory); >>  C<< $erdb->DumpRelations($outputDirectory); >>
1517    
1518  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.
1519  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 1530 
1530    
1531  sub DumpRelations {  sub DumpRelations {
1532          # Get the parameters.          # Get the parameters.
1533          my $self = shift @_;      my ($self, $outputDirectory) = @_;
         my ($outputDirectory) = @_;  
1534          # 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.
1535          my $metaData = $self->{_metaData};          my $metaData = $self->{_metaData};
1536          my $entities = $metaData->{Entities};          my $entities = $metaData->{Entities};
1537          while (my ($entityName, $entityStructure) = each %{$entities}) {      for my $entityName (keys %{$entities}) {
1538            my $entityStructure = $entities->{$entityName};
1539                  # Get the entity's relations.                  # Get the entity's relations.
1540                  my $relationList = $entityStructure->{Relations};                  my $relationList = $entityStructure->{Relations};
1541                  # Loop through the relations, dumping them.                  # Loop through the relations, dumping them.
1542                  while (my ($relationName, $relation) = each %{$relationList}) {          for my $relationName (keys %{$relationList}) {
1543                my $relation = $relationList->{$relationName};
1544                          $self->_DumpRelation($outputDirectory, $relationName, $relation);                          $self->_DumpRelation($outputDirectory, $relationName, $relation);
1545                  }                  }
1546          }          }
1547          # Next, we loop through the relationships.          # Next, we loop through the relationships.
1548          my $relationships = $metaData->{Relationships};          my $relationships = $metaData->{Relationships};
1549          while (my ($relationshipName, $relationshipStructure) = each %{$relationships}) {      for my $relationshipName (keys %{$relationships}) {
1550            my $relationshipStructure = $relationships->{$relationshipName};
1551                  # Dump this relationship's relation.                  # Dump this relationship's relation.
1552                  $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});                  $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});
1553          }          }
1554  }  }
1555    
1556    =head3 InsertValue
1557    
1558    C<< $erdb->InsertValue($entityID, $fieldName, $value); >>
1559    
1560    This method will insert a new value into the database. The value must be one
1561    associated with a secondary relation, since primary values cannot be inserted:
1562    they occur exactly once. Secondary values, on the other hand, can be missing
1563    or multiply-occurring.
1564    
1565    =over 4
1566    
1567    =item entityID
1568    
1569    ID of the object that is to receive the new value.
1570    
1571    =item fieldName
1572    
1573    Field name for the new value-- this includes the entity name, since
1574    field names are of the format I<objectName>C<(>I<fieldName>C<)>.
1575    
1576    =item value
1577    
1578    New value to be put in the field.
1579    
1580    =back
1581    
1582    =cut
1583    
1584    sub InsertValue {
1585        # Get the parameters.
1586        my ($self, $entityID, $fieldName, $value) = @_;
1587        # Parse the entity name and the real field name.
1588        if ($fieldName =~ /^([^(]+)\(([^)]+)\)/) {
1589            my $entityName = $1;
1590            my $fieldTitle = $2;
1591            # Get its descriptor.
1592            if (!$self->IsEntity($entityName)) {
1593                Confess("$entityName is not a valid entity.");
1594            } else {
1595                my $entityData = $self->{_metaData}->{Entities}->{$entityName};
1596                # Find the relation containing this field.
1597                my $fieldHash = $entityData->{Fields};
1598                if (! exists $fieldHash->{$fieldTitle}) {
1599                    Confess("$fieldTitle not found in $entityName.");
1600                } else {
1601                    my $relation = $fieldHash->{$fieldTitle}->{relation};
1602                    if ($relation eq $entityName) {
1603                        Confess("Cannot do InsertValue on primary field $fieldTitle of $entityName.");
1604                    } else {
1605                        # Now we can create an INSERT statement.
1606                        my $dbh = $self->{_dbh};
1607                        my $fixedName = _FixName($fieldTitle);
1608                        my $statement = "INSERT INTO $relation (id, $fixedName) VALUES(?, ?)";
1609                        # Execute the command.
1610                        $dbh->SQL($statement, 0, $entityID, $value);
1611                    }
1612                }
1613            }
1614        } else {
1615            Confess("$fieldName is not a valid field name.");
1616        }
1617    }
1618    
1619  =head3 InsertObject  =head3 InsertObject
1620    
1621  C<< my $ok = $database->InsertObject($objectType, \%fieldHash); >>  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>
1622    
1623  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
1624  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 1627 
1627  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
1628  C<ZP_00210270.1> and C<gi|46206278>.  C<ZP_00210270.1> and C<gi|46206278>.
1629    
1630  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']}); >>
1631    
1632  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
1633  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>.
1634    
1635  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'}); >>
1636    
1637  =over 4  =over 4
1638    
# Line 853  Line 1654 
1654    
1655  sub InsertObject {  sub InsertObject {
1656          # Get the parameters.          # Get the parameters.
1657          my $self = shift @_;      my ($self, $newObjectType, $fieldHash) = @_;
         my ($newObjectType, $fieldHash) = @_;  
1658          # Denote that so far we appear successful.          # Denote that so far we appear successful.
1659          my $retVal = 1;          my $retVal = 1;
1660          # Get the database handle.          # Get the database handle.
# Line 864  Line 1664 
1664          # 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
1665          # 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
1666          # stop the loop.          # stop the loop.
1667          while ($retVal && (my ($relationName, $relationDefinition) = each %{$relationTable})) {      my @relationList = keys %{$relationTable};
1668        for (my $i = 0; $retVal && $i <= $#relationList; $i++) {
1669            my $relationName = $relationList[$i];
1670            my $relationDefinition = $relationTable->{$relationName};
1671                  # 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
1672                  # 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
1673                  # @missing list.                  # @missing list.
# Line 939  Line 1742 
1742                                                  push @parameterList, $value;                                                  push @parameterList, $value;
1743                                          }                                          }
1744                                  }                                  }
1745                                  # Execute the INSERT statement with the specified parameter list.                  # Execute the INSERT statement with the specified parameter list.
1746                                  $retVal = $sth->execute(@parameterList);                  $retVal = $sth->execute(@parameterList);
1747                                  if (!$retVal) {                  if (!$retVal) {
1748                                          my $errorString = $sth->errstr();                      my $errorString = $sth->errstr();
1749                                          Trace("Insert error: $errorString.") if T(0);                      Trace("Insert error: $errorString.") if T(0);
1750                    }
1751                }
1752            }
1753        }
1754        # Return the success indicator.
1755        return $retVal;
1756    }
1757    
1758    =head3 LoadTable
1759    
1760    C<< my %results = $erdb->LoadTable($fileName, $relationName, $truncateFlag); >>
1761    
1762    Load data from a tab-delimited file into a specified table, optionally re-creating the table
1763    first.
1764    
1765    =over 4
1766    
1767    =item fileName
1768    
1769    Name of the file from which the table data should be loaded.
1770    
1771    =item relationName
1772    
1773    Name of the relation to be loaded. This is the same as the table name.
1774    
1775    =item truncateFlag
1776    
1777    TRUE if the table should be dropped and re-created, else FALSE
1778    
1779    =item RETURN
1780    
1781    Returns a statistical object containing a list of the error messages.
1782    
1783    =back
1784    
1785    =cut
1786    sub LoadTable {
1787        # Get the parameters.
1788        my ($self, $fileName, $relationName, $truncateFlag) = @_;
1789        # Create the statistical return object.
1790        my $retVal = _GetLoadStats();
1791        # Trace the fact of the load.
1792        Trace("Loading table $relationName from $fileName") if T(2);
1793        # Get the database handle.
1794        my $dbh = $self->{_dbh};
1795        # Get the input file size.
1796        my $fileSize = -s $fileName;
1797        # Get the relation data.
1798        my $relation = $self->_FindRelation($relationName);
1799        # Check the truncation flag.
1800        if ($truncateFlag) {
1801            Trace("Creating table $relationName") if T(2);
1802            # Compute the row count estimate. We take the size of the load file,
1803            # divide it by the estimated row size, and then multiply by 1.5 to
1804            # leave extra room. We postulate a minimum row count of 1000 to
1805            # prevent problems with incoming empty load files.
1806            my $rowSize = $self->EstimateRowSize($relationName);
1807            my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);
1808            # Re-create the table without its index.
1809            $self->CreateTable($relationName, 0, $estimate);
1810            # If this is a pre-index DBMS, create the index here.
1811            if ($dbh->{_preIndex}) {
1812                eval {
1813                    $self->CreateIndex($relationName);
1814                };
1815                if ($@) {
1816                    $retVal->AddMessage($@);
1817                }
1818            }
1819        }
1820        # Load the table.
1821        my $rv;
1822        eval {
1823            $rv = $dbh->load_table(file => $fileName, tbl => $relationName);
1824        };
1825        if (!defined $rv) {
1826            $retVal->AddMessage($@) if ($@);
1827            $retVal->AddMessage("Table load failed for $relationName using $fileName.");
1828            Trace("Table load failed for $relationName.") if T(1);
1829        } else {
1830            # Here we successfully loaded the table.
1831            $retVal->Add("tables");
1832            my $size = -s $fileName;
1833            Trace("$size bytes loaded into $relationName.") if T(2);
1834            # If we're rebuilding, we need to create the table indexes.
1835            if ($truncateFlag && ! $dbh->{_preIndex}) {
1836                eval {
1837                    $self->CreateIndex($relationName);
1838                };
1839                if ($@) {
1840                    $retVal->AddMessage($@);
1841                }
1842            }
1843        }
1844        # Analyze the table to improve performance.
1845        Trace("Analyzing and compacting $relationName.") if T(3);
1846        $dbh->vacuum_it($relationName);
1847        Trace("$relationName load completed.") if T(3);
1848        # Return the statistics.
1849        return $retVal;
1850    }
1851    
1852    =head3 GenerateEntity
1853    
1854    C<< my $fieldHash = $erdb->GenerateEntity($id, $type, \%values); >>
1855    
1856    Generate the data for a new entity instance. This method creates a field hash suitable for
1857    passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest
1858    of the fields are generated using information in the database schema.
1859    
1860    Each data type has a default algorithm for generating random test data. This can be overridden
1861    by including a B<DataGen> element in the field. If this happens, the content of the element is
1862    executed as a PERL program in the context of this module. The element may make use of a C<$this>
1863    variable which contains the field hash as it has been built up to the current point. If any
1864    fields are dependent on other fields, the C<pass> attribute can be used to control the order
1865    in which the fields are generated. A field with a high data pass number will be generated after
1866    a field with a lower one. If any external values are needed, they should be passed in via the
1867    optional third parameter, which will be available to the data generation script under the name
1868    C<$value>. Several useful utility methods are provided for generating random values, including
1869    L</IntGen>, L</StringGen>, L</FloatGen>, and L</DateGen>. Note that dates are stored and generated
1870    in the form of a timestamp number rather than a string.
1871    
1872    =over 4
1873    
1874    =item id
1875    
1876    ID to assign to the new entity.
1877    
1878    =item type
1879    
1880    Type name for the new entity.
1881    
1882    =item values
1883    
1884    Hash containing additional values that might be needed by the data generation methods (optional).
1885    
1886    =back
1887    
1888    =cut
1889    
1890    sub GenerateEntity {
1891        # Get the parameters.
1892        my ($self, $id, $type, $values) = @_;
1893        # Create the return hash.
1894        my $this = { id => $id };
1895        # Get the metadata structure.
1896        my $metadata = $self->{_metaData};
1897        # Get this entity's list of fields.
1898        if (!exists $metadata->{Entities}->{$type}) {
1899            Confess("Unrecognized entity type $type in GenerateEntity.");
1900        } else {
1901            my $entity = $metadata->{Entities}->{$type};
1902            my $fields = $entity->{Fields};
1903            # Generate data from the fields.
1904            _GenerateFields($this, $fields, $type, $values);
1905        }
1906        # Return the hash created.
1907        return $this;
1908    }
1909    
1910    =head3 GetEntity
1911    
1912    C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >>
1913    
1914    Return an object describing the entity instance with a specified ID.
1915    
1916    =over 4
1917    
1918    =item entityType
1919    
1920    Entity type name.
1921    
1922    =item ID
1923    
1924    ID of the desired entity.
1925    
1926    =item RETURN
1927    
1928    Returns a B<DBObject> representing the desired entity instance, or an undefined value if no
1929    instance is found with the specified key.
1930    
1931    =back
1932    
1933    =cut
1934    
1935    sub GetEntity {
1936        # Get the parameters.
1937        my ($self, $entityType, $ID) = @_;
1938        # Create a query.
1939        my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
1940        # Get the first (and only) object.
1941        my $retVal = $query->Fetch();
1942        # Return the result.
1943        return $retVal;
1944    }
1945    
1946    =head3 GetChoices
1947    
1948    C<< my @values = $erdb->GetChoices($entityName, $fieldName); >>
1949    
1950    Return a list of all the values for the specified field that are represented in the
1951    specified entity.
1952    
1953    Note that if the field is not indexed, then this will be a very slow operation.
1954    
1955    =over 4
1956    
1957    =item entityName
1958    
1959    Name of an entity in the database.
1960    
1961    =item fieldName
1962    
1963    Name of a field belonging to the entity. This is a raw field name without
1964    the standard parenthesized notation used in most calls.
1965    
1966    =item RETURN
1967    
1968    Returns a list of the distinct values for the specified field in the database.
1969    
1970    =back
1971    
1972    =cut
1973    
1974    sub GetChoices {
1975        # Get the parameters.
1976        my ($self, $entityName, $fieldName) = @_;
1977        # Declare the return variable.
1978        my @retVal;
1979        # Get the entity data structure.
1980        my $entityData = $self->_GetStructure($entityName);
1981        # Get the field.
1982        my $fieldHash = $entityData->{Fields};
1983        if (! exists $fieldHash->{$fieldName}) {
1984            Confess("$fieldName not found in $entityName.");
1985        } else {
1986            # Get the name of the relation containing the field.
1987            my $relation = $fieldHash->{$fieldName}->{relation};
1988            # Fix up the field name.
1989            my $realName = _FixName($fieldName);
1990            # Get the database handle.
1991            my $dbh = $self->{_dbh};
1992            # Query the database.
1993            my $results = $dbh->SQL("SELECT DISTINCT $realName FROM $relation");
1994            # Clean the results. They are stored as a list of lists, and we just want the one list.
1995            @retVal = sort map { $_->[0] } @{$results};
1996        }
1997        # Return the result.
1998        return @retVal;
1999    }
2000    
2001    =head3 GetEntityValues
2002    
2003    C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>
2004    
2005    Return a list of values from a specified entity instance. If the entity instance
2006    does not exist, an empty list is returned.
2007    
2008    =over 4
2009    
2010    =item entityType
2011    
2012    Entity type name.
2013    
2014    =item ID
2015    
2016    ID of the desired entity.
2017    
2018    =item fields
2019    
2020    List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.
2021    
2022    =item RETURN
2023    
2024    Returns a flattened list of the values of the specified fields for the specified entity.
2025    
2026    =back
2027    
2028    =cut
2029    
2030    sub GetEntityValues {
2031        # Get the parameters.
2032        my ($self, $entityType, $ID, $fields) = @_;
2033        # Get the specified entity.
2034        my $entity = $self->GetEntity($entityType, $ID);
2035        # Declare the return list.
2036        my @retVal = ();
2037        # If we found the entity, push the values into the return list.
2038        if ($entity) {
2039            push @retVal, $entity->Values($fields);
2040        }
2041        # Return the result.
2042        return @retVal;
2043    }
2044    
2045    =head3 GetAll
2046    
2047    C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>
2048    
2049    Return a list of values taken from the objects returned by a query. The first three
2050    parameters correspond to the parameters of the L</Get> method. The final parameter is
2051    a list of the fields desired from each record found by the query. The field name
2052    syntax is the standard syntax used for fields in the B<ERDB> system--
2053    B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity
2054    or relationship and I<fieldName> is the name of the field.
2055    
2056    The list returned will be a list of lists. Each element of the list will contain
2057    the values returned for the fields specified in the fourth parameter. If one of the
2058    fields specified returns multiple values, they are flattened in with the rest. For
2059    example, the following call will return a list of the features in a particular
2060    spreadsheet cell, and each feature will be represented by a list containing the
2061    feature ID followed by all of its aliases.
2062    
2063    C<< $query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>
2064    
2065    =over 4
2066    
2067    =item objectNames
2068    
2069    List containing the names of the entity and relationship objects to be retrieved.
2070    
2071    =item filterClause
2072    
2073    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
2074    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
2075    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
2076    parameter list as additional parameters. The fields in a filter clause can come from primary
2077    entity relations, relationship relations, or secondary entity relations; however, all of the
2078    entities and relationships involved must be included in the list of object names.
2079    
2080    =item parameterList
2081    
2082    List of the parameters to be substituted in for the parameters marks in the filter clause.
2083    
2084    =item fields
2085    
2086    List of the fields to be returned in each element of the list returned.
2087    
2088    =item count
2089    
2090    Maximum number of records to return. If omitted or 0, all available records will be returned.
2091    
2092    =item RETURN
2093    
2094    Returns a list of list references. Each element of the return list contains the values for the
2095    fields specified in the B<fields> parameter.
2096    
2097    =back
2098    
2099    =cut
2100    #: Return Type @@;
2101    sub GetAll {
2102        # Get the parameters.
2103        my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
2104        # Translate the parameters from a list reference to a list. If the parameter
2105        # list is a scalar we convert it into a singleton list.
2106        my @parmList = ();
2107        if (ref $parameterList eq "ARRAY") {
2108            Trace("GetAll parm list is an array.") if T(4);
2109            @parmList = @{$parameterList};
2110        } else {
2111            Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
2112            push @parmList, $parameterList;
2113        }
2114        # Insure the counter has a value.
2115        if (!defined $count) {
2116            $count = 0;
2117        }
2118        # Add the row limit to the filter clause.
2119        if ($count > 0) {
2120            $filterClause .= " LIMIT $count";
2121        }
2122        # Create the query.
2123        my $query = $self->Get($objectNames, $filterClause, \@parmList);
2124        # Set up a counter of the number of records read.
2125        my $fetched = 0;
2126        # Loop through the records returned, extracting the fields. Note that if the
2127        # counter is non-zero, we stop when the number of records read hits the count.
2128        my @retVal = ();
2129        while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
2130            my @rowData = $row->Values($fields);
2131            push @retVal, \@rowData;
2132            $fetched++;
2133        }
2134        Trace("$fetched rows returned in GetAll.") if T(SQL => 4);
2135        # Return the resulting list.
2136        return @retVal;
2137    }
2138    
2139    =head3 Exists
2140    
2141    C<< my $found = $sprout->Exists($entityName, $entityID); >>
2142    
2143    Return TRUE if an entity exists, else FALSE.
2144    
2145    =over 4
2146    
2147    =item entityName
2148    
2149    Name of the entity type (e.g. C<Feature>) relevant to the existence check.
2150    
2151    =item entityID
2152    
2153    ID of the entity instance whose existence is to be checked.
2154    
2155    =item RETURN
2156    
2157    Returns TRUE if the entity instance exists, else FALSE.
2158    
2159    =back
2160    
2161    =cut
2162    #: Return Type $;
2163    sub Exists {
2164        # Get the parameters.
2165        my ($self, $entityName, $entityID) = @_;
2166        # Check for the entity instance.
2167        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2168        my $testInstance = $self->GetEntity($entityName, $entityID);
2169        # Return an existence indicator.
2170        my $retVal = ($testInstance ? 1 : 0);
2171        return $retVal;
2172    }
2173    
2174    =head3 EstimateRowSize
2175    
2176    C<< my $rowSize = $erdb->EstimateRowSize($relName); >>
2177    
2178    Estimate the row size of the specified relation. The estimated row size is computed by adding
2179    up the average length for each data type.
2180    
2181    =over 4
2182    
2183    =item relName
2184    
2185    Name of the relation whose estimated row size is desired.
2186    
2187    =item RETURN
2188    
2189    Returns an estimate of the row size for the specified relation.
2190    
2191    =back
2192    
2193    =cut
2194    #: Return Type $;
2195    sub EstimateRowSize {
2196        # Get the parameters.
2197        my ($self, $relName) = @_;
2198        # Declare the return variable.
2199        my $retVal = 0;
2200        # Find the relation descriptor.
2201        my $relation = $self->_FindRelation($relName);
2202        # Get the list of fields.
2203        for my $fieldData (@{$relation->{Fields}}) {
2204            # Get the field type and add its length.
2205            my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};
2206            $retVal += $fieldLen;
2207        }
2208        # Return the result.
2209        return $retVal;
2210    }
2211    
2212    =head3 GetFieldTable
2213    
2214    C<< my $fieldHash = $self->GetFieldTable($objectnName); >>
2215    
2216    Get the field structure for a specified entity or relationship.
2217    
2218    =over 4
2219    
2220    =item objectName
2221    
2222    Name of the desired entity or relationship.
2223    
2224    =item RETURN
2225    
2226    The table containing the field descriptors for the specified object.
2227    
2228    =back
2229    
2230    =cut
2231    
2232    sub GetFieldTable {
2233        # Get the parameters.
2234        my ($self, $objectName) = @_;
2235        # Get the descriptor from the metadata.
2236        my $objectData = $self->_GetStructure($objectName);
2237        # Return the object's field table.
2238        return $objectData->{Fields};
2239    }
2240    
2241    =head2 Data Mining Methods
2242    
2243    =head3 GetUsefulCrossValues
2244    
2245    C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>
2246    
2247    Return a list of the useful attributes that would be returned by a B<Cross> call
2248    from an entity of the source entity type through the specified relationship. This
2249    means it will return the fields of the target entity type and the intersection data
2250    fields in the relationship. Only primary table fields are returned. In other words,
2251    the field names returned will be for fields where there is always one and only one
2252    value.
2253    
2254    =over 4
2255    
2256    =item sourceEntity
2257    
2258    Name of the entity from which the relationship crossing will start.
2259    
2260    =item relationship
2261    
2262    Name of the relationship being crossed.
2263    
2264    =item RETURN
2265    
2266    Returns a list of field names in Sprout field format (I<objectName>C<(>I<fieldName>C<)>.
2267    
2268    =back
2269    
2270    =cut
2271    #: Return Type @;
2272    sub GetUsefulCrossValues {
2273        # Get the parameters.
2274        my ($self, $sourceEntity, $relationship) = @_;
2275        # Declare the return variable.
2276        my @retVal = ();
2277        # Determine the target entity for the relationship. This is whichever entity is not
2278        # the source entity. So, if the source entity is the FROM, we'll get the name of
2279        # the TO, and vice versa.
2280        my $relStructure = $self->_GetStructure($relationship);
2281        my $targetEntityType = ($relStructure->{from} eq $sourceEntity ? "to" : "from");
2282        my $targetEntity = $relStructure->{$targetEntityType};
2283        # Get the field table for the entity.
2284        my $entityFields = $self->GetFieldTable($targetEntity);
2285        # The field table is a hash. The hash key is the field name. The hash value is a structure.
2286        # For the entity fields, the key aspect of the target structure is that the {relation} value
2287        # must match the entity name.
2288        my @fieldList = map { "$targetEntity($_)" } grep { $entityFields->{$_}->{relation} eq $targetEntity }
2289                            keys %{$entityFields};
2290        # Push the fields found onto the return variable.
2291        push @retVal, sort @fieldList;
2292        # Get the field table for the relationship.
2293        my $relationshipFields = $self->GetFieldTable($relationship);
2294        # Here we have a different rule. We want all the fields other than "from-link" and "to-link".
2295        # This may end up being an empty set.
2296        my @fieldList2 = map { "$relationship($_)" } grep { $_ ne "from-link" && $_ ne "to-link" }
2297                            keys %{$relationshipFields};
2298        # Push these onto the return list.
2299        push @retVal, sort @fieldList2;
2300        # Return the result.
2301        return @retVal;
2302    }
2303    
2304    =head3 FindColumn
2305    
2306    C<< my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier); >>
2307    
2308    Return the location a desired column in a data mining header line. The data
2309    mining header line is a tab-separated list of column names. The column
2310    identifier is either the numerical index of a column or the actual column
2311    name.
2312    
2313    =over 4
2314    
2315    =item headerLine
2316    
2317    The header line from a data mining command, which consists of a tab-separated
2318    list of column names.
2319    
2320    =item columnIdentifier
2321    
2322    Either the ordinal number of the desired column (1-based), or the name of the
2323    desired column.
2324    
2325    =item RETURN
2326    
2327    Returns the array index (0-based) of the desired column.
2328    
2329    =back
2330    
2331    =cut
2332    
2333    sub FindColumn {
2334        # Get the parameters.
2335        my ($headerLine, $columnIdentifier) = @_;
2336        # Declare the return variable.
2337        my $retVal;
2338        # Split the header line into column names.
2339        my @headers = ParseColumns($headerLine);
2340        # Determine whether we have a number or a name.
2341        if ($columnIdentifier =~ /^\d+$/) {
2342            # Here we have a number. Subtract 1 and validate the result.
2343            $retVal = $columnIdentifier - 1;
2344            if ($retVal < 0 || $retVal > $#headers) {
2345                Confess("Invalid column identifer \"$columnIdentifier\": value out of range.");
2346            }
2347        } else {
2348            # Here we have a name. We need to find it in the list.
2349            for (my $i = 0; $i <= $#headers && ! defined($retVal); $i++) {
2350                if ($headers[$i] eq $columnIdentifier) {
2351                    $retVal = $i;
2352                                  }                                  }
2353                          }                          }
2354            if (! defined($retVal)) {
2355                Confess("Invalid column identifier \"$columnIdentifier\": value not found.");
2356                  }                  }
2357          }          }
2358          # Return the success indicator.      # Return the result.
2359          return $retVal;          return $retVal;
2360  }  }
2361    
2362  =head3 LoadTable  =head3 ParseColumns
2363    
2364  C<< my %results = $database->LoadTable($fileName, $relationName, $truncateFlag); >>  C<< my @columns = ERDB::ParseColumns($line); >>
2365    
2366  Load data from a tab-delimited file into a specified table, optionally re-creating the table first.  Convert the specified data line to a list of columns.
2367    
2368  =over 4  =over 4
2369    
2370  =item fileName  =item line
2371    
2372  Name of the file from which the table data should be loaded.  A data mining input, consisting of a tab-separated list of columns terminated by a
2373    new-line.
2374    
2375  =item relationName  =item RETURN
2376    
2377  Name of the relation to be loaded. This is the same as the table name.  Returns a list consisting of the column values.
2378    
2379  =item truncateFlag  =back
2380    
2381  TRUE if the table should be dropped and re-created, else FALSE  =cut
2382    
2383    sub ParseColumns {
2384        # Get the parameters.
2385        my ($line) = @_;
2386        # Chop off the line-end.
2387        chomp $line;
2388        # Split it into a list.
2389        my @retVal = split(/\t/, $line);
2390        # Return the result.
2391        return @retVal;
2392    }
2393    
2394    =head2 Internal Utility Methods
2395    
2396    =head3 SetupSQL
2397    
2398    Process a list of object names and a filter clause so that they can be used to
2399    build an SQL statement. This method takes in a reference to a list of object names
2400    and a filter clause. It will return a corrected filter clause, a list of mapped
2401    names and the mapped name hash.
2402    
2403    This is an instance method.
2404    
2405    =over 4
2406    
2407    =item objectNames
2408    
2409    Reference to a list of the object names to be included in the query.
2410    
2411    =item filterClause
2412    
2413    A string containing the WHERE clause for the query (without the C<WHERE>) and also
2414    optionally the C<ORDER BY> and C<LIMIT> clauses.
2415    
2416  =item RETURN  =item RETURN
2417    
2418  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
2419    with the FROM clause. The second element is a reference to a list of the names to be
2420    used in retrieving the fields. The third element is a hash mapping the names to the
2421    objects they represent.
2422    
2423  =back  =back
2424    
2425  =cut  =cut
2426  sub LoadTable {  
2427          # Get the parameters.  sub _SetupSQL {
2428          my $self = shift @_;      my ($self, $objectNames, $filterClause) = @_;
2429          my ($fileName, $relationName, $truncateFlag) = @_;      # Adjust the list of object names to account for multiple occurrences of the
2430          # Create the statistical return object.      # same object. We start with a hash table keyed on object name that will
2431          my $retVal = _GetLoadStats();      # return the object suffix. The first time an object is encountered it will
2432          # Trace the fact of the load.      # not be found in the hash. The next time the hash will map the object name
2433          Trace("Loading table $relationName from $fileName") if T(1);      # to 2, then 3, and so forth.
2434          # Get the database handle.      my %objectHash = ();
2435          my $dbh = $self->{_dbh};      # This list will contain the object names as they are to appear in the
2436          # Get the relation data.      # FROM list.
2437          my $relation = $self->_FindRelation($relationName);      my @fromList = ();
2438          # Check the truncation flag.      # This list contains the suffixed object name for each object. It is exactly
2439          if ($truncateFlag) {      # parallel to the list in the $objectNames parameter.
2440                  Trace("Creating table $relationName") if T(1);      my @mappedNameList = ();
2441                  # Re-create the table without its index.      # Finally, this hash translates from a mapped name to its original object name.
2442                  $self->CreateTable($relationName, 0);      my %mappedNameHash = ();
2443        # Now we create the lists. Note that for every single name we push something into
2444        # @fromList and @mappedNameList. This insures that those two arrays are exactly
2445        # parallel to $objectNames.
2446        for my $objectName (@{$objectNames}) {
2447            # Get the next suffix for this object.
2448            my $suffix = $objectHash{$objectName};
2449            if (! $suffix) {
2450                # Here we are seeing the object for the first time. The object name
2451                # is used as is.
2452                push @mappedNameList, $objectName;
2453                push @fromList, $objectName;
2454                $mappedNameHash{$objectName} = $objectName;
2455                # Denote the next suffix will be 2.
2456                $objectHash{$objectName} = 2;
2457            } else {
2458                # Here we've seen the object before. We construct a new name using
2459                # the suffix from the hash and update the hash.
2460                my $mappedName = "$objectName$suffix";
2461                $objectHash{$objectName} = $suffix + 1;
2462                # The FROM list has the object name followed by the mapped name. This
2463                # tells SQL it's still the same table, but we're using a different name
2464                # for it to avoid confusion.
2465                push @fromList, "$objectName $mappedName";
2466                # The mapped-name list contains the real mapped name.
2467                push @mappedNameList, $mappedName;
2468                # Finally, enable us to get back from the mapped name to the object name.
2469                $mappedNameHash{$mappedName} = $objectName;
2470          }          }
2471          # Determine whether or not this is a primary relation. Primary relations have an extra      }
2472          # field indicating whether or not a given object is new or was loaded from the flat files.      # Begin the SELECT suffix. It starts with
2473          my $primary = $self->_IsPrimary($relationName);      #
2474          # Get the number of fields in this relation.      # FROM name1, name2, ... nameN
2475          my @fieldList = @{$relation->{Fields}};      #
2476          my $fieldCount = @fieldList;      my $suffix = "FROM " . join(', ', @fromList);
2477          # Record the number of expected fields.      # Check for a filter clause.
2478          my $expectedFields = $fieldCount + ($primary ? 1 : 0);      if ($filterClause) {
2479          # Start a database transaction.          # Here we have one, so we convert its field names and add it to the query. First,
2480          $dbh->begin_tran;          # We create a copy of the filter string we can work with.
2481          # Open the relation file. We need to create a cleaned-up copy before loading.          my $filterString = $filterClause;
2482          open TABLEIN, '<', $fileName;          # Next, we sort the object names by length. This helps protect us from finding
2483          my $tempName = "$fileName.tbl";          # object names inside other object names when we're doing our search and replace.
2484          open TABLEOUT, '>', $tempName;          my @sortedNames = sort { length($b) - length($a) } @mappedNameList;
2485          # Loop through the file.          # We will also keep a list of conditions to add to the WHERE clause in order to link
2486          while (<TABLEIN>) {          # entities and relationships as well as primary relations to secondary ones.
2487                  # Chop off the new-line character.          my @joinWhere = ();
2488                  my $record = $_;          # The final preparatory step is to create a hash table of relation names. The
2489                  chomp $record;          # table begins with the relation names already in the SELECT command. We may
2490          # Only proceed if the record is non-blank.          # need to add relations later if there is filtering on a field in a secondary
2491          if ($record) {          # relation. The secondary relations are the ones that contain multiply-
2492              # Escape all the backslashes found in the line.          # occurring or optional fields.
2493              $record =~ s/\\/\\\\/g;          my %fromNames = map { $_ => 1 } @sortedNames;
2494              # Eliminate any trailing tabs.          # We are ready to begin. We loop through the object names, replacing each
2495              chop $record while substr($record, -1) eq "\t";          # object name's field references by the corresponding SQL field reference.
2496              # If this is a primary relation, add a 0 for the new-record flag (indicating that          # Along the way, if we find a secondary relation, we will need to add it
2497              # this record is not new, but part of the original load).          # to the FROM clause.
2498              if ($primary) {          for my $mappedName (@sortedNames) {
2499                  $record .= "\t0";              # Get the length of the object name plus 2. This is the value we add to the
2500              }              # size of the field name to determine the size of the field reference as a
2501              # Write the record.              # whole.
2502              print TABLEOUT "$record\n";              my $nameLength = 2 + length $mappedName;
2503              # Count the record read.              # Get the real object name for this mapped name.
2504              my $count = $retVal->Add('records');              my $objectName = $mappedNameHash{$mappedName};
2505              my $len = length $record;              Trace("Processing $mappedName for object $objectName.") if T(4);
2506              Trace("Record $count written with $len characters.") if T(4);              # Get the object's field list.
2507          }              my $fieldList = $self->GetFieldTable($objectName);
2508          }              # Find the field references for this object.
2509          # Close the files.              while ($filterString =~ m/$mappedName\(([^)]*)\)/g) {
2510          close TABLEIN;                  # At this point, $1 contains the field name, and the current position
2511          close TABLEOUT;                  # is set immediately after the final parenthesis. We pull out the name of
2512      Trace("Temporary file $tempName created.") if T(4);                  # the field and the position and length of the field reference as a whole.
2513      # Load the table.                  my $fieldName = $1;
2514          my $rv;                  my $len = $nameLength + length $fieldName;
2515          eval {                  my $pos = pos($filterString) - $len;
2516                  $rv = $dbh->load_table(file => $tempName, tbl => $relationName);                  # Insure the field exists.
2517          };                  if (!exists $fieldList->{$fieldName}) {
2518          if (!defined $rv) {                      Confess("Field $fieldName not found for object $objectName.");
         $retVal->AddMessage($@) if ($@);  
         $retVal->AddMessage("Table load failed for $relationName using $tempName.");  
                 Trace("Table load failed for $relationName.") if T(1);  
2519          } else {          } else {
2520                  # Here we successfully loaded the table. Trace the number of records loaded.                      Trace("Processing $fieldName at position $pos.") if T(4);
2521                  Trace("$retVal->{records} records read for $relationName.") if T(1);                      # Get the field's relation.
2522                  # If we're rebuilding, we need to create the table indexes.                      my $relationName = $fieldList->{$fieldName}->{relation};
2523                  if ($truncateFlag) {                      # Now we have a secondary relation. We need to insure it matches the
2524                          eval {                      # mapped name of the primary relation. First we peel off the suffix
2525                                  $self->CreateIndex($relationName);                      # from the mapped name.
2526                          };                      my $mappingSuffix = substr $mappedName, length($objectName);
2527                          if ($@) {                      # Put the mapping suffix onto the relation name to get the
2528                                  $retVal->AddMessage($@);                      # mapped relation name.
2529                        my $mappedRelationName = "$relationName$mappingSuffix";
2530                        # Insure the relation is in the FROM clause.
2531                        if (!exists $fromNames{$mappedRelationName}) {
2532                            # Add the relation to the FROM clause.
2533                            if ($mappedRelationName eq $relationName) {
2534                                # The name is un-mapped, so we add it without
2535                                # any frills.
2536                                $suffix .= ", $relationName";
2537                                push @joinWhere, "$objectName.id = $relationName.id";
2538                            } else {
2539                                # Here we have a mapping situation.
2540                                $suffix .= ", $relationName $mappedRelationName";
2541                                push @joinWhere, "$mappedRelationName.id = $mappedName.id";
2542                          }                          }
2543                            # Denote we have this relation available for future fields.
2544                            $fromNames{$mappedRelationName} = 1;
2545                        }
2546                        # Form an SQL field reference from the relation name and the field name.
2547                        my $sqlReference = "$mappedRelationName." . _FixName($fieldName);
2548                        # Put it into the filter string in place of the old value.
2549                        substr($filterString, $pos, $len) = $sqlReference;
2550                        # Reposition the search.
2551                        pos $filterString = $pos + length $sqlReference;
2552                  }                  }
2553          }          }
2554          # Commit the database changes.          }
2555          $dbh->commit_tran;          # The next step is to join the objects together. We only need to do this if there
2556          # Delete the temporary file.          # is more than one object in the object list. We start with the first object and
2557          unlink $tempName;          # run through the objects after it. Note also that we make a safety copy of the
2558          # Return the statistics.          # list before running through it.
2559          return $retVal;          my @mappedObjectList = @mappedNameList;
2560            my $lastMappedObject = shift @mappedObjectList;
2561            # Get the join table.
2562            my $joinTable = $self->{_metaData}->{Joins};
2563            # Loop through the object list.
2564            for my $thisMappedObject (@mappedObjectList) {
2565                # Look for a join using the real object names.
2566                my $lastObject = $mappedNameHash{$lastMappedObject};
2567                my $thisObject = $mappedNameHash{$thisMappedObject};
2568                my $joinKey = "$lastObject/$thisObject";
2569                if (!exists $joinTable->{$joinKey}) {
2570                    # Here there's no join, so we throw an error.
2571                    Confess("No join exists to connect from $lastMappedObject to $thisMappedObject.");
2572                } else {
2573                    # Get the join clause.
2574                    my $unMappedJoin = $joinTable->{$joinKey};
2575                    # Fix the names.
2576                    $unMappedJoin =~ s/$lastObject/$lastMappedObject/;
2577                    $unMappedJoin =~ s/$thisObject/$thisMappedObject/;
2578                    push @joinWhere, $unMappedJoin;
2579                    # Save this object as the last object for the next iteration.
2580                    $lastMappedObject = $thisMappedObject;
2581                }
2582            }
2583            # Now we need to handle the whole ORDER BY / LIMIT thing. The important part
2584            # here is we want the filter clause to be empty if there's no WHERE filter.
2585            # We'll put the ORDER BY / LIMIT clauses in the following variable.
2586            my $orderClause = "";
2587            # Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy
2588            # operator so that we find the first occurrence of either verb.
2589            if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {
2590                # Here we have an ORDER BY or LIMIT verb. Split it off of the filter string.
2591                my $pos = pos $filterString;
2592                $orderClause = $2 . substr($filterString, $pos);
2593                $filterString = $1;
2594            }
2595            # Add the filter and the join clauses (if any) to the SELECT command.
2596            if ($filterString) {
2597                Trace("Filter string is \"$filterString\".") if T(4);
2598                push @joinWhere, "($filterString)";
2599            }
2600            if (@joinWhere) {
2601                $suffix .= " WHERE " . join(' AND ', @joinWhere);
2602            }
2603            # Add the sort or limit clause (if any) to the SELECT command.
2604            if ($orderClause) {
2605                $suffix .= " $orderClause";
2606            }
2607        }
2608        # Return the suffix, the mapped name list, and the mapped name hash.
2609        return ($suffix, \@mappedNameList, \%mappedNameHash);
2610  }  }
2611    
2612  =head3 GenerateEntity  =head3 GetStatementHandle
   
 C<< my $fieldHash = $database->GenerateEntity($id, $type, \%values); >>  
2613    
2614  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.
2615  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
2616  of the fields are generated using information in the database schema.  the benefit of tracing.
2617    
2618  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.  
2619    
2620  =over 4  =over 4
2621    
2622  =item id  =item command
2623    
2624  ID to assign to the new entity.  Command to prepare and execute.
2625    
2626  =item type  =item params
2627    
2628  Type name for the new entity.  Reference to a list of the values to be substituted in for the parameter marks.
2629    
2630  =item values  =item RETURN
2631    
2632  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
2633    results.
2634    
2635  =back  =back
2636    
2637  =cut  =cut
2638    
2639  sub GenerateEntity {  sub _GetStatementHandle {
2640          # Get the parameters.          # Get the parameters.
2641          my $self = shift @_;      my ($self, $command, $params) = @_;
2642          my ($id, $type, $values) = @_;      # Trace the query.
2643          # Create the return hash.      Trace("SQL query: $command") if T(SQL => 3);
2644          my $this = { id => $id };      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
2645          # Get the metadata structure.      # Get the database handle.
2646          my $metadata = $self->{_metaData};      my $dbh = $self->{_dbh};
2647          # Get this entity's list of fields.      # Prepare the command.
2648          if (!exists $metadata->{Entities}->{$type}) {      my $sth = $dbh->prepare_command($command);
2649                  Confess("Unrecognized entity type $type in GenerateEntity.");      # Execute it with the parameters bound in.
2650          } else {      $sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr());
2651                  my $entity = $metadata->{Entities}->{$type};      # Return the statement handle.
2652                  my $fields = $entity->{Fields};      return $sth;
                 # Generate data from the fields.  
                 _GenerateFields($this, $fields, $type, $values);  
         }  
         # Return the hash created.  
         return $this;  
2653  }  }
2654    
   
 =head2 Internal Utility Methods  
   
2655  =head3 GetLoadStats  =head3 GetLoadStats
2656    
2657  Return a blank statistics object for use by the load methods.  Return a blank statistics object for use by the load methods.
# Line 1140  Line 2661 
2661  =cut  =cut
2662    
2663  sub _GetLoadStats {  sub _GetLoadStats {
2664          return Stats->new('records');      return Stats->new();
2665  }  }
2666    
2667  =head3 GenerateFields  =head3 GenerateFields
# Line 1243  Line 2764 
2764    
2765  sub _DumpRelation {  sub _DumpRelation {
2766          # Get the parameters.          # Get the parameters.
2767          my $self = shift @_;      my ($self, $outputDirectory, $relationName, $relation) = @_;
         my ($outputDirectory, $relationName, $relation) = @_;  
2768          # Open the output file.          # Open the output file.
2769          my $fileName = "$outputDirectory/$relationName.dtx";          my $fileName = "$outputDirectory/$relationName.dtx";
2770          open(DTXOUT, ">$fileName") || Confess("Could not open dump file $fileName: $!");          open(DTXOUT, ">$fileName") || Confess("Could not open dump file $fileName: $!");
# Line 1290  Line 2810 
2810    
2811  sub _GetStructure {  sub _GetStructure {
2812          # Get the parameters.          # Get the parameters.
2813          my $self = shift @_;      my ($self, $objectName) = @_;
         my ($objectName) = @_;  
2814          # Get the metadata structure.          # Get the metadata structure.
2815          my $metadata = $self->{_metaData};          my $metadata = $self->{_metaData};
2816          # Declare the variable to receive the descriptor.          # Declare the variable to receive the descriptor.
# Line 1330  Line 2849 
2849    
2850  sub _GetRelationTable {  sub _GetRelationTable {
2851          # Get the parameters.          # Get the parameters.
2852          my $self = shift @_;      my ($self, $objectName) = @_;
         my ($objectName) = @_;  
2853          # Get the descriptor from the metadata.          # Get the descriptor from the metadata.
2854          my $objectData = $self->_GetStructure($objectName);          my $objectData = $self->_GetStructure($objectName);
2855          # Return the object's relation list.          # Return the object's relation list.
2856          return $objectData->{Relations};          return $objectData->{Relations};
2857  }  }
2858    
 =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};  
 }  
   
2859  =head3 ValidateFieldNames  =head3 ValidateFieldNames
2860    
2861  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 1458  Line 2946 
2946    
2947  sub _LoadRelation {  sub _LoadRelation {
2948          # Get the parameters.          # Get the parameters.
2949          my $self = shift @_;      my ($self, $directoryName, $relationName, $rebuild) = @_;
         my ($directoryName, $relationName, $rebuild) = @_;  
2950          # Create the file name.          # Create the file name.
2951          my $fileName = "$directoryName/$relationName";          my $fileName = "$directoryName/$relationName";
2952          # If the file doesn't exist, try adding the .dtx suffix.          # If the file doesn't exist, try adding the .dtx suffix.
# Line 1509  Line 2996 
2996  sub _LoadMetaData {  sub _LoadMetaData {
2997          # Get the parameters.          # Get the parameters.
2998          my ($filename) = @_;          my ($filename) = @_;
2999        Trace("Reading Sprout DBD from $filename.") if T(2);
3000          # 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
3001          # get the exact structure we want.          # get the exact structure we want.
3002          my $metadata = XML::Simple::XMLin($filename,          my $metadata = XML::Simple::XMLin($filename,
# Line 1533  Line 3021 
3021          my %masterRelationTable = ();          my %masterRelationTable = ();
3022          # Loop through the entities.          # Loop through the entities.
3023          my $entityList = $metadata->{Entities};          my $entityList = $metadata->{Entities};
3024          while (my ($entityName, $entityStructure) = each %{$entityList}) {      for my $entityName (keys %{$entityList}) {
3025            my $entityStructure = $entityList->{$entityName};
3026                  #                  #
3027                  # 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,
3028                  # 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,
3029                  # 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>
3030                  # 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 1581  Line 3070 
3070                  # to a list of fields. First, we need the ID field itself.                  # to a list of fields. First, we need the ID field itself.
3071                  my $idField = $fieldList->{id};                  my $idField = $fieldList->{id};
3072                  # Loop through the relations.                  # Loop through the relations.
3073                  while (my ($relationName, $relation) = each %{$relationTable}) {          for my $relationName (keys %{$relationTable}) {
3074                my $relation = $relationTable->{$relationName};
3075                          # Get the relation's field list.                          # Get the relation's field list.
3076                          my $relationFieldList = $relation->{Fields};                          my $relationFieldList = $relation->{Fields};
3077                          # 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 1631  Line 3121 
3121                  # 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.
3122                  # 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
3123                  # the relations.                  # the relations.
3124                  while (my ($relationName, $relation) = each %{$relationTable}) {          for my $relationName (keys %{$relationTable}) {
3125                my $relation = $relationTable->{$relationName};
3126                          # Get the relation's index list.                          # Get the relation's index list.
3127                          my $indexList = $relation->{Indexes};                          my $indexList = $relation->{Indexes};
3128                          # Insure this relation has an ID index.                          # Insure this relation has an ID index.
# Line 1662  Line 3153 
3153          # 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.
3154          # For one thing, there is only a single constituent relation.          # For one thing, there is only a single constituent relation.
3155          my $relationshipList = $metadata->{Relationships};          my $relationshipList = $metadata->{Relationships};
3156          while (my ($relationshipName, $relationshipStructure) = each %{$relationshipList}) {      for my $relationshipName (keys %{$relationshipList}) {
3157            my $relationshipStructure = $relationshipList->{$relationshipName};
3158                  # Fix up this relationship.                  # Fix up this relationship.
3159                  _FixupFields($relationshipStructure, $relationshipName, 2, 3);                  _FixupFields($relationshipStructure, $relationshipName, 2, 3);
3160                  # Format a description for the FROM field.                  # Format a description for the FROM field.
# Line 1711  Line 3203 
3203                  my @fromList = ();                  my @fromList = ();
3204                  my @toList = ();                  my @toList = ();
3205                  my @bothList = ();                  my @bothList = ();
3206                  while (my ($relationshipName, $relationship) = each %{$relationshipList}) {          Trace("Join table build for $entityName.") if T(metadata => 4);
3207            for my $relationshipName (keys %{$relationshipList}) {
3208                my $relationship = $relationshipList->{$relationshipName};
3209                          # 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.
3210                          if ($relationship->{from} eq $entityName) {              my $fromEntity = $relationship->{from};
3211                                  if ($relationship->{to} eq $entityName) {              my $toEntity = $relationship->{to};
3212                Trace("Join check for relationship $relationshipName from $fromEntity to $toEntity.") if T(Joins => 4);
3213                if ($fromEntity eq $entityName) {
3214                    if ($toEntity eq $entityName) {
3215                                          # Here the relationship is recursive.                                          # Here the relationship is recursive.
3216                                          push @bothList, $relationshipName;                                          push @bothList, $relationshipName;
3217                        Trace("Relationship $relationshipName put in both-list.") if T(metadata => 4);
3218                                  } else {                                  } else {
3219                                          # Here the relationship comes from the entity.                                          # Here the relationship comes from the entity.
3220                                          push @fromList, $relationshipName;                                          push @fromList, $relationshipName;
3221                        Trace("Relationship $relationshipName put in from-list.") if T(metadata => 4);
3222                                  }                                  }
3223                          } elsif ($relationship->{to} eq $entityName) {              } elsif ($toEntity eq $entityName) {
3224                                  # Here the relationship goes to the entity.                                  # Here the relationship goes to the entity.
3225                                  push @toList, $relationshipName;                                  push @toList, $relationshipName;
3226                    Trace("Relationship $relationshipName put in to-list.") if T(metadata => 4);
3227                          }                          }
3228                  }                  }
3229                  # 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 1732  Line 3232 
3232                  # hash table at the same time.                  # hash table at the same time.
3233                  my %directRelationships = ( from => \@fromList, to => \@toList );                  my %directRelationships = ( from => \@fromList, to => \@toList );
3234                  my %otherRelationships = ( from => \@fromList, to => \@toList );                  my %otherRelationships = ( from => \@fromList, to => \@toList );
3235                  while (my ($linkType, $relationships) = each %directRelationships) {          for my $linkType (keys %directRelationships) {
3236                my $relationships = $directRelationships{$linkType};
3237                          # Loop through all the relationships.                          # Loop through all the relationships.
3238                          for my $relationshipName (@{$relationships}) {                          for my $relationshipName (@{$relationships}) {
3239                                  # Create joins between the entity and this relationship.                                  # Create joins between the entity and this relationship.
3240                                  my $linkField = "$relationshipName.${linkType}_link";                                  my $linkField = "$relationshipName.${linkType}_link";
3241                                  my $joinClause = "$entityName.id = $linkField";                                  my $joinClause = "$entityName.id = $linkField";
3242                    Trace("Entity join clause is $joinClause for $entityName and $relationshipName.") if T(metadata => 4);
3243                                  $joinTable{"$entityName/$relationshipName"} = $joinClause;                                  $joinTable{"$entityName/$relationshipName"} = $joinClause;
3244                                  $joinTable{"$relationshipName/$entityName"} = $joinClause;                                  $joinTable{"$relationshipName/$entityName"} = $joinClause;
3245                                  # Create joins between this relationship and the other relationships.                                  # Create joins between this relationship and the other relationships.
3246                                  while (my ($otherType, $otherships) = each %otherRelationships) {                  for my $otherType (keys %otherRelationships) {
3247                        my $otherships = $otherRelationships{$otherType};
3248                                          for my $otherName (@{$otherships}) {                                          for my $otherName (@{$otherships}) {
3249                                                  # Get the key for this join.                                                  # Get the key for this join.
3250                                                  my $joinKey = "$otherName/$relationshipName";                                                  my $joinKey = "$otherName/$relationshipName";
# Line 1751  Line 3254 
3254                                                          # path is ambiguous. We delete the join from the join                                                          # path is ambiguous. We delete the join from the join
3255                                                          # table to prevent it from being used.                                                          # table to prevent it from being used.
3256                                                          delete $joinTable{$joinKey};                                                          delete $joinTable{$joinKey};
3257                                Trace("Deleting ambiguous join $joinKey.") if T(4);
3258                                                  } elsif ($otherName ne $relationshipName) {                                                  } elsif ($otherName ne $relationshipName) {
3259                                                          # Here we have a valid join. Note that joins between a                                                          # Here we have a valid join. Note that joins between a
3260                                                          # relationship and itself are prohibited.                                                          # relationship and itself are prohibited.
3261                                                          $joinTable{$joinKey} = "$otherName.${otherType}_link = $linkField";                              my $relJoinClause = "$otherName.${otherType}_link = $linkField";
3262                                $joinTable{$joinKey} = $relJoinClause;
3263                                Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(metadata => 4);
3264                                                  }                                                  }
3265                                          }                                          }
3266                                  }                                  }
# Line 1763  Line 3269 
3269                                  # relationship can only be ambiguous with another recursive relationship,                                  # relationship can only be ambiguous with another recursive relationship,
3270                                  # and the incoming relationship from the outer loop is never recursive.                                  # and the incoming relationship from the outer loop is never recursive.
3271                                  for my $otherName (@bothList) {                                  for my $otherName (@bothList) {
3272                        Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(metadata => 4);
3273                                          # Join from the left.                                          # Join from the left.
3274                                          $joinTable{"$relationshipName/$otherName"} =                                          $joinTable{"$relationshipName/$otherName"} =
3275                                                  "$linkField = $otherName.from_link";                                                  "$linkField = $otherName.from_link";
# Line 1777  Line 3284 
3284                  # 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
3285                  # possible to get the same effect using multiple queries.                  # possible to get the same effect using multiple queries.
3286                  for my $relationshipName (@bothList) {                  for my $relationshipName (@bothList) {
3287                Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(metadata => 4);
3288                          # Join to the entity from each direction.                          # Join to the entity from each direction.
3289                          $joinTable{"$entityName/$relationshipName"} =                          $joinTable{"$entityName/$relationshipName"} =
3290                                  "$entityName.id = $relationshipName.from_link";                                  "$entityName.id = $relationshipName.from_link";
# Line 1790  Line 3298 
3298          return $metadata;          return $metadata;
3299  }  }
3300    
3301    =head3 SortNeeded
3302    
3303    C<< my $parms = $erdb->SortNeeded($relationName); >>
3304    
3305    Return the pipe command for the sort that should be applied to the specified
3306    relation when creating the load file.
3307    
3308    For example, if the load file should be sorted ascending by the first
3309    field, this method would return
3310    
3311        sort -k1 -t"\t"
3312    
3313    If the first field is numeric, the method would return
3314    
3315        sort -k1n -t"\t"
3316    
3317    Unfortunately, due to a bug in the C<sort> command, we cannot eliminate duplicate
3318    keys using a sort.
3319    
3320    =over 4
3321    
3322    =item relationName
3323    
3324    Name of the relation to be examined.
3325    
3326    =item
3327    
3328    Returns the sort command to use for sorting the relation, suitable for piping.
3329    
3330    =back
3331    
3332    =cut
3333    #: Return Type $;
3334    sub SortNeeded {
3335        # Get the parameters.
3336        my ($self, $relationName) = @_;
3337        # Declare a descriptor to hold the names of the key fields.
3338        my @keyNames = ();
3339        # Get the relation structure.
3340        my $relationData = $self->_FindRelation($relationName);
3341        # Find out if the relation is a primary entity relation,
3342        # a relationship relation, or a secondary entity relation.
3343        my $entityTable = $self->{_metaData}->{Entities};
3344        my $relationshipTable = $self->{_metaData}->{Relationships};
3345        if (exists $entityTable->{$relationName}) {
3346            # Here we have a primary entity relation.
3347            push @keyNames, "id";
3348        } elsif (exists $relationshipTable->{$relationName}) {
3349            # Here we have a relationship. We sort using the FROM index.
3350            my $relationshipData = $relationshipTable->{$relationName};
3351            my $index = $relationData->{Indexes}->{"idx${relationName}From"};
3352            push @keyNames, @{$index->{IndexFields}};
3353        } else {
3354            # Here we have a secondary entity relation, so we have a sort on the ID field.
3355            push @keyNames, "id";
3356        }
3357        # Now we parse the key names into sort parameters. First, we prime the return
3358        # string.
3359        my $retVal = "sort -t\"\t\" ";
3360        # Get the relation's field list.
3361        my @fields = @{$relationData->{Fields}};
3362        # Loop through the keys.
3363        for my $keyData (@keyNames) {
3364            # Get the key and the ordering.
3365            my ($keyName, $ordering);
3366            if ($keyData =~ /^([^ ]+) DESC/) {
3367                ($keyName, $ordering) = ($1, "descending");
3368            } else {
3369                ($keyName, $ordering) = ($keyData, "ascending");
3370            }
3371            # Find the key's position and type.
3372            my $fieldSpec;
3373            for (my $i = 0; $i <= $#fields && ! $fieldSpec; $i++) {
3374                my $thisField = $fields[$i];
3375                if ($thisField->{name} eq $keyName) {
3376                    # Get the sort modifier for this field type. The modifier
3377                    # decides whether we're using a character, numeric, or
3378                    # floating-point sort.
3379                    my $modifier = $TypeTable{$thisField->{type}}->{sort};
3380                    # If the index is descending for this field, denote we want
3381                    # to reverse the sort order on this field.
3382                    if ($ordering eq 'descending') {
3383                        $modifier .= "r";
3384                    }
3385                    # Store the position and modifier into the field spec, which
3386                    # will stop the inner loop. Note that the field number is
3387                    # 1-based in the sort command, so we have to increment the
3388                    # index.
3389                    $fieldSpec = ($i + 1) . $modifier;
3390                }
3391            }
3392            # Add this field to the sort command.
3393            $retVal .= " -k$fieldSpec";
3394        }
3395        # Return the result.
3396        return $retVal;
3397    }
3398    
3399  =head3 CreateRelationshipIndex  =head3 CreateRelationshipIndex
3400    
3401  Create an index for a relationship's relation.  Create an index for a relationship's relation.
# Line 1827  Line 3433 
3433          # 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
3434          # the field to it.          # the field to it.
3435          unshift @{$newIndex->{IndexFields}}, $firstField;          unshift @{$newIndex->{IndexFields}}, $firstField;
3436        # If this is a one-to-many relationship, the "To" index is unique.
3437        if ($relationshipStructure->{arity} eq "1M" && $indexKey eq "To") {
3438            $newIndex->{Unique} = 'true';
3439        }
3440          # Add the index to the relation.          # Add the index to the relation.
3441          _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);          _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);
3442  }  }
# Line 1916  Line 3526 
3526                  $structure->{Fields} = { };                  $structure->{Fields} = { };
3527          } else {          } else {
3528                  # Here we have a field list. Loop through its fields.                  # Here we have a field list. Loop through its fields.
3529                  while (my ($fieldName, $fieldData) = each %{$structure->{Fields}}) {          my $fieldStructures = $structure->{Fields};
3530            for my $fieldName (keys %{$fieldStructures}) {
3531                Trace("Processing field $fieldName of $defaultRelationName.") if T(4);
3532                my $fieldData = $fieldStructures->{$fieldName};
3533                          # Get the field type.                          # Get the field type.
3534                          my $type = $fieldData->{type};                          my $type = $fieldData->{type};
3535                          # Plug in a relation name if it is needed.                          # Plug in a relation name if it is needed.
# Line 2113  Line 3726 
3726    
3727  sub _IsPrimary {  sub _IsPrimary {
3728          # Get the parameters.          # Get the parameters.
3729          my $self = shift @_;      my ($self, $relationName) = @_;
         my ($relationName) = @_;  
3730          # Check for the relation in the entity table.          # Check for the relation in the entity table.
3731          my $entityTable = $self->{_metaData}->{Entities};          my $entityTable = $self->{_metaData}->{Entities};
3732          my $retVal = exists $entityTable->{$relationName};          my $retVal = exists $entityTable->{$relationName};
# Line 2148  Line 3760 
3760  =cut  =cut
3761  sub _FindRelation {  sub _FindRelation {
3762          # Get the parameters.          # Get the parameters.
3763          my $self = shift @_;      my ($self, $relationName) = @_;
         my ($relationName) = @_;  
3764          # 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.
3765          my $metaData = $self->{_metaData};          my $metaData = $self->{_metaData};
3766          my $retVal = $metaData->{RelationTable}->{$relationName};          my $retVal = $metaData->{RelationTable}->{$relationName};
# Line 2277  Line 3888 
3888                  my $indexData = $indexTable->{$indexName};                  my $indexData = $indexTable->{$indexName};
3889                  # Determine whether or not the index is unique.                  # Determine whether or not the index is unique.
3890                  my $fullName = $indexName;                  my $fullName = $indexName;
3891                  if ($indexData->{Unique} eq "true") {          if (exists $indexData->{Unique} && $indexData->{Unique} eq "true") {
3892                          $fullName .= " (unique)";                          $fullName .= " (unique)";
3893                  }                  }
3894                  # Start an HTML list item for this index.                  # Start an HTML list item for this index.

Legend:
Removed from v.1.3  
changed lines
  Added in v.1.69

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3