[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.6, Wed May 4 03:24:43 2005 UTC revision 1.17, Wed Jul 27 20:00:00 2005 UTC
# Line 2  Line 2 
2    
3          use strict;          use strict;
4          use Tracer;          use Tracer;
5          use DBKernel;      use DBrtns;
6          use Data::Dumper;          use Data::Dumper;
7          use XML::Simple;          use XML::Simple;
8          use DBQuery;          use DBQuery;
# Line 32  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 69  Line 70 
70  is described in the L</GenerateEntity> and L</GenerateConnection> methods, though it is not yet  is described in the L</GenerateEntity> and L</GenerateConnection> methods, though it is not yet
71  fully implemented.  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    
298  # GLOBALS  # GLOBALS
# Line 315  Line 539 
539    
540  =head3 CreateTables  =head3 CreateTables
541    
542  C<< $datanase->CreateTables(); >>  C<< $database->CreateTables(); >>
543    
544  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
545  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 413  Line 637 
637  C<< $database->CreateIndex($relationName); >>  C<< $database->CreateIndex($relationName); >>
638    
639  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
640  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.
641  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
642  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.
643    
644  =cut  =cut
645    
# Line 735  Line 959 
959                          $command .= " ORDER BY $orderClause";                          $command .= " ORDER BY $orderClause";
960                  }                  }
961          }          }
962          Trace("SQL query: $command") if T(2);      Trace("SQL query: $command") if T(3);
963          Trace("PARMS: '" . (join "', '", @params) . "'") if (T(3) && (@params > 0));      Trace("PARMS: '" . (join "', '", @params) . "'") if (T(4) && (@params > 0));
964          my $sth = $dbh->prepare_command($command);          my $sth = $dbh->prepare_command($command);
965          # Execute it with the parameters bound in.          # Execute it with the parameters bound in.
966          $sth->execute(@params) || Confess("SELECT error" . $sth->errstr());          $sth->execute(@params) || Confess("SELECT error" . $sth->errstr());
# Line 753  Line 977 
977  specified filter clause.  specified filter clause.
978    
979  This method is essentially the same as L</Get> except it returns a list of objects rather  This method is essentially the same as L</Get> except it returns a list of objects rather
980  that a query object that can be used to get the results one record at a time.  than a query object that can be used to get the results one record at a time.
   
 =over 4  
981    
982  =over 4  =over 4
983    
# Line 1030  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 1048  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    
# Line 1059  Line 1283 
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 1076  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($_);
                 chomp $record;  
