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

Diff of /Sprout/ERDB.pm

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

revision 1.1, Sun Jan 23 16:12:29 2005 UTC revision 1.11, Thu Jun 23 21:24:49 2005 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 DBKernel;
6          use Data::Dumper;          use Data::Dumper;
# Line 33  Line 32 
32  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>).
33  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
34  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
35  (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
36  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
37  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
38    C<FeatureVirulence>.
39    
40  Entities are connected by binary relationships implemented using single relations possessing the  Entities are connected by binary relationships implemented using single relations possessing the
41  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 67 
67  was inserted by the L</InsertObject> method.  was inserted by the L</InsertObject> method.
68    
69  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
70  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
71    fully implemented.
72    
73    =head2 XML Database Description
74    
75    =head3 Data Types
76    
77    The ERDB system supports the following data types. Note that there are numerous string
78    types depending on the maximum length. Some database packages limit the total number of
79    characters you have in an index key; to insure the database works in all environments,
80    the type of string should be the shortest one possible that supports all the known values.
81    
82    =over 4
83    
84    =item char
85    
86    single ASCII character
87    
88    =item int
89    
90    32-bit signed integer
91    
92    =item date
93    
94    64-bit unsigned integer, representing a PERL date/time value
95    
96    =item text
97    
98    long string; Text fields cannot be used in indexes or sorting and do not support the
99    normal syntax of filter clauses, but can be up to a billion character in length
100    
101    =item float
102    
103    double-precision floating-point number
104    
105    =item boolean
106    
107    single-bit numeric value; The value is stored as a 16-bit signed integer (for
108    compatability with certain database packages), but the only values supported are
109    0 and 1.
110    
111    =item key-string
112    
113    variable-length string, maximum 40 characters
114    
115    =item name-string
116    
117    variable-length string, maximum 80 characters
118    
119    =item medium-string
120    
121    variable-length string, maximum 160 characters
122    
123    =item string
124    
125    variable-length string, maximum 255 characters
126    
127    =back
128    
129    =head3 Global Tags
130    
131    The entire database definition must be inside a B<Database> tag. The display name of
132    the database is given by the text associated with the B<Title> tag. The display name
133    is only used in the automated documentation. It has no other effect. The entities and
134    relationships are listed inside the B<Entities> and B<Relationships> tags,
135    respectively. None of these tags have attributes.
136    
137        <Database>
138            <Title>... display title here...</Title>
139            <Entities>
140                ... entity definitions here ...
141            </Entities>
142            <Relationships>
143                ... relationship definitions here...
144            </Relationships>
145        </Database>
146    
147    Entities, relationships, indexes, and fields all allow a text tag called B<Notes>.
148    The text inside the B<Notes> tag contains comments that will appear when the database
149    documentation is generated. Within a B<Notes> tag, you may use C<[i]> and C<[/i]> for
150    italics, C<[b]> and C<[/b]> for bold, and C<[p]> for a new paragraph.
151    
152    =head3 Fields
153    
154    Both entities and relationships have fields described by B<Field> tags. A B<Field>
155    tag can have B<Notes> associated with it. The complete set of B<Field> tags for an
156    object mus be inside B<Fields> tags.
157    
158        <Entity ... >
159            <Fields>
160                ... Field tags ...
161            </Fields>
162        </Entity>
163    
164    The attributes for the B<Field> tag are as follows.
165    
166    =over 4
167    
168    =item name
169    
170    Name of the field. The field name should contain only letters, digits, and hyphens (C<->),
171    and the first character should be a letter. Most underlying databases are case-insensitive
172    with the respect to field names, so a best practice is to use lower-case letters only.
173    
174    =item type
175    
176    Data type of the field. The legal data types are given above.
177    
178    =item relation
179    
180    Name of the relation containing the field. This should only be specified for entity
181    fields. The ERDB system does not support optional fields or multi-occurring fields
182    in the primary relation of an entity. Instead, they are put into secondary relations.
183    So, for example, in the C<Genome> entity, the C<group-name> field indicates a special
184    grouping used to select a subset of the genomes. A given genome may not be in any
185    groups or may be in multiple groups. Therefore, C<group-name> specifies a relation
186    value. The relation name specified must be a valid table name. By convention, it is
187    usually the entity name followed by a qualifying word (e.g. C<GenomeGroup>). In an
188    entity, the fields without a relation attribute are said to belong to the
189    I<primary relation>. This relation has the same name as the entity itself.
190    
191    =back
192    
193    =head3 Indexes
194    
195    An entity can have multiple alternate indexes associated with it. The fields must
196    be from the primary relation. The alternate indexes assist in ordering results
197    from a query. A relationship can have up to two indexes-- a I<to-index> and a
198    I<from-index>. These order the results when crossing the relationship. For
199    example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the
200    from-index would order the contigs of a ganome, and the to-index would order
201    the genomes of a contig. A relationship's index must specify only fields in
202    the relationship.
203    
204    The indexes for an entity must be listed inside the B<Indexes> tag. The from-index
205    of a relationship is specified using the B<FromIndex> tag; the to-index is specified
206    using the B<ToIndex> tag.
207    
208    Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields>
209    tag containing the B<IndexField> tags. These specify, in order, the fields used in
210    the index. The attributes of an B<IndexField> tag are as follows.
211    
212    =over 4
213    
214    =item name
215    
216    Name of the field.
217    
218    =item order
219    
220    Sort order of the field-- C<ascending> or C<descending>.
221    
222    =back
223    
224    The B<Index>, B<FromIndex>, and B<ToIndex> tags themselves have no attributes.
225    
226    =head3 Object and Field Names
227    
228    By convention entity and relationship names use capital casing (e.g. C<Genome> or
229    C<HasRegionsIn>. Most underlying databases, however, are aggressively case-insensitive
230    with respect to relation names, converting them internally to all-upper case or
231    all-lower case.
232    
233    If syntax or parsing errors occur when you try to load or use an ERDB database, the
234    most likely reason is that one of your objects has an SQL reserved word as its name.
235    The list of SQL reserved words keeps increasing; however, most are unlikely to show
236    up as a noun or declarative verb phrase. The exceptions are C<Group>, C<User>,
237    C<Table>, C<Index>, C<Object>, C<Date>, C<Number>, C<Update>, C<Time>, C<Percent>,
238    C<Memo>, C<Order>, and C<Sum>. This problem can crop up in field names as well.
239    
240    Every entity has a field called C<id> that acts as its primary key. Every relationship
241    has fields called C<from-link> and C<to-link> that contain copies of the relevant
242    entity IDs. These are essentially ERDB's reserved words, and should not be used
243    for user-defined field names.
244    
245    =head3 Entities
246    
247    An entity is described by the B<Entity> tag. The entity can contain B<Notes>, an
248    B<Indexes> tag containing one or more secondary indexes, and a B<Fields> tag
249    containing one or more fields. The attributes of the B<Entity> tag are as follows.
250    
251    =over 4
252    
253    =item name
254    
255    Name of the entity. The entity name, by convention, uses capital casing (e.g. C<Genome>
256    or C<GroupBlock>) and should be a noun or noun phrase.
257    
258    =item keyType
259    
260    Data type of the primary key. The primary key is always named C<id>.
261    
262    =back
263    
264    =head3 Relationships
265    
266    A relationship is described by the C<Relationship> tag. Within a relationship,
267    there can be a C<Notes> tag, a C<Fields> tag containing the intersection data
268    fields, a C<FromIndex> tag containing the from-index, and a C<ToIndex> tag containing
269    the to-index.
270    
271    The C<Relationship> tag has the following attributes.
272    
273    =over 4
274    
275    =item name
276    
277    Name of the relationship. The relationship name, by convention, uses capital casing
278    (e.g. C<ContainsRegionIn> or C<HasContig>), and should be a declarative verb
279    phrase, designed to fit between the from-entity and the to-entity (e.g.
280    Block C<ContainsRegionIn> Genome).
281    
282    =item from
283    
284    Name of the entity from which the relationship starts.
285    
286    =item to
287    
288    Name of the entity to which the relationship proceeds.
289    
290    =item arity
291    
292    Relationship type: C<1M> for one-to-many and C<MM> for many-to-many.
293    
294    =back
295    
296  =cut  =cut
297    
# Line 111  Line 335 
335    
336  =head3 new  =head3 new
337    
338  C<< my $database = ERDB::new($dbh, $metaFileName); >>  C<< my $database = ERDB->new($dbh, $metaFileName); >>
339    
340  Create a new ERDB object.  Create a new ERDB object.
341    
# Line 136  Line 360 
360          my $metaData = _LoadMetaData($metaFileName);          my $metaData = _LoadMetaData($metaFileName);
361          # Create the object.          # Create the object.
362          my $self = { _dbh => $dbh,          my $self = { _dbh => $dbh,
363                                   _metaData => $metaData,                   _metaData => $metaData
                                  _options => $options,  
364                             };                             };
365          # Bless and return it.          # Bless and return it.
366          bless $self;      bless $self, $class;
367          return $self;          return $self;
368  }  }
369    
# Line 163  Line 386 
386    
387  sub ShowMetaData {  sub ShowMetaData {
388          # Get the parameters.          # Get the parameters.
389          my $self = shift @_;      my ($self, $filename) = @_;
         my ($filename) = @_;  
390          # Get the metadata and the title string.          # Get the metadata and the title string.
391          my $metadata = $self->{_metaData};          my $metadata = $self->{_metaData};
392          # Get the title string.          # Get the title string.
# Line 174  Line 396 
396          my $relationshipList = $metadata->{Relationships};          my $relationshipList = $metadata->{Relationships};
397          # Open the output file.          # Open the output file.
398          open(HTMLOUT, ">$filename") || Confess("Could not open MetaData display file $filename: $!");          open(HTMLOUT, ">$filename") || Confess("Could not open MetaData display file $filename: $!");
399        Trace("Building MetaData table of contents.") if T(4);
400          # Write the HTML heading stuff.          # Write the HTML heading stuff.
401          print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";          print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";
402          print HTMLOUT "</head>\n<body>\n";          print HTMLOUT "</head>\n<body>\n";
# Line 201  Line 424 
424          print HTMLOUT "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";          print HTMLOUT "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";
425          # Loop through the entities.          # Loop through the entities.
426          for my $key (sort keys %{$entityList}) {          for my $key (sort keys %{$entityList}) {
427            Trace("Building MetaData entry for $key entity.") if T(4);
428                  # Create the entity header. It contains a bookmark and the entity name.                  # Create the entity header. It contains a bookmark and the entity name.
429                  print HTMLOUT "<a name=\"$key\"></a><h3>$key</h3>\n";                  print HTMLOUT "<a name=\"$key\"></a><h3>$key</h3>\n";
430                  # Get the entity data.                  # Get the entity data.
# Line 239  Line 463 
463          print HTMLOUT "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";          print HTMLOUT "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";
464          # Loop through the relationships.          # Loop through the relationships.
465          for my $key (sort keys %{$relationshipList}) {          for my $key (sort keys %{$relationshipList}) {
466            Trace("Building MetaData entry for $key relationship.") if T(4);
467                  # Get the relationship's structure.                  # Get the relationship's structure.
468                  my $relationshipStructure = $relationshipList->{$key};                  my $relationshipStructure = $relationshipList->{$key};
469                  # Create the relationship header.                  # Create the relationship header.
# Line 269  Line 494 
494                  my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});                  my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});
495                  print HTMLOUT $htmlString;                  print HTMLOUT $htmlString;
496          }          }
497        Trace("Building MetaData join table.") if T(4);
498          # Denote we're starting the join table.          # Denote we're starting the join table.
499          print HTMLOUT "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";          print HTMLOUT "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";
500          # Create a table header.          # Create a table header.
501          print HTMLOUT _OpenTable("Join Table", "Source", "Target", "Join Condition");          print HTMLOUT _OpenTable("Join Table", "Source", "Target", "Join Condition");
502          # Loop through the joins.          # Loop through the joins.
503          my $joinTable = $metadata->{Joins};          my $joinTable = $metadata->{Joins};
504          for my $joinKey (sort keys %{$joinTable}) {      my @joinKeys = keys %{$joinTable};
505        for my $joinKey (sort @joinKeys) {
506                  # Separate out the source, the target, and the join clause.                  # Separate out the source, the target, and the join clause.
507                  $joinKey =~ m!([^/]*)/(.*)$!;          $joinKey =~ m!^([^/]+)/(.+)$!;
508                  my ($source, $target, $clause) = ($self->ComputeObjectSentence($1),          my ($sourceRelation, $targetRelation) = ($1, $2);
509                                                                                    $self->ComputeObjectSentence($2),          Trace("Join with key $joinKey is from $sourceRelation to $targetRelation.") if T(4);
510                                                                                    $joinTable->{$joinKey});          my $source = $self->ComputeObjectSentence($sourceRelation);
511            my $target = $self->ComputeObjectSentence($targetRelation);
512            my $clause = $joinTable->{$joinKey};
513                  # Display them in a table row.                  # Display them in a table row.
514                  print HTMLOUT "<tr><td>$source</td><td>$target</td><td>$clause</td></tr>\n";                  print HTMLOUT "<tr><td>$source</td><td>$target</td><td>$clause</td></tr>\n";
515          }          }
# Line 290  Line 519 
519          print HTMLOUT "</body>\n</html>\n";          print HTMLOUT "</body>\n</html>\n";
520          # Close the file.          # Close the file.
521          close HTMLOUT;          close HTMLOUT;
522        Trace("Built MetaData web page.") if T(3);
523  }  }
524    
525  =head3 DumpMetaData  =head3 DumpMetaData
# Line 302  Line 532 
532    
533  sub DumpMetaData {  sub DumpMetaData {
534          # Get the parameters.          # Get the parameters.
535          my $self = shift @_;      my ($self) = @_;
536          # Dump the meta-data.          # Dump the meta-data.
537          return Data::Dumper::Dumper($self->{_metaData});          return Data::Dumper::Dumper($self->{_metaData});
538  }  }
# Line 320  Line 550 
550    
551  sub CreateTables {  sub CreateTables {
552          # Get the parameters.          # Get the parameters.
553          my $self = shift @_;      my ($self) = @_;
554          my $metadata = $self->{_metaData};          my $metadata = $self->{_metaData};
555          my $dbh = $self->{_dbh};          my $dbh = $self->{_dbh};
556          # Loop through the entities.          # Loop through the entities.
557          while (my ($entityName, $entityData) = each %{$metadata->{Entities}}) {      my $entityHash = $metadata->{Entities};
558        for my $entityName (keys %{$entityHash}) {
559            my $entityData = $entityHash->{$entityName};
560                  # Tell the user what we're doing.                  # Tell the user what we're doing.
561                  Trace("Creating relations for entity $entityName.") if T(1);                  Trace("Creating relations for entity $entityName.") if T(1);
562                  # Loop through the entity's relations.                  # Loop through the entity's relations.
# Line 366  Line 598 
598    
599  sub CreateTable {  sub CreateTable {
600          # Get the parameters.          # Get the parameters.
601          my $self = shift @_;      my ($self, $relationName, $indexFlag) = @_;
         my ($relationName, $indexFlag) = @_;  
602          # Get the database handle.          # Get the database handle.
603          my $dbh = $self->{_dbh};          my $dbh = $self->{_dbh};
604          # 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 414  Line 645 
645    
646  sub CreateIndex {  sub CreateIndex {
647          # Get the parameters.          # Get the parameters.
648          my $self = shift @_;      my ($self, $relationName) = @_;
         my ($relationName) = @_;  
649          # Get the relation's descriptor.          # Get the relation's descriptor.
650          my $relationData = $self->_FindRelation($relationName);          my $relationData = $self->_FindRelation($relationName);
651          # Get the database handle.          # Get the database handle.
652          my $dbh = $self->{_dbh};          my $dbh = $self->{_dbh};
653          # 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.
654          while (my ($indexName, $indexData) = each %{$relationData->{Indexes}}) {      my $indexHash = $relationData->{Indexes};
655        for my $indexName (keys %{$indexHash}) {
656            my $indexData = $indexHash->{$indexName};
657                  # Get the index's field list.                  # Get the index's field list.
658                  my @fieldList = _FixNames(@{$indexData->{IndexFields}});                  my @fieldList = _FixNames(@{$indexData->{IndexFields}});
659                  my $flds = join(', ', @fieldList);                  my $flds = join(', ', @fieldList);
# Line 471  Line 703 
703    
704  sub LoadTables {  sub LoadTables {
705          # Get the parameters.          # Get the parameters.
706          my $self = shift @_;      my ($self, $directoryName, $rebuild) = @_;
         my ($directoryName, $rebuild) = @_;  
707          # Start the timer.          # Start the timer.
708          my $startTime = gettimeofday;          my $startTime = gettimeofday;
709          # Clean any trailing slash from the directory name.          # Clean any trailing slash from the directory name.
# Line 514  Line 745 
745    
746  sub GetTableNames {  sub GetTableNames {
747          # Get the parameters.          # Get the parameters.
748          my $self = shift @_;      my ($self) = @_;
749          # Get the relation list from the metadata.          # Get the relation list from the metadata.
750          my $relationTable = $self->{_metaData}->{RelationTable};          my $relationTable = $self->{_metaData}->{RelationTable};
751          # Return the relation names.          # Return the relation names.
# Line 531  Line 762 
762    
763  sub GetEntityTypes {  sub GetEntityTypes {
764          # Get the database object.          # Get the database object.
765          my $self = shift @_;      my ($self) = @_;
766          # Get the entity list from the metadata object.          # Get the entity list from the metadata object.
767          my $entityList = $self->{_metaData}->{Entities};          my $entityList = $self->{_metaData}->{Entities};
768          # Return the list of entity names in alphabetical order.          # Return the list of entity names in alphabetical order.
# Line 616  Line 847 
847    
848  sub Get {  sub Get {
849          # Get the parameters.          # Get the parameters.
850          my $self = shift @_;      my ($self, $objectNames, $filterClause, @params) = @_;
         my ($objectNames, $filterClause, @params) = @_;  
851          # Construct the SELECT statement. The general pattern is          # Construct the SELECT statement. The general pattern is
852          #          #
853          # SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN          # SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN
# Line 739  Line 969 
969          return $retVal;          return $retVal;
970  }  }
971    
972    =head3 GetList
973    
974    C<< my @dbObjects = $database->GetList(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>
975    
976    Return a list of object descriptors for the specified objects as determined by the
977    specified filter clause.
978    
979    This method is essentially the same as L</Get> except it returns a list of objects rather
980    than a query object that can be used to get the results one record at a time.
981    
982    =over 4
983    
984    =item objectNames
985    
986    List containing the names of the entity and relationship objects to be retrieved.
987    
988    =item filterClause
989    
990    WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
991    be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
992    specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
993    in the filter clause should be added to the parameter list as additional parameters. The
994    fields in a filter clause can come from primary entity relations, relationship relations,
995    or secondary entity relations; however, all of the entities and relationships involved must
996    be included in the list of object names.
997    
998    The filter clause can also specify a sort order. To do this, simply follow the filter string
999    with an ORDER BY clause. For example, the following filter string gets all genomes for a
1000    particular genus and sorts them by species name.
1001    
1002    C<< "Genome(genus) = ? ORDER BY Genome(species)" >>
1003    
1004    The rules for field references in a sort order are the same as those for field references in the
1005    filter clause in general; however, odd things may happen if a sort field is from a secondary
1006    relation.
1007    
1008    =item param1, param2, ..., paramN
1009    
1010    Parameter values to be substituted into the filter clause.
1011    
1012    =item RETURN
1013    
1014    Returns a list of B<DBObject>s that satisfy the query conditions.
1015    
1016    =back
1017    
1018    =cut
1019    #: Return Type @%
1020    sub GetList {
1021        # Get the parameters.
1022        my ($self, $objectNames, $filterClause, @params) = @_;
1023        # Declare the return variable.
1024        my @retVal = ();
1025        # Perform the query.
1026        my $query = $self->Get($objectNames, $filterClause, @params);
1027        # Loop through the results.
1028        while (my $object = $query->Fetch) {
1029            push @retVal, $object;
1030        }
1031        # Return the result.
1032        return @retVal;
1033    }
1034    
1035  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
1036    
1037  C<< my $sentence = $database->ComputeObjectSentence($objectName); >>  C<< my $sentence = $database->ComputeObjectSentence($objectName); >>
# Line 761  Line 1054 
1054    
1055  sub ComputeObjectSentence {  sub ComputeObjectSentence {
1056          # Get the parameters.          # Get the parameters.
1057          my $self = shift @_;      my ($self, $objectName) = @_;
         my ($objectName) = @_;  
1058          # Set the default return value.          # Set the default return value.
1059          my $retVal = $objectName;          my $retVal = $objectName;
1060          # Look for the object as a relationship.          # Look for the object as a relationship.
# Line 794  Line 1086 
1086    
1087  sub DumpRelations {  sub DumpRelations {
1088          # Get the parameters.          # Get the parameters.
1089          my $self = shift @_;      my ($self, $outputDirectory) = @_;
         my ($outputDirectory) = @_;  
1090          # 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.
1091          my $metaData = $self->{_metaData};          my $metaData = $self->{_metaData};
1092          my $entities = $metaData->{Entities};          my $entities = $metaData->{Entities};
1093          while (my ($entityName, $entityStructure) = each %{$entities}) {      for my $entityName (keys %{$entities}) {
1094            my $entityStructure = $entities->{$entityName};
1095                  # Get the entity's relations.                  # Get the entity's relations.
1096                  my $relationList = $entityStructure->{Relations};                  my $relationList = $entityStructure->{Relations};
1097                  # Loop through the relations, dumping them.                  # Loop through the relations, dumping them.
1098                  while (my ($relationName, $relation) = each %{$relationList}) {          for my $relationName (keys %{$relationList}) {
1099                my $relation = $relationList->{$relationName};
1100                          $self->_DumpRelation($outputDirectory, $relationName, $relation);                          $self->_DumpRelation($outputDirectory, $relationName, $relation);
1101                  }                  }
1102          }          }
1103          # Next, we loop through the relationships.          # Next, we loop through the relationships.
1104          my $relationships = $metaData->{Relationships};          my $relationships = $metaData->{Relationships};
1105          while (my ($relationshipName, $relationshipStructure) = each %{$relationships}) {      for my $relationshipName (keys %{$relationships}) {
1106            my $relationshipStructure = $relationships->{$relationshipName};
1107                  # Dump this relationship's relation.                  # Dump this relationship's relation.
1108                  $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});                  $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});
1109          }          }
# Line 853  Line 1147 
1147    
1148  sub InsertObject {  sub InsertObject {
1149          # Get the parameters.          # Get the parameters.
1150          my $self = shift @_;      my ($self, $newObjectType, $fieldHash) = @_;
         my ($newObjectType, $fieldHash) = @_;  
1151          # Denote that so far we appear successful.          # Denote that so far we appear successful.
1152          my $retVal = 1;          my $retVal = 1;
1153          # Get the database handle.          # Get the database handle.
# Line 864  Line 1157 
1157          # 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
1158          # 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
1159          # stop the loop.          # stop the loop.
1160          while ($retVal && (my ($relationName, $relationDefinition) = each %{$relationTable})) {      my @relationList = keys %{$relationTable};
1161        for (my $i = 0; $retVal && $i <= $#relationList; $i++) {
1162            my $relationName = $relationList[$i];
1163            my $relationDefinition = $relationTable->{$relationName};
1164                  # 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
1165                  # 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
1166                  # @missing list.                  # @missing list.
# Line 956  Line 1252 
1252    
1253  C<< my %results = $database->LoadTable($fileName, $relationName, $truncateFlag); >>  C<< my %results = $database->LoadTable($fileName, $relationName, $truncateFlag); >>
1254    
1255  Load data from a tab-delimited file into a specified table, optionally re-creating the table first.  Load data from a tab-delimited file into a specified table, optionally re-creating the table
1256    first.
1257    
1258  =over 4  =over 4
1259    
# Line 974  Line 1271 
1271    
1272  =item RETURN  =item RETURN
1273    
1274  Returns a statistical object containing the number of records read and a list of the error messages.  Returns a statistical object containing the number of records read and a list of
1275    the error messages.
1276    
1277  =back  =back
1278    
1279  =cut  =cut
1280  sub LoadTable {  sub LoadTable {
1281          # Get the parameters.          # Get the parameters.
1282          my $self = shift @_;      my ($self, $fileName, $relationName, $truncateFlag) = @_;
         my ($fileName, $relationName, $truncateFlag) = @_;  
1283          # Create the statistical return object.          # Create the statistical return object.
1284          my $retVal = _GetLoadStats();          my $retVal = _GetLoadStats();
1285          # Trace the fact of the load.          # Trace the fact of the load.
1286          Trace("Loading table $relationName from $fileName") if T(1);      Trace("Loading table $relationName from $fileName") if T(2);
1287          # Get the database handle.          # Get the database handle.
1288          my $dbh = $self->{_dbh};          my $dbh = $self->{_dbh};
1289          # Get the relation data.          # Get the relation data.
1290          my $relation = $self->_FindRelation($relationName);          my $relation = $self->_FindRelation($relationName);
1291          # Check the truncation flag.          # Check the truncation flag.
1292          if ($truncateFlag) {          if ($truncateFlag) {
1293                  Trace("Creating table $relationName") if T(1);          Trace("Creating table $relationName") if T(2);
1294                  # Re-create the table without its index.                  # Re-create the table without its index.
1295                  $self->CreateTable($relationName, 0);                  $self->CreateTable($relationName, 0);
1296            # If this is a pre-index DBMS, create the index here.
1297            if ($dbh->{_preIndex}) {
1298                eval {
1299                    $self->CreateIndex($relationName);
1300                };
1301                if ($@) {
1302                    $retVal->AddMessage($@);
1303                }
1304            }
1305          }          }
1306          # Determine whether or not this is a primary relation. Primary relations have an extra          # Determine whether or not this is a primary relation. Primary relations have an extra
1307          # field indicating whether or not a given object is new or was loaded from the flat files.          # field indicating whether or not a given object is new or was loaded from the flat files.
# Line 1003  Line 1309 
1309          # Get the number of fields in this relation.          # Get the number of fields in this relation.
1310          my @fieldList = @{$relation->{Fields}};          my @fieldList = @{$relation->{Fields}};
1311          my $fieldCount = @fieldList;          my $fieldCount = @fieldList;
         # Record the number of expected fields.  
         my $expectedFields = $fieldCount + ($primary ? 1 : 0);  
1312          # Start a database transaction.          # Start a database transaction.
1313          $dbh->begin_tran;          $dbh->begin_tran;
1314          # Open the relation file. We need to create a cleaned-up copy before loading.          # Open the relation file. We need to create a cleaned-up copy before loading.
1315          open TABLEIN, '<', $fileName;          open TABLEIN, '<', $fileName;
1316          my $tempName = "$fileName.tbl";          my $tempName = "$fileName.tbl";
1317          open TABLEOUT, '>', $tempName;          open TABLEOUT, '>', $tempName;
1318        my $inputCount = 0;
1319          # Loop through the file.          # Loop through the file.
1320          while (<TABLEIN>) {          while (<TABLEIN>) {
1321            $inputCount++;
1322                  # Chop off the new-line character.                  # Chop off the new-line character.
1323                  my $record = $_;          my $record = Tracer::Strip($_);
1324                  chomp $record;          # Only proceed if the record is non-blank.
1325            if ($record) {
1326                  # Escape all the backslashes found in the line.                  # Escape all the backslashes found in the line.
1327                  $record =~ s/\\/\\\\/g;                  $record =~ s/\\/\\\\/g;
1328                # Insure the number of fields is correct.
1329                my @fields = split /\t/, $record;
1330                while (@fields > $fieldCount) {
1331                    my $extraField = $fields[$#fields];
1332                    delete $fields[$#fields];
1333                    if ($extraField) {
1334                        Trace("Nonblank extra field value \"$extraField\" deleted from record $inputCount of $fileName.") if T(1);
1335                    }
1336                }
1337                while (@fields < $fieldCount) {
1338                    push @fields, "";
1339                }
1340                  # If this is a primary relation, add a 0 for the new-record flag (indicating that                  # If this is a primary relation, add a 0 for the new-record flag (indicating that
1341                  # this record is not new, but part of the original load).                  # this record is not new, but part of the original load).
1342                  if ($primary) {                  if ($primary) {
1343                          $record .= "\t0";                  push @fields, "0";
1344                  }                  }
1345                  # Write the record.                  # Write the record.
1346                $record = join "\t", @fields;
1347                  print TABLEOUT "$record\n";                  print TABLEOUT "$record\n";
1348                  # Count the record read.              # Count the record written.
1349                  my $count = $retVal->Add('records');                  my $count = $retVal->Add('records');
1350                my $len = length $record;
1351                Trace("Record $count written with $len characters.") if T(4);
1352            } else {
1353                # Here we have a blank record.
1354                $retVal->Add('skipped');
1355            }
1356          }          }
1357          # Close the files.          # Close the files.
1358          close TABLEIN;          close TABLEIN;
1359          close TABLEOUT;          close TABLEOUT;
1360        Trace("Temporary file $tempName created.") if T(2);
1361          # Load the table.          # Load the table.
1362          my $rv;          my $rv;
1363          eval {          eval {
1364                  $rv = $dbh->load_table(file => $tempName, tbl => $relationName);                  $rv = $dbh->load_table(file => $tempName, tbl => $relationName);
1365          };          };
1366          if (!defined $rv) {          if (!defined $rv) {
1367                  $retVal->AddMessage("Table load failed for $relationName.");          $retVal->AddMessage($@) if ($@);
1368            $retVal->AddMessage("Table load failed for $relationName using $tempName.");
1369                  Trace("Table load failed for $relationName.") if T(1);                  Trace("Table load failed for $relationName.") if T(1);
1370          } else {          } else {
1371                  # Here we successfully loaded the table. Trace the number of records loaded.                  # Here we successfully loaded the table. Trace the number of records loaded.
1372                  Trace("$retVal->{records} records read for $relationName.") if T(1);          Trace("$retVal->{records} records read for $relationName.") if T(2);
1373                  # If we're rebuilding, we need to create the table indexes.                  # If we're rebuilding, we need to create the table indexes.
1374                  if ($truncateFlag) {          if ($truncateFlag && ! $dbh->{_preIndex}) {
1375                          eval {                          eval {
1376                                  $self->CreateIndex($relationName);                                  $self->CreateIndex($relationName);
1377                          };                          };
# Line 1100  Line 1428 
1428    
1429  sub GenerateEntity {  sub GenerateEntity {
1430          # Get the parameters.          # Get the parameters.
1431          my $self = shift @_;      my ($self, $id, $type, $values) = @_;
         my ($id, $type, $values) = @_;  
1432          # Create the return hash.          # Create the return hash.
1433          my $this = { id => $id };          my $this = { id => $id };
1434          # Get the metadata structure.          # Get the metadata structure.
# Line 1119  Line 1446 
1446          return $this;          return $this;
1447  }  }
1448    
1449    =head3 GetEntity
1450    
1451    C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>
1452    
1453    Return an object describing the entity instance with a specified ID.
1454    
1455    =over 4
1456    
1457    =item entityType
1458    
1459    Entity type name.
1460    
1461    =item ID
1462    
1463    ID of the desired entity.
1464    
1465    =item RETURN
1466    
1467    Returns a B<DBObject> representing the desired entity instance, or an undefined value if no
1468    instance is found with the specified key.
1469    
1470    =back
1471    
1472    =cut
1473    
1474    sub GetEntity {
1475        # Get the parameters.
1476        my ($self, $entityType, $ID) = @_;
1477        # Create a query.
1478        my $query = $self->Get([$entityType], "$entityType(id) = ?", $ID);
1479        # Get the first (and only) object.
1480        my $retVal = $query->Fetch();
1481        # Return the result.
1482        return $retVal;
1483    }
1484    
1485    =head3 GetEntityValues
1486    
1487    C<< my @values = GetEntityValues($entityType, $ID, \@fields); >>
1488    
1489    Return a list of values from a specified entity instance.
1490    
1491    =over 4
1492    
1493    =item entityType
1494    
1495    Entity type name.
1496    
1497    =item ID
1498    
1499    ID of the desired entity.
1500    
1501    =item fields
1502    
1503    List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.
1504    
1505    =item RETURN
1506    
1507    Returns a flattened list of the values of the specified fields for the specified entity.
1508    
1509    =back
1510    
1511    =cut
1512    
1513    sub GetEntityValues {
1514        # Get the parameters.
1515        my ($self, $entityType, $ID, $fields) = @_;
1516        # Get the specified entity.
1517        my $entity = $self->GetEntity($entityType, $ID);
1518        # Declare the return list.
1519        my @retVal = ();
1520        # If we found the entity, push the values into the return list.
1521        if ($entity) {
1522            push @retVal, $entity->Values($fields);
1523        }
1524        # Return the result.
1525        return @retVal;
1526    }
1527    
1528    =head3 GetAll
1529    
1530    C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>
1531    
1532    Return a list of values taken from the objects returned by a query. The first three
1533    parameters correspond to the parameters of the L</Get> method. The final parameter is
1534    a list of the fields desired from each record found by the query. The field name
1535    syntax is the standard syntax used for fields in the B<ERDB> system--
1536    B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity
1537    or relationship and I<fieldName> is the name of the field.
1538    
1539    The list returned will be a list of lists. Each element of the list will contain
1540    the values returned for the fields specified in the fourth parameter. If one of the
1541    fields specified returns multiple values, they are flattened in with the rest. For
1542    example, the following call will return a list of the features in a particular
1543    spreadsheet cell, and each feature will be represented by a list containing the
1544    feature ID followed by all of its aliases.
1545    
1546    C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>
1547    
1548    =over 4
1549    
1550    =item objectNames
1551    
1552    List containing the names of the entity and relationship objects to be retrieved.
1553    
1554    =item filterClause
1555    
1556    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1557    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1558    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1559    parameter list as additional parameters. The fields in a filter clause can come from primary
1560    entity relations, relationship relations, or secondary entity relations; however, all of the
1561    entities and relationships involved must be included in the list of object names.
1562    
1563    =item parameterList
1564    
1565    List of the parameters to be substituted in for the parameters marks in the filter clause.
1566    
1567    =item fields
1568    
1569    List of the fields to be returned in each element of the list returned.
1570    
1571    =item count
1572    
1573    Maximum number of records to return. If omitted or 0, all available records will be returned.
1574    
1575    =item RETURN
1576    
1577    Returns a list of list references. Each element of the return list contains the values for the
1578    fields specified in the B<fields> parameter.
1579    
1580    =back
1581    
1582    =cut
1583    #: Return Type @@;
1584    sub GetAll {
1585        # Get the parameters.
1586        my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
1587        # Translate the parameters from a list reference to a list. If the parameter
1588        # list is a scalar we convert it into a singleton list.
1589        my @parmList = ();
1590        if (ref $parameterList eq "ARRAY") {
1591            @parmList = @{$parameterList};
1592        } else {
1593            push @parmList, $parameterList;
1594        }
1595        # Create the query.
1596        my $query = $self->Get($objectNames, $filterClause, @parmList);
1597        # Set up a counter of the number of records read.
1598        my $fetched = 0;
1599        # Insure the counter has a value.
1600        if (!defined $count) {
1601            $count = 0;
1602        }
1603        # Loop through the records returned, extracting the fields. Note that if the
1604        # counter is non-zero, we stop when the number of records read hits the count.
1605        my @retVal = ();
1606        while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
1607            my @rowData = $row->Values($fields);
1608            push @retVal, \@rowData;
1609            $fetched++;
1610        }
1611        # Return the resulting list.
1612        return @retVal;
1613    }
1614    
1615  =head2 Internal Utility Methods  =head2 Internal Utility Methods
1616    
# Line 1234  Line 1726 
1726    
1727  sub _DumpRelation {  sub _DumpRelation {
1728          # Get the parameters.          # Get the parameters.
1729          my $self = shift @_;      my ($self, $outputDirectory, $relationName, $relation) = @_;
         my ($outputDirectory, $relationName, $relation) = @_;  
1730          # Open the output file.          # Open the output file.
1731          my $fileName = "$outputDirectory/$relationName.dtx";          my $fileName = "$outputDirectory/$relationName.dtx";
1732          open(DTXOUT, ">$fileName") || Confess("Could not open dump file $fileName: $!");          open(DTXOUT, ">$fileName") || Confess("Could not open dump file $fileName: $!");
# Line 1281  Line 1772 
1772    
1773  sub _GetStructure {  sub _GetStructure {
1774          # Get the parameters.          # Get the parameters.
1775          my $self = shift @_;      my ($self, $objectName) = @_;
         my ($objectName) = @_;  
1776          # Get the metadata structure.          # Get the metadata structure.
1777          my $metadata = $self->{_metaData};          my $metadata = $self->{_metaData};
1778          # Declare the variable to receive the descriptor.          # Declare the variable to receive the descriptor.
# Line 1321  Line 1811 
1811    
1812  sub _GetRelationTable {  sub _GetRelationTable {
1813          # Get the parameters.          # Get the parameters.
1814          my $self = shift @_;      my ($self, $objectName) = @_;
         my ($objectName) = @_;  
1815          # Get the descriptor from the metadata.          # Get the descriptor from the metadata.
1816          my $objectData = $self->_GetStructure($objectName);          my $objectData = $self->_GetStructure($objectName);
1817          # Return the object's relation list.          # Return the object's relation list.
# Line 1351  Line 1840 
1840    
1841  sub _GetFieldTable {  sub _GetFieldTable {
1842          # Get the parameters.          # Get the parameters.
1843          my $self = shift @_;      my ($self, $objectName) = @_;
         my ($objectName) = @_;  
1844          # Get the descriptor from the metadata.          # Get the descriptor from the metadata.
1845          my $objectData = $self->_GetStructure($objectName);          my $objectData = $self->_GetStructure($objectName);
1846          # Return the object's field table.          # Return the object's field table.
# Line 1449  Line 1937 
1937    
1938  sub _LoadRelation {  sub _LoadRelation {
1939          # Get the parameters.          # Get the parameters.
1940          my $self = shift @_;      my ($self, $directoryName, $relationName, $rebuild) = @_;
         my ($directoryName, $relationName, $rebuild) = @_;  
1941          # Create the file name.          # Create the file name.
1942          my $fileName = "$directoryName/$relationName";          my $fileName = "$directoryName/$relationName";
1943          # If the file doesn't exist, try adding the .dtx suffix.          # If the file doesn't exist, try adding the .dtx suffix.
# Line 1524  Line 2011 
2011          my %masterRelationTable = ();          my %masterRelationTable = ();
2012          # Loop through the entities.          # Loop through the entities.
2013          my $entityList = $metadata->{Entities};          my $entityList = $metadata->{Entities};
2014          while (my ($entityName, $entityStructure) = each %{$entityList}) {      for my $entityName (keys %{$entityList}) {
2015            my $entityStructure = $entityList->{$entityName};
2016                  #                  #
2017                  # The first step is to run creating all the entity's default values. For C<Field> elements,                  # The first step is to run creating all the entity's default values. For C<Field> elements,
2018                  # 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,
# Line 1572  Line 2060 
2060                  # to a list of fields. First, we need the ID field itself.                  # to a list of fields. First, we need the ID field itself.
2061                  my $idField = $fieldList->{id};                  my $idField = $fieldList->{id};
2062                  # Loop through the relations.                  # Loop through the relations.
2063                  while (my ($relationName, $relation) = each %{$relationTable}) {          for my $relationName (keys %{$relationTable}) {
2064                my $relation = $relationTable->{$relationName};
2065                          # Get the relation's field list.                          # Get the relation's field list.
2066                          my $relationFieldList = $relation->{Fields};                          my $relationFieldList = $relation->{Fields};
2067                          # Add the ID field to it. If the field's already there, it will not make any                          # Add the ID field to it. If the field's already there, it will not make any
# Line 1622  Line 2111 
2111                  # 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.
2112                  # 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
2113                  # the relations.                  # the relations.
2114                  while (my ($relationName, $relation) = each %{$relationTable}) {          for my $relationName (keys %{$relationTable}) {
2115                my $relation = $relationTable->{$relationName};
2116                          # Get the relation's index list.                          # Get the relation's index list.
2117                          my $indexList = $relation->{Indexes};                          my $indexList = $relation->{Indexes};
2118                          # Insure this relation has an ID index.                          # Insure this relation has an ID index.
# Line 1653  Line 2143 
2143          # 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.
2144          # For one thing, there is only a single constituent relation.          # For one thing, there is only a single constituent relation.
2145          my $relationshipList = $metadata->{Relationships};          my $relationshipList = $metadata->{Relationships};
2146          while (my ($relationshipName, $relationshipStructure) = each %{$relationshipList}) {      for my $relationshipName (keys %{$relationshipList}) {
2147            my $relationshipStructure = $relationshipList->{$relationshipName};
2148                  # Fix up this relationship.                  # Fix up this relationship.
2149                  _FixupFields($relationshipStructure, $relationshipName, 2, 3);                  _FixupFields($relationshipStructure, $relationshipName, 2, 3);
2150                  # Format a description for the FROM field.                  # Format a description for the FROM field.
# Line 1702  Line 2193 
2193                  my @fromList = ();                  my @fromList = ();
2194                  my @toList = ();                  my @toList = ();
2195                  my @bothList = ();                  my @bothList = ();
2196                  while (my ($relationshipName, $relationship) = each %{$relationshipList}) {          Trace("Join table build for $entityName.") if T(3);
2197            for my $relationshipName (keys %{$relationshipList}) {
2198                my $relationship = $relationshipList->{$relationshipName};
2199                          # 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.
2200                          if ($relationship->{from} eq $entityName) {              my $fromEntity = $relationship->{from};
2201                                  if ($relationship->{to} eq $entityName) {              my $toEntity = $relationship->{to};
2202                Trace("Join check for relationship $relationshipName from $fromEntity to $toEntity.") if T(3);
2203                if ($fromEntity eq $entityName) {
2204                    if ($toEntity eq $entityName) {
2205                                          # Here the relationship is recursive.                                          # Here the relationship is recursive.
2206                                          push @bothList, $relationshipName;                                          push @bothList, $relationshipName;
2207                        Trace("Relationship $relationshipName put in both-list.") if T(3);
2208                                  } else {                                  } else {
2209                                          # Here the relationship comes from the entity.                                          # Here the relationship comes from the entity.
2210                                          push @fromList, $relationshipName;                                          push @fromList, $relationshipName;
2211                        Trace("Relationship $relationshipName put in from-list.") if T(3);
2212                                  }                                  }
2213                          } elsif ($relationship->{to} eq $entityName) {              } elsif ($toEntity eq $entityName) {
2214                                  # Here the relationship goes to the entity.                                  # Here the relationship goes to the entity.
2215                                  push @toList, $relationshipName;                                  push @toList, $relationshipName;
2216                    Trace("Relationship $relationshipName put in to-list.") if T(3);
2217                          }                          }
2218                  }                  }
2219                  # Create the nonrecursive joins. Note that we build two hashes for running                  # Create the nonrecursive joins. Note that we build two hashes for running
# Line 1723  Line 2222 
2222                  # hash table at the same time.                  # hash table at the same time.
2223                  my %directRelationships = ( from => \@fromList, to => \@toList );                  my %directRelationships = ( from => \@fromList, to => \@toList );
2224                  my %otherRelationships = ( from => \@fromList, to => \@toList );                  my %otherRelationships = ( from => \@fromList, to => \@toList );
2225                  while (my ($linkType, $relationships) = each %directRelationships) {          for my $linkType (keys %directRelationships) {
2226                my $relationships = $directRelationships{$linkType};
2227                          # Loop through all the relationships.                          # Loop through all the relationships.
2228                          for my $relationshipName (@{$relationships}) {                          for my $relationshipName (@{$relationships}) {
2229                                  # Create joins between the entity and this relationship.                                  # Create joins between the entity and this relationship.
2230                                  my $linkField = "$relationshipName.${linkType}_link";                                  my $linkField = "$relationshipName.${linkType}_link";
2231                                  my $joinClause = "$entityName.id = $linkField";                                  my $joinClause = "$entityName.id = $linkField";
2232                    Trace("Entity join clause is $joinClause for $entityName and $relationshipName.") if T(4);
2233                                  $joinTable{"$entityName/$relationshipName"} = $joinClause;                                  $joinTable{"$entityName/$relationshipName"} = $joinClause;
2234                                  $joinTable{"$relationshipName/$entityName"} = $joinClause;                                  $joinTable{"$relationshipName/$entityName"} = $joinClause;
2235                                  # Create joins between this relationship and the other relationships.                                  # Create joins between this relationship and the other relationships.
2236                                  while (my ($otherType, $otherships) = each %otherRelationships) {                  for my $otherType (keys %otherRelationships) {
2237                        my $otherships = $otherRelationships{$otherType};
2238                                          for my $otherName (@{$otherships}) {                                          for my $otherName (@{$otherships}) {
2239                                                  # Get the key for this join.                                                  # Get the key for this join.
2240                                                  my $joinKey = "$otherName/$relationshipName";                                                  my $joinKey = "$otherName/$relationshipName";
# Line 1742  Line 2244 
2244                                                          # path is ambiguous. We delete the join from the join                                                          # path is ambiguous. We delete the join from the join
2245                                                          # table to prevent it from being used.                                                          # table to prevent it from being used.
2246                                                          delete $joinTable{$joinKey};                                                          delete $joinTable{$joinKey};
2247                                Trace("Deleting ambiguous join $joinKey.") if T(4);
2248                                                  } elsif ($otherName ne $relationshipName) {                                                  } elsif ($otherName ne $relationshipName) {
2249                                                          # Here we have a valid join. Note that joins between a                                                          # Here we have a valid join. Note that joins between a
2250                                                          # relationship and itself are prohibited.                                                          # relationship and itself are prohibited.
2251                                                          $joinTable{$joinKey} = "$otherName.${otherType}_link = $linkField";                              my $relJoinClause = "$otherName.${otherType}_link = $linkField";
2252                                $joinTable{$joinKey} = $relJoinClause;
2253                                Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(4);
2254                                                  }                                                  }
2255                                          }                                          }
2256                                  }                                  }
# Line 1754  Line 2259 
2259                                  # relationship can only be ambiguous with another recursive relationship,                                  # relationship can only be ambiguous with another recursive relationship,
2260                                  # and the incoming relationship from the outer loop is never recursive.                                  # and the incoming relationship from the outer loop is never recursive.
2261                                  for my $otherName (@bothList) {                                  for my $otherName (@bothList) {
2262                        Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(3);
2263                                          # Join from the left.                                          # Join from the left.
2264                                          $joinTable{"$relationshipName/$otherName"} =                                          $joinTable{"$relationshipName/$otherName"} =
2265                                                  "$linkField = $otherName.from_link";                                                  "$linkField = $otherName.from_link";
# Line 1768  Line 2274 
2274                  # 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
2275                  # possible to get the same effect using multiple queries.                  # possible to get the same effect using multiple queries.
2276                  for my $relationshipName (@bothList) {                  for my $relationshipName (@bothList) {
2277                Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(3);
2278                          # Join to the entity from each direction.                          # Join to the entity from each direction.
2279                          $joinTable{"$entityName/$relationshipName"} =                          $joinTable{"$entityName/$relationshipName"} =
2280                                  "$entityName.id = $relationshipName.from_link";                                  "$entityName.id = $relationshipName.from_link";
# Line 1907  Line 2414 
2414                  $structure->{Fields} = { };                  $structure->{Fields} = { };
2415          } else {          } else {
2416                  # Here we have a field list. Loop through its fields.                  # Here we have a field list. Loop through its fields.
2417                  while (my ($fieldName, $fieldData) = each %{$structure->{Fields}}) {          my $fieldStructures = $structure->{Fields};
2418            for my $fieldName (keys %{$fieldStructures}) {
2419                Trace("Processing field $fieldName of $defaultRelationName.") if T(4);
2420                my $fieldData = $fieldStructures->{$fieldName};
2421                          # Get the field type.                          # Get the field type.
2422                          my $type = $fieldData->{type};                          my $type = $fieldData->{type};
2423                          # Plug in a relation name if it is needed.                          # Plug in a relation name if it is needed.
# Line 2104  Line 2614 
2614    
2615  sub _IsPrimary {  sub _IsPrimary {
2616          # Get the parameters.          # Get the parameters.
2617          my $self = shift @_;      my ($self, $relationName) = @_;
         my ($relationName) = @_;  
2618          # Check for the relation in the entity table.          # Check for the relation in the entity table.
2619          my $entityTable = $self->{_metaData}->{Entities};          my $entityTable = $self->{_metaData}->{Entities};
2620          my $retVal = exists $entityTable->{$relationName};          my $retVal = exists $entityTable->{$relationName};
# Line 2139  Line 2648 
2648  =cut  =cut
2649  sub _FindRelation {  sub _FindRelation {
2650          # Get the parameters.          # Get the parameters.
2651          my $self = shift @_;      my ($self, $relationName) = @_;
         my ($relationName) = @_;  
2652          # 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.
2653          my $metaData = $self->{_metaData};          my $metaData = $self->{_metaData};
2654          my $retVal = $metaData->{RelationTable}->{$relationName};          my $retVal = $metaData->{RelationTable}->{$relationName};
# Line 2268  Line 2776 
2776                  my $indexData = $indexTable->{$indexName};                  my $indexData = $indexTable->{$indexName};
2777                  # Determine whether or not the index is unique.                  # Determine whether or not the index is unique.
2778                  my $fullName = $indexName;                  my $fullName = $indexName;
2779                  if ($indexData->{Unique} eq "true") {          if (exists $indexData->{Unique} && $indexData->{Unique} eq "true") {
2780                          $fullName .= " (unique)";                          $fullName .= " (unique)";
2781                  }                  }
2782                  # Start an HTML list item for this index.                  # Start an HTML list item for this index.

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3