1324          # Only proceed if the record is non-blank.          # Only proceed if the record is non-blank.
1325          if ($record) {          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              # Eliminate any trailing tabs.              # Insure the number of fields is correct.
1329              chop $record while substr($record, -1) eq "\t";              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;              my $len = length $record;
1351              Trace("Record $count written with $len characters.") if T(4);              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(4);      Trace("Temporary file $tempName created.") if T(2);
1361      # Load the table.      # Load the table.
1362          my $rv;          my $rv;
1363          eval {          eval {
# Line 1123  Line 1369 
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 1133  Line 1379 
1379                                  $retVal->AddMessage($@);                                  $retVal->AddMessage($@);
1380                          }                          }
1381                  }                  }
1382            # Analyze the table to help optimize tables.
1383          }          }
1384          # Commit the database changes.          # Commit the database changes.
1385          $dbh->commit_tran;          $dbh->commit_tran;
1386        $dbh->vacuum_it($relationName);
1387          # Delete the temporary file.          # Delete the temporary file.
1388          unlink $tempName;          unlink $tempName;
1389          # Return the statistics.          # Return the statistics.
# Line 1279  Line 1527 
1527          return @retVal;          return @retVal;
1528  }  }
1529    
1530    =head3 GetAll
1531    
1532    C<< my @list = $sprout->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>
1533    
1534    Return a list of values taken from the objects returned by a query. The first three
1535    parameters correspond to the parameters of the L</Get> method. The final parameter is
1536    a list of the fields desired from each record found by the query. The field name
1537    syntax is the standard syntax used for fields in the B<ERDB> system--
1538    B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity
1539    or relationship and I<fieldName> is the name of the field.
1540    
1541    The list returned will be a list of lists. Each element of the list will contain
1542    the values returned for the fields specified in the fourth parameter. If one of the
1543    fields specified returns multiple values, they are flattened in with the rest. For
1544    example, the following call will return a list of the features in a particular
1545    spreadsheet cell, and each feature will be represented by a list containing the
1546    feature ID followed by all of its aliases.
1547    
1548    C<< $query = $sprout->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>
1549    
1550    =over 4
1551    
1552    =item objectNames
1553    
1554    List containing the names of the entity and relationship objects to be retrieved.
1555    
1556    =item filterClause
1557    
1558    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1559    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1560    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1561    parameter list as additional parameters. The fields in a filter clause can come from primary
1562    entity relations, relationship relations, or secondary entity relations; however, all of the
1563    entities and relationships involved must be included in the list of object names.
1564    
1565    =item parameterList
1566    
1567    List of the parameters to be substituted in for the parameters marks in the filter clause.
1568    
1569    =item fields
1570    
1571    List of the fields to be returned in each element of the list returned.
1572    
1573    =item count
1574    
1575    Maximum number of records to return. If omitted or 0, all available records will be returned.
1576    
1577    =item RETURN
1578    
1579    Returns a list of list references. Each element of the return list contains the values for the
1580    fields specified in the B<fields> parameter.
1581    
1582    =back
1583    
1584    =cut
1585    #: Return Type @@;
1586    sub GetAll {
1587        # Get the parameters.
1588        my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
1589        # Translate the parameters from a list reference to a list. If the parameter
1590        # list is a scalar we convert it into a singleton list.
1591        my @parmList = ();
1592        if (ref $parameterList eq "ARRAY") {
1593            @parmList = @{$parameterList};
1594        } else {
1595            push @parmList, $parameterList;
1596        }
1597        # Create the query.
1598        my $query = $self->Get($objectNames, $filterClause, @parmList);
1599        # Set up a counter of the number of records read.
1600        my $fetched = 0;
1601        # Insure the counter has a value.
1602        if (!defined $count) {
1603            $count = 0;
1604        }
1605        # Loop through the records returned, extracting the fields. Note that if the
1606        # counter is non-zero, we stop when the number of records read hits the count.
1607        my @retVal = ();
1608        while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
1609            my @rowData = $row->Values($fields);
1610            push @retVal, \@rowData;
1611            $fetched++;
1612        }
1613        # Return the resulting list.
1614        return @retVal;
1615    }
1616    
1617  =head2 Internal Utility Methods  =head2 Internal Utility Methods
1618    
1619  =head3 GetLoadStats  =head3 GetLoadStats
# Line 1654  Line 1989 
1989  sub _LoadMetaData {  sub _LoadMetaData {
1990          # Get the parameters.          # Get the parameters.
1991          my ($filename) = @_;          my ($filename) = @_;
1992        Trace("Reading Sprout DBD from $filename.") if T(2);
1993          # 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
1994          # get the exact structure we want.          # get the exact structure we want.
1995          my $metadata = XML::Simple::XMLin($filename,          my $metadata = XML::Simple::XMLin($filename,
# Line 1681  Line 2017 
2017          for my $entityName (keys %{$entityList}) {          for my $entityName (keys %{$entityList}) {
2018                  my $entityStructure = $entityList->{$entityName};                  my $entityStructure = $entityList->{$entityName};
2019                  #                  #
2020                  # 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,
2021                  # 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,
2022                  # 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>
2023                  # 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 1860  Line 2196 
2196                  my @fromList = ();                  my @fromList = ();
2197                  my @toList = ();                  my @toList = ();
2198                  my @bothList = ();                  my @bothList = ();
2199                  Trace("Join table build for $entityName.") if T(3);          Trace("Join table build for $entityName.") if T(4);
2200                  for my $relationshipName (keys %{$relationshipList}) {                  for my $relationshipName (keys %{$relationshipList}) {
2201                          my $relationship = $relationshipList->{$relationshipName};                          my $relationship = $relationshipList->{$relationshipName};
2202                          # 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.
2203                          my $fromEntity = $relationship->{from};                          my $fromEntity = $relationship->{from};
2204                          my $toEntity = $relationship->{to};                          my $toEntity = $relationship->{to};
2205                          Trace("Join check for relationship $relationshipName from $fromEntity to $toEntity.") if T(3);              Trace("Join check for relationship $relationshipName from $fromEntity to $toEntity.") if T(4);
2206                          if ($fromEntity eq $entityName) {                          if ($fromEntity eq $entityName) {
2207                                  if ($toEntity eq $entityName) {                                  if ($toEntity eq $entityName) {
2208                                          # Here the relationship is recursive.                                          # Here the relationship is recursive.
2209                                          push @bothList, $relationshipName;                                          push @bothList, $relationshipName;
2210                                          Trace("Relationship $relationshipName put in both-list.") if T(3);                      Trace("Relationship $relationshipName put in both-list.") if T(4);
2211                                  } else {                                  } else {
2212                                          # Here the relationship comes from the entity.                                          # Here the relationship comes from the entity.
2213                                          push @fromList, $relationshipName;                                          push @fromList, $relationshipName;
2214                                          Trace("Relationship $relationshipName put in from-list.") if T(3);                      Trace("Relationship $relationshipName put in from-list.") if T(4);
2215                                  }                                  }
2216                          } elsif ($toEntity eq $entityName) {                          } elsif ($toEntity eq $entityName) {
2217                                  # Here the relationship goes to the entity.                                  # Here the relationship goes to the entity.
2218                                  push @toList, $relationshipName;                                  push @toList, $relationshipName;
2219                                  Trace("Relationship $relationshipName put in to-list.") if T(3);                  Trace("Relationship $relationshipName put in to-list.") if T(4);
2220                          }                          }
2221                  }                  }
2222                  # 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 1926  Line 2262 
2262                                  # relationship can only be ambiguous with another recursive relationship,                                  # relationship can only be ambiguous with another recursive relationship,
2263                                  # and the incoming relationship from the outer loop is never recursive.                                  # and the incoming relationship from the outer loop is never recursive.
2264                                  for my $otherName (@bothList) {                                  for my $otherName (@bothList) {
2265                                          Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(3);                      Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(4);
2266                                          # Join from the left.                                          # Join from the left.
2267                                          $joinTable{"$relationshipName/$otherName"} =                                          $joinTable{"$relationshipName/$otherName"} =
2268                                                  "$linkField = $otherName.from_link";                                                  "$linkField = $otherName.from_link";
# Line 1941  Line 2277 
2277                  # 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
2278                  # possible to get the same effect using multiple queries.                  # possible to get the same effect using multiple queries.
2279                  for my $relationshipName (@bothList) {                  for my $relationshipName (@bothList) {
2280                          Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(3);              Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(4);
2281                          # Join to the entity from each direction.                          # Join to the entity from each direction.
2282                          $joinTable{"$entityName/$relationshipName"} =                          $joinTable{"$entityName/$relationshipName"} =
2283                                  "$entityName.id = $relationshipName.from_link";                                  "$entityName.id = $relationshipName.from_link";
# Line 1992  Line 2328 
2328          # 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
2329          # the field to it.          # the field to it.
2330          unshift @{$newIndex->{IndexFields}}, $firstField;          unshift @{$newIndex->{IndexFields}}, $firstField;
2331        # If this is a one-to-many relationship, the "To" index is unique.
2332        if ($relationshipStructure->{arity} eq "1M" && $indexKey eq "To") {
2333            $newIndex->{Unique} = 'true';
2334        }
2335          # Add the index to the relation.          # Add the index to the relation.
2336          _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);          _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);
2337  }  }
# Line 2083  Line 2423 
2423                  # Here we have a field list. Loop through its fields.                  # Here we have a field list. Loop through its fields.
2424                  my $fieldStructures = $structure->{Fields};                  my $fieldStructures = $structure->{Fields};
2425                  for my $fieldName (keys %{$fieldStructures}) {                  for my $fieldName (keys %{$fieldStructures}) {
2426                Trace("Processing field $fieldName of $defaultRelationName.") if T(4);
2427                          my $fieldData = $fieldStructures->{$fieldName};                          my $fieldData = $fieldStructures->{$fieldName};
2428                          # Get the field type.                          # Get the field type.
2429                          my $type = $fieldData->{type};                          my $type = $fieldData->{type};

Legend:
Removed from v.1.6  
changed lines
  Added in v.1.17

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3