[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.5, Tue Apr 5 05:17:01 2005 UTC revision 1.96, Tue Feb 5 04:52:24 2008 UTC
# Line 1  Line 1 
1  package ERDB;  package ERDB;
2    
3          use strict;          use strict;
         use Carp;  
4          use Tracer;          use Tracer;
5          use DBKernel;      use DBrtns;
6          use Data::Dumper;          use Data::Dumper;
7          use XML::Simple;          use XML::Simple;
8          use DBQuery;          use DBQuery;
9          use DBObject;      use ERDBObject;
10          use Stats;          use Stats;
11          use Time::HiRes qw(gettimeofday);          use Time::HiRes qw(gettimeofday);
12        use Digest::MD5 qw(md5_base64);
13        use CGI;
14        use WikiTools;
15    
16  =head1 Entity-Relationship Database Package  =head1 Entity-Relationship Database Package
17    
# Line 33  Line 35 
35  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>).
36  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
37  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
38  (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
39  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
40  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
41    C<FeatureVirulence>.
42    
43  Entities are connected by binary relationships implemented using single relations possessing the  Entities are connected by binary relationships implemented using single relations possessing the
44  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 57  Line 60 
60  B<start-position>, which indicates where in the contig that the sequence begins. This attribute  B<start-position>, which indicates where in the contig that the sequence begins. This attribute
61  is implemented as the C<start_position> field in the C<IsMadeUpOf> relation.  is implemented as the C<start_position> field in the C<IsMadeUpOf> relation.
62    
63  The database itself is described by an XML file using the F<ERDatabase.xsd> schema. In addition to  The database itself is described by an XML file. In addition to all the data required to define
64  all the data required to define the entities, relationships, and attributes, the schema provides  the entities, relationships, and attributes, the schema provides space for notes describing
65  space for notes describing the data and what it means. These notes are used by L</ShowMetaData>  the data and what it means. These notes are used by L</ShowMetaData> to generate documentation
66  to generate documentation for the database.  for the database.
67    
68    Special support is provided for text searching. An entity field can be marked as <em>searchable</em>,
69    in which case it will be used to generate a text search index in which the user searches for words
70    in the field instead of a particular field value.
71    
72  Finally, every entity and relationship object has a flag indicating if it is new or old. The object  Finally, every entity and relationship object has a flag indicating if it is new or old. The object
73  is considered I<old> if it was loaded by the L</LoadTables> method. It is considered I<new> if it  is considered I<old> if it was loaded by the L</LoadTables> method. It is considered I<new> if it
74  was inserted by the L</InsertObject> method.  was inserted by the L</InsertObject> method.
75    
76  To facilitate testing, the ERDB module supports automatic generation of test data. This process  =head2 XML Database Description
77  is described in the L</GenerateEntity> and L</GenerateConnection> methods, though it is not yet  
78  fully implemented.  =head3 Data Types
79    
80    The ERDB system supports the following data types. Note that there are numerous string
81    types depending on the maximum length. Some database packages limit the total number of
82    characters you have in an index key; to insure the database works in all environments,
83    the type of string should be the shortest one possible that supports all the known values.
84    
85    =over 4
86    
87    =item char
88    
89    single ASCII character
90    
91    =item int
92    
93    32-bit signed integer
94    
95    =item counter
96    
97    32-bit unsigned integer
98    
99    =item date
100    
101    64-bit unsigned integer, representing a PERL date/time value
102    
103    =item text
104    
105    long string; Text fields cannot be used in indexes or sorting and do not support the
106    normal syntax of filter clauses, but can be up to a billion character in length
107    
108    =item float
109    
110    double-precision floating-point number
111    
112    =item boolean
113    
114    single-bit numeric value; The value is stored as a 16-bit signed integer (for
115    compatability with certain database packages), but the only values supported are
116    0 and 1.
117    
118    =item id-string
119    
120    variable-length string, maximum 25 characters
121    
122    =item key-string
123    
124    variable-length string, maximum 40 characters
125    
126    =item name-string
127    
128    variable-length string, maximum 80 characters
129    
130    =item medium-string
131    
132    variable-length string, maximum 160 characters
133    
134    =item string
135    
136    variable-length string, maximum 255 characters
137    
138    =item hash-string
139    
140    variable-length string, maximum 22 characters
141    
142    =back
143    
144    The hash-string data type has a special meaning. The actual key passed into the loader will
145    be a string, but it will be digested into a 22-character MD5 code to save space. Although the
146    MD5 algorithm is not perfect, it is extremely unlikely two strings will have the same
147    digest. Therefore, it is presumed the keys will be unique. When the database is actually
148    in use, the hashed keys will be presented rather than the original values. For this reason,
149    they should not be used for entities where the key is meaningful.
150    
151    =head3 Global Tags
152    
153    The entire database definition must be inside a B<Database> tag. The display name of
154    the database is given by the text associated with the B<Title> tag. The display name
155    is only used in the automated documentation. It has no other effect. The entities and
156    relationships are listed inside the B<Entities> and B<Relationships> tags,
157    respectively. None of these tags have attributes.
158    
159        <Database>
160            <Title>... display title here...</Title>
161            <Entities>
162                ... entity definitions here ...
163            </Entities>
164            <Relationships>
165                ... relationship definitions here...
166            </Relationships>
167        </Database>
168    
169    Entities, relationships, indexes, and fields all allow a text tag called B<Notes>.
170    The text inside the B<Notes> tag contains comments that will appear when the database
171    documentation is generated. Within a B<Notes> tag, you may use C<[i]> and C<[/i]> for
172    italics, C<[b]> and C<[/b]> for bold, and C<[p]> for a new paragraph.
173    
174    =head3 Fields
175    
176    Both entities and relationships have fields described by B<Field> tags. A B<Field>
177    tag can have B<Notes> associated with it. The complete set of B<Field> tags for an
178    object mus be inside B<Fields> tags.
179    
180        <Entity ... >
181            <Fields>
182                ... Field tags ...
183            </Fields>
184        </Entity>
185    
186    The attributes for the B<Field> tag are as follows.
187    
188    =over 4
189    
190    =item name
191    
192    Name of the field. The field name should contain only letters, digits, and hyphens (C<->),
193    and the first character should be a letter. Most underlying databases are case-insensitive
194    with the respect to field names, so a best practice is to use lower-case letters only. Finally,
195    the name C<search-relevance> has special meaning for full-text searches and should not be
196    used as a field name.
197    
198    =item type
199    
200    Data type of the field. The legal data types are given above.
201    
202    =item relation
203    
204    Name of the relation containing the field. This should only be specified for entity
205    fields. The ERDB system does not support optional fields or multi-occurring fields
206    in the primary relation of an entity. Instead, they are put into secondary relations.
207    So, for example, in the C<Genome> entity, the C<group-name> field indicates a special
208    grouping used to select a subset of the genomes. A given genome may not be in any
209    groups or may be in multiple groups. Therefore, C<group-name> specifies a relation
210    value. The relation name specified must be a valid table name. By convention, it is
211    usually the entity name followed by a qualifying word (e.g. C<GenomeGroup>). In an
212    entity, the fields without a relation attribute are said to belong to the
213    I<primary relation>. This relation has the same name as the entity itself.
214    
215    =item searchable
216    
217    If specified, then the field is a candidate for full-text searching. A single full-text
218    index will be created for each relation with at least one searchable field in it.
219    For best results, this option should only be used for string or text fields.
220    
221    =item special
222    
223    This attribute allows the subclass to assign special meaning for certain fields.
224    The interpretation is up to the subclass itself. Currently, only entity fields
225    can have this attribute.
226    
227    =back
228    
229    =head3 Indexes
230    
231    An entity can have multiple alternate indexes associated with it. The fields in an
232    index must all be from the same relation. The alternate indexes assist in searching
233    on fields other than the entity ID. A relationship has at least two indexes-- a I<to-index> and a
234    I<from-index> that order the results when crossing the relationship. For
235    example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the
236    from-index would order the contigs of a ganome, and the to-index would order
237    the genomes of a contig. In addition, it can have zero or more alternate
238    indexes. A relationship's index must specify only fields in
239    the relationship.
240    
241    The alternate indexes for an entity or relationship must be listed inside the B<Indexes> tag.
242    The from-index of a relationship is specified using the B<FromIndex> tag; the to-index is
243    specified using the B<ToIndex> tag.
244    
245    Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields>
246    tag containing the B<IndexField> tags. These specify, in order, the fields used in
247    the index. The attributes of an B<IndexField> tag are as follows.
248    
249    =over 4
250    
251    =item name
252    
253    Name of the field.
254    
255    =item order
256    
257    Sort order of the field-- C<ascending> or C<descending>.
258    
259    =back
260    
261    The B<FromIndex>, and B<ToIndex> tags have no attributes. The B<Index> tag can
262    have a B<Unique> attribute. If specified, the index will be generated as a unique
263    index.
264    
265    =head3 Object and Field Names
266    
267    By convention entity and relationship names use capital casing (e.g. C<Genome> or
268    C<HasRegionsIn>. Most underlying databases, however, are aggressively case-insensitive
269    with respect to relation names, converting them internally to all-upper case or
270    all-lower case.
271    
272    If syntax or parsing errors occur when you try to load or use an ERDB database, the
273    most likely reason is that one of your objects has an SQL reserved word as its name.
274    The list of SQL reserved words keeps increasing; however, most are unlikely to show
275    up as a noun or declarative verb phrase. The exceptions are C<Group>, C<User>,
276    C<Table>, C<Index>, C<Object>, C<Date>, C<Number>, C<Update>, C<Time>, C<Percent>,
277    C<Memo>, C<Order>, and C<Sum>. This problem can crop up in field names as well.
278    
279    Every entity has a field called C<id> that acts as its primary key. Every relationship
280    has fields called C<from-link> and C<to-link> that contain copies of the relevant
281    entity IDs. These are essentially ERDB's reserved words, and should not be used
282    for user-defined field names.
283    
284    =head3 Entities
285    
286    An entity is described by the B<Entity> tag. The entity can contain B<Notes>, an
287    B<Indexes> tag containing one or more secondary indexes, and a B<Fields> tag
288    containing one or more fields. The attributes of the B<Entity> tag are as follows.
289    
290    =over 4
291    
292    =item name
293    
294    Name of the entity. The entity name, by convention, uses capital casing (e.g. C<Genome>
295    or C<GroupBlock>) and should be a noun or noun phrase.
296    
297    =item keyType
298    
299    Data type of the primary key. The primary key is always named C<id>.
300    
301    =back
302    
303    =head3 Relationships
304    
305    A relationship is described by the C<Relationship> tag. Within a relationship,
306    there can be a C<Notes> tag, a C<Fields> tag containing the intersection data
307    fields, a C<FromIndex> tag containing the from-index, a C<ToIndex> tag containing
308    the to-index, and an C<Indexes> tag containing the alternate indexes.
309    
310    The C<Relationship> tag has the following attributes.
311    
312    =over 4
313    
314    =item name
315    
316    Name of the relationship. The relationship name, by convention, uses capital casing
317    (e.g. C<ContainsRegionIn> or C<HasContig>), and should be a declarative verb
318    phrase, designed to fit between the from-entity and the to-entity (e.g.
319    Block C<ContainsRegionIn> Genome).
320    
321    =item from
322    
323    Name of the entity from which the relationship starts.
324    
325    =item to
326    
327    Name of the entity to which the relationship proceeds.
328    
329    =item arity
330    
331    Relationship type: C<1M> for one-to-many and C<MM> for many-to-many.
332    
333    =back
334    
335  =cut  =cut
336    
# Line 76  Line 338 
338    
339  # Table of information about our datatypes. "sqlType" is the corresponding SQL datatype string.  # Table of information about our datatypes. "sqlType" is the corresponding SQL datatype string.
340  # "maxLen" is the maximum permissible length of the incoming string data used to populate a field  # "maxLen" is the maximum permissible length of the incoming string data used to populate a field
341  # of the specified type. "dataGen" is PERL string that will be evaluated if no test data generation  # of the specified type. "avgLen" is the average byte length for estimating
342   #string is specified in the field definition.  # record sizes. "sort" is the key modifier for the sort command, "notes" is a type description,
343  my %TypeTable = ( char =>        { sqlType => 'CHAR(1)',                        maxLen => 1,                    dataGen => "StringGen('A')" },  # and "indexMod", if non-zero, is the number of characters to use when the field is specified in an
344                                    int =>         { sqlType => 'INTEGER',                        maxLen => 20,                   dataGen => "IntGen(0, 99999999)" },  # index
345                                    string =>  { sqlType => 'VARCHAR(255)',               maxLen => 255,                  dataGen => "StringGen(IntGen(10,250))" },  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, sort => "",
346                                    text =>        { sqlType => 'TEXT',                           maxLen => 1000000000,   dataGen => "StringGen(IntGen(80,1000))" },                                 indexMod =>   0, notes => "single ASCII character"},
347                                    date =>        { sqlType => 'BIGINT',                         maxLen => 80,                   dataGen => "DateGen(-7, 7, IntGen(0,1400))" },                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, sort => "n",
348                                    float =>       { sqlType => 'DOUBLE PRECISION',       maxLen => 40,                   dataGen => "FloatGen(0.0, 100.0)" },                                 indexMod =>   0, notes => "signed 32-bit integer"},
349                                    boolean => { sqlType => 'SMALLINT',                   maxLen => 1,                    dataGen => "IntGen(0, 1)" },                    counter => { sqlType => 'INTEGER UNSIGNED',   maxLen => 20,           avgLen =>   4, sort => "n",
350                                   indexMod =>   0, notes => "unsigned 32-bit integer"},
351                      string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          avgLen => 100, sort => "",
352                                   indexMod =>   0, notes => "character string, 0 to 255 characters"},
353                      text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, sort => "",
354                                   indexMod => 255, notes => "character string, nearly unlimited length, only first 255 characters are indexed"},
355                      date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, sort => "n",
356                                   indexMod =>   0, notes => "signed, 64-bit integer"},
357                      float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, sort => "g",
358                                   indexMod =>   0, notes => "64-bit double precision floating-point number"},
359                      boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   1, sort => "n",
360                                   indexMod =>   0, notes => "boolean value: 0 if false, 1 if true"},
361                     'hash-string' =>
362                                 { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, sort => "",
363                                   indexMod =>   0, notes => "string stored in digested form, used for certain types of key fields"},
364                     'id-string' =>
365                                 { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, sort => "",
366                                   indexMod =>   0, notes => "character string, 0 to 25 characters"},
367                               'key-string' =>                               'key-string' =>
368                                                           { sqlType => 'VARCHAR(40)',            maxLen => 40,                   dataGen => "StringGen(IntGen(10,40))" },                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, sort => "",
369                                   indexMod =>   0, notes => "character string, 0 to 40 characters"},
370                                   'name-string' =>                                   'name-string' =>
371                                                           { sqlType => 'VARCHAR(80)',            maxLen => 80,                   dataGen => "StringGen(IntGen(10,80))" },                               { sqlType => 'VARCHAR(80)',        maxLen => 80,           avgLen =>  40, sort => "",
372                                   indexMod =>   0, notes => "character string, 0 to 80 characters"},
373                                   'medium-string' =>                                   'medium-string' =>
374                                                           { sqlType => 'VARCHAR(160)',           maxLen => 160,                  dataGen => "StringGen(IntGen(10,160))" },                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",
375                                   indexMod =>   0, notes => "character string, 0 to 160 characters"},
376                     'long-string' =>
377                                 { sqlType => 'VARCHAR(500)',       maxLen => 500,          avglen => 255, sort => "",
378                                   indexMod =>   0, notes => "character string, 0 to 500 characters"},
379                                  );                                  );
380    
381  # Table translating arities into natural language.  # Table translating arities into natural language.
# Line 99  Line 384 
384                                     'MM' => 'many-to-many'                                     'MM' => 'many-to-many'
385                                   );                                   );
386    
387  # Table for interpreting string patterns.  # Options for XML input and output.
388    
389    my %XmlOptions = (GroupTags =>  { Relationships => 'Relationship',
390                                      Entities => 'Entity',
391                                      Fields => 'Field',
392                                      Indexes => 'Index',
393                                      IndexFields => 'IndexField'
394                                    },
395                      KeyAttr =>    { Relationship => 'name',
396                                      Entity => 'name',
397                                      Field => 'name'
398                                    },
399                      SuppressEmpty => 1,
400                     );
401    
402  my %PictureTable = ( 'A' => "abcdefghijklmnopqrstuvwxyz",  my %XmlInOpts  = (
403                                           '9' => "0123456789",                    ForceArray => ['Field', 'Index', 'IndexField', 'Relationship', 'Entity'],
404                                           'X' => "abcdefghijklmnopqrstuvwxyz0123456789",                    ForceContent => 1,
405                                           'V' => "aeiou",                    NormalizeSpace => 2,
406                                           'K' => "bcdfghjklmnoprstvwxyz"                   );
407    my %XmlOutOpts = (
408                      RootName => 'Database',
409                      XMLDecl => 1,
410                                     );                                     );
411    
412    
413  =head2 Public Methods  =head2 Public Methods
414    
415  =head3 new  =head3 new
416    
417  C<< my $database = ERDB->new($dbh, $metaFileName); >>      my $database = ERDB->new($dbh, $metaFileName);
418    
419  Create a new ERDB object.  Create a new ERDB object.
420    
# Line 132  Line 434 
434    
435  sub new {  sub new {
436          # Get the parameters.          # Get the parameters.
437          my ($class, $dbh, $metaFileName, $options) = @_;      my ($class, $dbh, $metaFileName, %options) = @_;
438          # Load the meta-data.          # Load the meta-data.
439          my $metaData = _LoadMetaData($metaFileName);          my $metaData = _LoadMetaData($metaFileName);
440          # Create the object.          # Create the object.
# Line 140  Line 442 
442                                   _metaData => $metaData                                   _metaData => $metaData
443                             };                             };
444          # Bless and return it.          # Bless and return it.
445          bless $self;      bless $self, $class;
446          return $self;          return $self;
447  }  }
448    
449  =head3 ShowMetaData  =head3 ShowMetaData
450    
451  C<< $database->ShowMetaData($fileName); >>      $erdb->ShowMetaData($fileName);
452    
453  This method outputs a description of the database. This description can be used to help users create  This method outputs a description of the database. This description can be used to help users create
454  the data to be loaded into the relations.  the data to be loaded into the relations.
# Line 177  Line 479 
479          # Write the HTML heading stuff.          # Write the HTML heading stuff.
480          print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";          print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";
481          print HTMLOUT "</head>\n<body>\n";          print HTMLOUT "</head>\n<body>\n";
482        # Write the documentation.
483        print HTMLOUT $self->DisplayMetaData();
484        # Close the document.
485        print HTMLOUT "</body>\n</html>\n";
486        # Close the file.
487        close HTMLOUT;
488    }
489    
490    =head3 DisplayMetaData
491    
492        my $html = $erdb->DisplayMetaData();
493    
494    Return an HTML description of the database. This description can be used to help users create
495    the data to be loaded into the relations and form queries. The output is raw includable HTML
496    without any HEAD or BODY tags.
497    
498    =over 4
499    
500    =item filename
501    
502    The name of the output file.
503    
504    =back
505    
506    =cut
507    
508    sub DisplayMetaData {
509        # Get the parameters.
510        my ($self) = @_;
511        # Get the metadata and the title string.
512        my $metadata = $self->{_metaData};
513        # Get the title string.
514        my $title = $metadata->{Title};
515        # Get the entity and relationship lists.
516        my $entityList = $metadata->{Entities};
517        my $relationshipList = $metadata->{Relationships};
518        # Declare the return variable.
519        my $retVal = "";
520        # Open the output file.
521        Trace("Building MetaData table of contents.") if T(4);
522          # Here we do the table of contents. It starts as an unordered list of section names. Each          # Here we do the table of contents. It starts as an unordered list of section names. Each
523          # section contains an ordered list of entity or relationship subsections.          # section contains an ordered list of entity or relationship subsections.
524          print HTMLOUT "<ul>\n<li><a href=\"#EntitiesSection\">Entities</a>\n<ol>\n";      $retVal .= "<ul>\n<li><a href=\"#EntitiesSection\">Entities</a>\n<ol>\n";
525          # Loop through the Entities, displaying a list item for each.          # Loop through the Entities, displaying a list item for each.
526          foreach my $key (sort keys %{$entityList}) {          foreach my $key (sort keys %{$entityList}) {
527                  # Display this item.                  # Display this item.
528                  print HTMLOUT "<li><a href=\"#$key\">$key</a></li>\n";          $retVal .= "<li><a href=\"#$key\">$key</a></li>\n";
529          }          }
530          # Close off the entity section and start the relationship section.          # Close off the entity section and start the relationship section.
531          print HTMLOUT "</ol></li>\n<li><a href=\"#RelationshipsSection\">Relationships</a>\n<ol>\n";      $retVal .= "</ol></li>\n<li><a href=\"#RelationshipsSection\">Relationships</a>\n<ol>\n";
532          # Loop through the Relationships.          # Loop through the Relationships.
533          foreach my $key (sort keys %{$relationshipList}) {          foreach my $key (sort keys %{$relationshipList}) {
534                  # Display this item.                  # Display this item.
535                  my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});                  my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});
536                  print HTMLOUT "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";          $retVal .= "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";
537          }          }
538          # Close off the relationship section and list the join table section.          # Close off the relationship section and list the join table section.
539          print HTMLOUT "</ol></li>\n<li><a href=\"#JoinTable\">Join Table</a></li>\n";      $retVal .= "</ol></li>\n<li><a href=\"#JoinTable\">Join Table</a></li>\n";
540          # Close off the table of contents itself.          # Close off the table of contents itself.
541          print HTMLOUT "</ul>\n";      $retVal .=  "</ul>\n";
542          # Now we start with the actual data. Denote we're starting the entity section.          # Now we start with the actual data. Denote we're starting the entity section.
543          print HTMLOUT "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";      $retVal .= "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";
544          # Loop through the entities.          # Loop through the entities.
545          for my $key (sort keys %{$entityList}) {          for my $key (sort keys %{$entityList}) {
546                  Trace("Building MetaData entry for $key entity.") if T(4);                  Trace("Building MetaData entry for $key entity.") if T(4);
547                  # Create the entity header. It contains a bookmark and the entity name.                  # Create the entity header. It contains a bookmark and the entity name.
548                  print HTMLOUT "<a name=\"$key\"></a><h3>$key</h3>\n";          $retVal .= "<a name=\"$key\"></a><h3>$key</h3>\n";
549                  # Get the entity data.                  # Get the entity data.
550                  my $entityData = $entityList->{$key};                  my $entityData = $entityList->{$key};
551                  # If there's descriptive text, display it.                  # If there's descriptive text, display it.
552                  if (my $notes = $entityData->{Notes}) {                  if (my $notes = $entityData->{Notes}) {
553                          print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . HTMLNote($notes->{content}) . "</p>\n";
554                  }                  }
555                  # Now we want a list of the entity's relationships. First, we set up the relationship subsection.          # See if we need a list of the entity's relationships.
556                  print HTMLOUT "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";          my $relCount = keys %{$relationshipList};
557            if ($relCount > 0) {
558                # First, we set up the relationship subsection.
559                $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";
560                  # Loop through the relationships.                  # Loop through the relationships.
561                  for my $relationship (sort keys %{$relationshipList}) {                  for my $relationship (sort keys %{$relationshipList}) {
562                          # Get the relationship data.                          # Get the relationship data.
# Line 221  Line 566 
566                                  # Get the relationship sentence and append the arity.                                  # Get the relationship sentence and append the arity.
567                                  my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);                                  my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);
568                                  # Display the relationship data.                                  # Display the relationship data.
569                                  print HTMLOUT "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";                      $retVal .= "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";
570                          }                          }
571                  }                  }
572                  # Close off the relationship list.                  # Close off the relationship list.
573                  print HTMLOUT "</ul>\n";              $retVal .= "</ul>\n";
574            }
575                  # Get the entity's relations.                  # Get the entity's relations.
576                  my $relationList = $entityData->{Relations};                  my $relationList = $entityData->{Relations};
577                  # Create a header for the relation subsection.                  # Create a header for the relation subsection.
578                  print HTMLOUT "<h4>Relations for <b>$key</b></h4>\n";          $retVal .= "<h4>Relations for <b>$key</b></h4>\n";
579                  # Loop through the relations, displaying them.                  # Loop through the relations, displaying them.
580                  for my $relation (sort keys %{$relationList}) {                  for my $relation (sort keys %{$relationList}) {
581                          my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});                          my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});
582                          print HTMLOUT $htmlString;              $retVal .= $htmlString;
583                  }                  }
584          }          }
585          # Denote we're starting the relationship section.          # Denote we're starting the relationship section.
586          print HTMLOUT "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";      $retVal .= "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";
587          # Loop through the relationships.          # Loop through the relationships.
588          for my $key (sort keys %{$relationshipList}) {          for my $key (sort keys %{$relationshipList}) {
589                  Trace("Building MetaData entry for $key relationship.") if T(4);                  Trace("Building MetaData entry for $key relationship.") if T(4);
# Line 245  Line 591 
591                  my $relationshipStructure = $relationshipList->{$key};                  my $relationshipStructure = $relationshipList->{$key};
592                  # Create the relationship header.                  # Create the relationship header.
593                  my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);                  my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);
594                  print HTMLOUT "<h3><a name=\"$key\"></a>$headerText</h3>\n";          $retVal .= "<h3><a name=\"$key\"></a>$headerText</h3>\n";
595                  # Get the entity names.                  # Get the entity names.
596                  my $fromEntity = $relationshipStructure->{from};                  my $fromEntity = $relationshipStructure->{from};
597                  my $toEntity = $relationshipStructure->{to};                  my $toEntity = $relationshipStructure->{to};
# Line 255  Line 601 
601                  # since both sentences will say the same thing.                  # since both sentences will say the same thing.
602                  my $arity = $relationshipStructure->{arity};                  my $arity = $relationshipStructure->{arity};
603                  if ($arity eq "11") {                  if ($arity eq "11") {
604                          print HTMLOUT "<p>Each <b>$fromEntity</b> relates to at most one <b>$toEntity</b>.\n";              $retVal .= "<p>Each <b>$fromEntity</b> relates to at most one <b>$toEntity</b>.\n";
605                  } else {                  } else {
606                          print HTMLOUT "<p>Each <b>$fromEntity</b> relates to multiple <b>$toEntity</b>s.\n";              $retVal .= "<p>Each <b>$fromEntity</b> relates to multiple <b>$toEntity</b>s.\n";
607                          if ($arity eq "MM" && $fromEntity ne $toEntity) {                          if ($arity eq "MM" && $fromEntity ne $toEntity) {
608                                  print HTMLOUT "Each <b>$toEntity</b> relates to multiple <b>$fromEntity</b>s.\n";                  $retVal .= "Each <b>$toEntity</b> relates to multiple <b>$fromEntity</b>s.\n";
609                          }                          }
610                  }                  }
611                  print HTMLOUT "</p>\n";          $retVal .= "</p>\n";
612                  # If there are notes on this relationship, display them.                  # If there are notes on this relationship, display them.
613                  if (my $notes = $relationshipStructure->{Notes}) {                  if (my $notes = $relationshipStructure->{Notes}) {
614                          print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . HTMLNote($notes->{content}) . "</p>\n";
615                  }                  }
616                  # Generate the relationship's relation table.                  # Generate the relationship's relation table.
617                  my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});                  my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});
618                  print HTMLOUT $htmlString;          $retVal .= $htmlString;
619          }          }
620          Trace("Building MetaData join table.") if T(4);          Trace("Building MetaData join table.") if T(4);
621          # Denote we're starting the join table.          # Denote we're starting the join table.
622          print HTMLOUT "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";      $retVal .= "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";
623          # Create a table header.          # Create a table header.
624          print HTMLOUT _OpenTable("Join Table", "Source", "Target", "Join Condition");      $retVal .= _OpenTable("Join Table", "Source", "Target", "Join Condition");
625          # Loop through the joins.          # Loop through the joins.
626          my $joinTable = $metadata->{Joins};          my $joinTable = $metadata->{Joins};
627          for my $joinKey (sort keys %{$joinTable}) {      my @joinKeys = keys %{$joinTable};
628        for my $joinKey (sort @joinKeys) {
629                  # Separate out the source, the target, and the join clause.                  # Separate out the source, the target, and the join clause.
630                  $joinKey =~ m!([^/]*)/(.*)$!;          $joinKey =~ m!^([^/]+)/(.+)$!;
631                  my ($source, $target, $clause) = ($self->ComputeObjectSentence($1),          my ($sourceRelation, $targetRelation) = ($1, $2);
632                                                                                    $self->ComputeObjectSentence($2),          Trace("Join with key $joinKey is from $sourceRelation to $targetRelation.") if T(Joins => 4);
633                                                                                    $joinTable->{$joinKey});          my $source = $self->ComputeObjectSentence($sourceRelation);
634            my $target = $self->ComputeObjectSentence($targetRelation);
635            my $clause = $joinTable->{$joinKey};
636                  # Display them in a table row.                  # Display them in a table row.
637                  print HTMLOUT "<tr><td>$source</td><td>$target</td><td>$clause</td></tr>\n";          $retVal .= "<tr><td>$source</td><td>$target</td><td>$clause</td></tr>\n";
638          }          }
639          # Close the table.          # Close the table.
640          print HTMLOUT _CloseTable();      $retVal .= _CloseTable();
641          # Close the document.      Trace("Built MetaData HTML.") if T(3);
642          print HTMLOUT "</body>\n</html>\n";      # Return the HTML.
643          # Close the file.      return $retVal;
         close HTMLOUT;  
         Trace("Built MetaData web page.") if T(3);  
644  }  }
645    
646  =head3 DumpMetaData  =head3 DumpMetaData
647    
648  C<< $database->DumpMetaData(); >>      $erdb->DumpMetaData();
649    
650  Return a dump of the metadata structure.  Return a dump of the metadata structure.
651    
# Line 311  Line 658 
658          return Data::Dumper::Dumper($self->{_metaData});          return Data::Dumper::Dumper($self->{_metaData});
659  }  }
660    
661    =head3 GenerateWikiData
662    
663        my @wikiLines = $erdb->GenerateWikiData();
664    
665    Build a description of the database for the wiki. The database will be
666    organized into a single page, with sections for each entity and relationship.
667    The return value is a list of text lines.
668    
669    =cut
670    
671    sub GenerateWikiData {
672        # Get the parameters.
673        my ($self) = @_;
674        # We'll build the wiki text in here.
675        my @retVal = ();
676        # Get the metadata object.
677        my $metadata = $self->{_metaData};
678        # Get the title string. This will become the page name.
679        my $title = $metadata->{Title}->{content};
680        # Get the entity and relationship lists.
681        my $entityList = $metadata->{Entities};
682        my $relationshipList = $metadata->{Relationships};
683        # Start with the introductory text.
684        push @retVal, WikiTools::Heading(2, "Introduction");
685        if (my $notes = $metadata->{Notes}) {
686            push @retVal, WikiNote($notes->{content});
687        }
688        # Start the entity section.
689        push @retVal, WikiTools::Heading(2, "Entities");
690        # Loop through the entities. Note that unlike the situation with HTML, we
691        # don't need to generate the table of contents manually, just the data
692        # itself.
693        for my $key (sort keys %$entityList) {
694            # Create a header for this entity.
695            push @retVal, "", WikiTools::Heading(3, $key);
696            # Get the entity data.
697            my $entityData = $entityList->{$key};
698            # Plant the notes here, if there are any.
699            if (my $notes = $entityData->{Notes}) {
700                push @retVal, "", WikiNote($notes->{content});
701            }
702            # Get the entity's relations.
703            my $relationList = $entityData->{Relations};
704            # Loop through the relations, displaying them.
705            for my $relation (sort keys %{$relationList}) {
706                my $wikiString = _WikiRelationTable($relation, $relationList->{$relation});
707                push @retVal, $wikiString;
708            }
709            # Now we list the entity's relationships (if any). First, we build a list
710            # of the relationships relevant to this entity.
711            my @rels = ();
712            for my $rel (sort keys %$relationshipList) {
713                my $relStructure = $relationshipList->{$rel};
714                if ($relStructure->{from} eq $key || $relStructure->{to} eq $key) {
715                    # Get the relationship sentence.
716                    my $relSentence = _ComputeRelationshipSentence($rel, $relStructure);
717                    # Linkify it.
718                    my $linkedRel = WikiTools::LinkMarkup("#$rel", $rel);
719                    $relSentence =~ s/$rel/$linkedRel/;
720                    push @rels, $relSentence;
721                }
722            }
723            # Add the relationships as a Wiki list.
724            push @retVal, WikiTools::List(@rels);
725        }
726        # Now the entities are documented. Next we do the relationships.
727        push @retVal, WikiTools::Heading(2, "Relationships");
728        for my $key (sort keys %$relationshipList) {
729            my $relationshipData = $relationshipList->{$key};
730            # Create the relationship heading.
731            push @retVal, WikiTools::Heading(3, $key);
732            # Describe the relationship arity. Note there's a bit of trickiness involving recursive
733            # many-to-many relationships. In a normal many-to-many we use two sentences to describe
734            # the arity (one for each direction). This is a bad idea for a recursive relationship,
735            # since both sentences will say the same thing.
736            my $arity = $relationshipData->{arity};
737            my $fromEntity = $relationshipData->{from};
738            my $toEntity = $relationshipData->{to};
739            my @listElements = ();
740            my $boldCode = WikiTools::BoldCode();
741            if ($arity eq "11") {
742                push @listElements, "Each $boldCode$fromEntity$boldCode relates to at most one $boldCode$toEntity$boldCode.";
743            } else {
744                push @listElements, "Each $boldCode$fromEntity$boldCode relates to multiple $boldCode${toEntity}s$boldCode.\n";
745                if ($arity eq "MM" && $fromEntity ne $toEntity) {
746                    push @listElements, "Each $boldCode$toEntity$boldCode relates to multiple $boldCode${fromEntity}s$boldCode.\n";
747                }
748            }
749            push @retVal, WikiTools::List(@listElements);
750            # Plant the notes here, if there are any.
751            if (my $notes = $relationshipData->{Notes}) {
752                push @retVal, "", WikiNote($notes->{content});
753            }
754            # Finally, the relationship table.
755            my $wikiString = _WikiRelationTable($key, $relationshipData->{Relations}->{$key});
756            push @retVal, $wikiString;
757        }
758        # All done. Return the lines.
759        return @retVal;
760    }
761    
762    
763    =head3 CreatePPO
764    
765        ERDB::CreatePPO($erdbXMLFile, $ppoXMLFile);
766    
767    Create a PPO XML file from an ERDB data definition XML file. At the
768    current time, the PPO XML file can be used to create a database with
769    similar functionality. Eventually, the PPO will be able to use the
770    created XML to access the live ERDB database.
771    
772    =over 4
773    
774    =item erdbXMLFile
775    
776    Name of the XML data definition file for the ERDB database. This
777    file must exist.
778    
779    =item ppoXMLFile
780    
781    Output file for the PPO XML definition. If this file exists, it
782    will be overwritten.
783    
784    =back
785    
786    =cut
787    
788    sub CreatePPO {
789        # Get the parameters.
790        my ($erdbXMLFile, $ppoXMLFile) = @_;
791        # First, we want to slurp in the ERDB XML file in its raw form.
792        my $xml = ReadMetaXML($erdbXMLFile);
793        # Create a variable to hold all of the objects in the PPO project.
794        my @objects = ();
795        # Get the relationship hash.
796        my $relationships = $xml->{Relationships};
797        # Loop through the entities.
798        my $entities = $xml->{Entities};
799        for my $entityName (keys %{$entities}) {
800            # Get the entity's data structures.
801            my $entityObject = $entities->{$entityName};
802            # We put the object's fields in here, according to their type.
803            my (@object_refs, @scalars, @indexes, @arrays);
804            # Create the ID field for the entity. We get the key type from the
805            # entity object and compute the corresponding SQL type.
806            my $type = $TypeTable{$entityObject->{keyType}}->{sqlType};
807            push @scalars, { label => 'id', type => $type };
808            # Loop through the entity fields.
809            for my $fieldName ( keys %{$entityObject->{Fields}} ) {
810                # Get the field object.
811                my $fieldObject = $entityObject->{Fields}->{$fieldName};
812                # Convert it to a scalar tag.
813                my $scalar = _CreatePPOField($fieldName, $fieldObject);
814                # If we have a relation, this field is stored in an array.
815                # otherwise, it is a scalar. The array tag has scalars
816                # stored as an XML array. In ERDB, there is only ever one,
817                # but PPO can have more.
818                my $relation = $fieldObject->{relation};
819                if ($relation) {
820                    push @arrays, { scalar => [$scalar] };
821                } else {
822                    push @scalars, $scalar;
823                }
824            }
825            # Loop through the relationships. If this entity is the to-entity
826            # on a relationship of 1M arity, then it is implemented as a PPO
827            # object reference.
828            for my $relationshipName (keys %{$relationships}) {
829                # Get the relationship data.
830                my $relationshipData = $relationships->{$relationshipName};
831                # If we have a from for this entity and an arity of 1M, we
832                # have an object reference.
833                if ($relationshipData->{to} eq $entityName &&
834                    $relationshipData->{arity} eq '1M') {
835                    # Build the object reference tag.
836                    push @object_refs, { label => $relationshipName,
837                                         type => $relationshipData->{from} };
838                }
839            }
840            # Create the indexes.
841            my $indexList = $entityObject->{Indexes};
842            push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
843            # Build the object XML tree.
844            my $object = { label => $entityName,
845                           object_ref => \@object_refs,
846                           scalar => \@scalars,
847                           index => \@indexes,
848                           array => \@arrays
849                          };
850            # Push the object onto the objects list.
851            push @objects, $object;
852        }
853        # Loop through the relationships, searching for MMs. The 1Ms were
854        # already handled by the entity search above.
855        for my $relationshipName (keys %{$relationships}) {
856            # Get this relationship's object.
857            my $relationshipObject = $relationships->{$relationshipName};
858            # Only proceed if it's many-to-many.
859            if ($relationshipObject->{arity} eq 'MM') {
860                # Create the tag lists for the relationship object.
861                my (@object_refs, @scalars, @indexes);
862                # The relationship will be created as an object with object
863                # references for its links to the participating entities.
864                my %links = ( from_link => $relationshipObject->{from},
865                              to_link => $relationshipObject->{to} );
866                for my $link (keys %links) {
867                    # Create an object_ref tag for this piece of the
868                    # relationship (from or to).
869                    my $object_ref = { label => $link,
870                                       type => $links{$link} };
871                    push @object_refs, $object_ref;
872                }
873                # Loop through the intersection data fields, creating scalar tags.
874                # There are no fancy array tags in a relationship.
875                for my $fieldName (keys %{$relationshipObject->{Fields}}) {
876                    my $fieldObject = $relationshipObject->{Fields}->{$fieldName};
877                    push @scalars, _CreatePPOField($fieldName, $fieldObject);
878                }
879                # Finally, the indexes: currently we cannot support the to-index and
880                # from-index in PPO, so we just process the alternate indexes.
881                my $indexList = $relationshipObject->{Indexes};
882                push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
883                # Wrap up all the stuff about this relationship.
884                my $object = { label => $relationshipName,
885                               scalar => \@scalars,
886                               object_ref => \@object_refs,
887                               index => \@indexes
888                             };
889                # Push it into the object list.
890                push @objects, $object;
891            }
892        }
893        # Compute a title.
894        my $title;
895        if ($erdbXMLFile =~ /(\/|^)([^\/]+)DBD\.xml/) {
896            # Here we have a standard file name we can use for a title.
897            $title = $2;
898        } else {
899            # Here the file name is non-standard, so we carve up the
900            # database title.
901            $title = $xml->{Title}->{content};
902            $title =~ s/\s\.,//g;
903        }
904        # Wrap up the XML as a project.
905        my $ppoXML = { project => { label => $title,
906                                    object => \@objects }};
907        # Write out the results.
908        my $ppoString = XML::Simple::XMLout($ppoXML,
909                                            AttrIndent => 1,
910                                            KeepRoot => 1);
911        Tracer::PutFile($ppoXMLFile, [ $ppoString ]);
912    }
913    
914    =head3 FindIndexForEntity
915    
916        my $indexFound = ERDB::FindIndexForEntity($xml, $entityName, $attributeName);
917    
918    This method locates the entry in an entity's index list that begins with the
919    specified attribute name. If the entity has no index list, one will be
920    created. This method works on raw XML, not a live ERDB object.
921    
922    =over 4
923    
924    =item xml
925    
926    The raw XML structure defining the database.
927    
928    =item entityName
929    
930    The name of the relevant entity.
931    
932    =item attributeName
933    
934    The name of the attribute relevant to the search.
935    
936    =item RETURN
937    
938    The numerical index in the index list of the index entry for the specified entity and
939    attribute, or C<undef> if no such index exists.
940    
941    =back
942    
943    =cut
944    
945    sub FindIndexForEntity {
946        # Get the parameters.
947        my ($xml, $entityName, $attributeName) = @_;
948        # Declare the return variable.
949        my $retVal;
950        # Get the named entity.
951        my $entityData = $xml->{Entities}->{$entityName};
952        if (! $entityData) {
953            Confess("Entity $entityName not found in DBD structure.");
954        } else {
955            # Insure it has an index list.
956            if (! exists $entityData->{Indexes}) {
957                $entityData->{Indexes} = [];
958            } else {
959                # Search for the desired index.
960                my $indexList = $entityData->{Indexes};
961                my $n = scalar @{$indexList};
962                Trace("Searching $n indexes in index list for $entityName.") if T(2);
963                # We use an indexed FOR here because we're returning an
964                # index number instead of an object. We do THAT so we can
965                # delete the index from the list if needed.
966                for (my $i = 0; $i < $n && !defined($retVal); $i++) {
967                    my $index = $indexList->[$i];
968                    my $fields = $index->{IndexFields};
969                    # Technically this IF should be safe (that is, we are guaranteed
970                    # the existence of a "$fields->[0]"), because when we load the XML
971                    # we have SuppressEmpty specified.
972                    if ($fields->[0]->{name} eq $attributeName) {
973                        $retVal = $i;
974                    }
975                }
976            }
977        }
978        Trace("Index for $attributeName of $entityName found at position $retVal.") if defined($retVal) && T(3);
979        Trace("Index for $attributeName not found in $entityName.") if !defined($retVal) && T(3);
980        # Return the result.
981        return $retVal;
982    }
983    
984  =head3 CreateTables  =head3 CreateTables
985    
986  C<< $datanase->CreateTables(); >>      $erdb->CreateTables();
987    
988  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
989  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 325  Line 995 
995  sub CreateTables {  sub CreateTables {
996          # Get the parameters.          # Get the parameters.
997          my ($self) = @_;          my ($self) = @_;
998          my $metadata = $self->{_metaData};      # Get the relation names.
999          my $dbh = $self->{_dbh};      my @relNames = $self->GetTableNames();
1000          # Loop through the entities.      # Loop through the relations.
1001          while (my ($entityName, $entityData) = each %{$metadata->{Entities}}) {      for my $relationName (@relNames) {
                 # Tell the user what we're doing.  
                 Trace("Creating relations for entity $entityName.") if T(1);  
                 # Loop through the entity's relations.  
                 for my $relationName (keys %{$entityData->{Relations}}) {  
1002                          # Create a table for this relation.                          # Create a table for this relation.
1003                          $self->CreateTable($relationName);          $self->CreateTable($relationName, 1);
1004                          Trace("Relation $relationName created.") if T(1);          Trace("Relation $relationName created.") if T(2);
                 }  
         }  
         # Loop through the relationships.  
         my $relationshipTable = $metadata->{Relationships};  
         for my $relationshipName (keys %{$metadata->{Relationships}}) {  
                 # Create a table for this relationship.  
                 Trace("Creating relationship $relationshipName.") if T(1);  
                 $self->CreateTable($relationshipName);  
1005          }          }
1006  }  }
1007    
1008  =head3 CreateTable  =head3 CreateTable
1009    
1010  C<< $database->CreateTable($tableName, $indexFlag); >>      $erdb->CreateTable($tableName, $indexFlag, $estimatedRows);
1011    
1012  Create the table for a relation and optionally create its indexes.  Create the table for a relation and optionally create its indexes.
1013    
# Line 359  Line 1017 
1017    
1018  Name of the relation (which will also be the table name).  Name of the relation (which will also be the table name).
1019    
1020  =item $indexFlag  =item indexFlag
1021    
1022  TRUE if the indexes for the relation should be created, else FALSE. If FALSE,  TRUE if the indexes for the relation should be created, else FALSE. If FALSE,
1023  L</CreateIndexes> must be called later to bring the indexes into existence.  L</CreateIndexes> must be called later to bring the indexes into existence.
1024    
1025    =item estimatedRows (optional)
1026    
1027    If specified, the estimated maximum number of rows for the relation. This
1028    information allows the creation of tables using storage engines that are
1029    faster but require size estimates, such as MyISAM.
1030    
1031  =back  =back
1032    
1033  =cut  =cut
1034    
1035  sub CreateTable {  sub CreateTable {
1036          # Get the parameters.          # Get the parameters.
1037          my ($self, $relationName, $indexFlag) = @_;      my ($self, $relationName, $indexFlag, $estimatedRows) = @_;
1038          # Get the database handle.          # Get the database handle.
1039          my $dbh = $self->{_dbh};          my $dbh = $self->{_dbh};
1040          # 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 394  Line 1058 
1058          # Insure the table is not already there.          # Insure the table is not already there.
1059          $dbh->drop_table(tbl => $relationName);          $dbh->drop_table(tbl => $relationName);
1060          Trace("Table $relationName dropped.") if T(2);          Trace("Table $relationName dropped.") if T(2);
1061        # If there are estimated rows, create an estimate so we can take advantage of
1062        # faster DB technologies.
1063        my $estimation = undef;
1064        if ($estimatedRows) {
1065            $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];
1066            Trace("$estimation->[1] rows of $estimation->[0] bytes each.") if T(3);
1067        }
1068          # Create the table.          # Create the table.
1069          Trace("Creating table $relationName: $fieldThing") if T(2);          Trace("Creating table $relationName: $fieldThing") if T(2);
1070          $dbh->create_table(tbl => $relationName, flds => $fieldThing);      $dbh->create_table(tbl => $relationName, flds => $fieldThing, estimates => $estimation);
1071          Trace("Relation $relationName created in database.") if T(2);          Trace("Relation $relationName created in database.") if T(2);
1072          # If we want to build the indexes, we do it here.      # If we want to build the indexes, we do it here. Note that the full-text search
1073        # index will not be built until the table has been loaded.
1074          if ($indexFlag) {          if ($indexFlag) {
1075                  $self->CreateIndex($relationName);                  $self->CreateIndex($relationName);
1076          }          }
1077  }  }
1078    
1079  =head3 CreateIndex  =head3 VerifyFields
1080    
1081  C<< $database->CreateIndex($relationName); >>      my $count = $erdb->VerifyFields($relName, \@fieldList);
1082    
1083  Create the indexes for a relation. If a table is being loaded from a large source file (as  Run through the list of proposed field values, insuring that all the character fields are
1084  is the case in L</LoadTable>), it is best to create the indexes after the load. If that is  below the maximum length. If any fields are too long, they will be truncated in place.
1085  the case, then L</CreateTable> should be called with the index flag set to FALSE, and this  
1086  method used after the load to create the indexes for the table.  =over 4
1087    
1088    =item relName
1089    
1090    Name of the relation for which the specified fields are destined.
1091    
1092    =item fieldList
1093    
1094    Reference to a list, in order, of the fields to be put into the relation.
1095    
1096    =item RETURN
1097    
1098    Returns the number of fields truncated.
1099    
1100    =back
1101    
1102    =cut
1103    
1104    sub VerifyFields {
1105        # Get the parameters.
1106        my ($self, $relName, $fieldList) = @_;
1107        # Initialize the return value.
1108        my $retVal = 0;
1109        # Get the relation definition.
1110        my $relData = $self->_FindRelation($relName);
1111        # Get the list of field descriptors.
1112        my $fieldTypes = $relData->{Fields};
1113        my $fieldCount = scalar @{$fieldTypes};
1114        # Loop through the two lists.
1115        for (my $i = 0; $i < $fieldCount; $i++) {
1116            # Get the type of the current field.
1117            my $fieldType = $fieldTypes->[$i]->{type};
1118            # If it's a character field, verify the length.
1119            if ($fieldType =~ /string/) {
1120                my $maxLen = $TypeTable{$fieldType}->{maxLen};
1121                my $oldString = $fieldList->[$i];
1122                if (length($oldString) > $maxLen) {
1123                    # Here it's too big, so we truncate it.
1124                    Trace("Truncating field $i ($fieldTypes->[$i]->{name}) in relation $relName to $maxLen characters from \"$oldString\".") if T(1);
1125                    $fieldList->[$i] = substr $oldString, 0, $maxLen;
1126                    $retVal++;
1127                }
1128            }
1129        }
1130        # Return the truncation count.
1131        return $retVal;
1132    }
1133    
1134    =head3 DigestFields
1135    
1136        $erdb->DigestFields($relName, $fieldList);
1137    
1138    Digest the strings in the field list that correspond to data type C<hash-string> in the
1139    specified relation.
1140    
1141    =over 4
1142    
1143    =item relName
1144    
1145    Name of the relation to which the fields belong.
1146    
1147    =item fieldList
1148    
1149    List of field contents to be loaded into the relation.
1150    
1151    =back
1152    
1153    =cut
1154    #: Return Type ;
1155    sub DigestFields {
1156        # Get the parameters.
1157        my ($self, $relName, $fieldList) = @_;
1158        # Get the relation definition.
1159        my $relData = $self->_FindRelation($relName);
1160        # Get the list of field descriptors.
1161        my $fieldTypes = $relData->{Fields};
1162        my $fieldCount = scalar @{$fieldTypes};
1163        # Loop through the two lists.
1164        for (my $i = 0; $i < $fieldCount; $i++) {
1165            # Get the type of the current field.
1166            my $fieldType = $fieldTypes->[$i]->{type};
1167            # If it's a hash string, digest it in place.
1168            if ($fieldType eq 'hash-string') {
1169                $fieldList->[$i] = $self->DigestKey($fieldList->[$i]);
1170            }
1171        }
1172    }
1173    
1174    =head3 DigestKey
1175    
1176        my $digested = $erdb->DigestKey($keyValue);
1177    
1178    Return the digested value of a symbolic key. The digested value can then be plugged into a
1179    key-based search into a table with key-type hash-string.
1180    
1181    Currently the digesting process is independent of the database structure, but that may not
1182    always be the case, so this is an instance method instead of a static method.
1183    
1184    =over 4
1185    
1186    =item keyValue
1187    
1188    Key value to digest.
1189    
1190    =item RETURN
1191    
1192    Digested value of the key.
1193    
1194    =back
1195    
1196    =cut
1197    
1198    sub DigestKey {
1199        # Get the parameters.
1200        my ($self, $keyValue) = @_;
1201        # Compute the digest.
1202        my $retVal = md5_base64($keyValue);
1203        # Return the result.
1204        return $retVal;
1205    }
1206    
1207    =head3 CreateIndex
1208    
1209        $erdb->CreateIndex($relationName);
1210    
1211    Create the indexes for a relation. If a table is being loaded from a large source file (as
1212    is the case in L</LoadTable>), it is sometimes best to create the indexes after the load.
1213    If that is the case, then L</CreateTable> should be called with the index flag set to
1214    FALSE, and this method used after the load to create the indexes for the table.
1215    
1216  =cut  =cut
1217    
# Line 423  Line 1223 
1223          # Get the database handle.          # Get the database handle.
1224          my $dbh = $self->{_dbh};          my $dbh = $self->{_dbh};
1225          # 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.
1226          while (my ($indexName, $indexData) = each %{$relationData->{Indexes}}) {      my $indexHash = $relationData->{Indexes};
1227        for my $indexName (keys %{$indexHash}) {
1228            my $indexData = $indexHash->{$indexName};
1229                  # Get the index's field list.                  # Get the index's field list.
1230                  my @fieldList = _FixNames(@{$indexData->{IndexFields}});          my @rawFields = @{$indexData->{IndexFields}};
1231            # Get a hash of the relation's field types.
1232            my %types = map { $_->{name} => $_->{type} } @{$relationData->{Fields}};
1233            # We need to check for text fields so we can append a length limitation for them. To do
1234            # that, we need the relation's field list.
1235            my $relFields = $relationData->{Fields};
1236            for (my $i = 0; $i <= $#rawFields; $i++) {
1237                # Get the field type.
1238                my $field = $rawFields[$i];
1239                my $type = $types{$field};
1240                # Ask if it requires using prefix notation for the index.
1241                my $mod = $TypeTable{$type}->{indexMod};
1242                Trace("Field $field ($i) in $relationName has type $type and indexMod $mod.") if T(3);
1243                if ($mod) {
1244                    # Append the prefix length to the field name,
1245                    $rawFields[$i] .= "($mod)";
1246                }
1247            }
1248            my @fieldList = _FixNames(@rawFields);
1249                  my $flds = join(', ', @fieldList);                  my $flds = join(', ', @fieldList);
1250                  # Get the index's uniqueness flag.                  # Get the index's uniqueness flag.
1251                  my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');          my $unique = (exists $indexData->{Unique} ? 'unique' : undef);
1252                  # Create the index.                  # Create the index.
1253                  $dbh->create_index(idx => $indexName, tbl => $relationName, flds => $flds, unique => $unique);          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,
1254                                        flds => $flds, kind => $unique);
1255            if ($rv) {
1256                  Trace("Index created: $indexName for $relationName ($flds)") if T(1);                  Trace("Index created: $indexName for $relationName ($flds)") if T(1);
1257            } else {
1258                Confess("Error creating index $indexName for $relationName using ($flds): " . $dbh->error_message());
1259            }
1260        }
1261    }
1262    
1263    =head3 GetSecondaryFields
1264    
1265        my %fieldTuples = $erdb->GetSecondaryFields($entityName);
1266    
1267    This method will return a list of the name and type of each of the secondary
1268    fields for a specified entity. Secondary fields are stored in two-column tables
1269    in addition to the primary entity table. This enables the field to have no value
1270    or to have multiple values.
1271    
1272    =over 4
1273    
1274    =item entityName
1275    
1276    Name of the entity whose secondary fields are desired.
1277    
1278    =item RETURN
1279    
1280    Returns a hash mapping the field names to their field types.
1281    
1282    =back
1283    
1284    =cut
1285    
1286    sub GetSecondaryFields {
1287        # Get the parameters.
1288        my ($self, $entityName) = @_;
1289        # Declare the return variable.
1290        my %retVal = ();
1291        # Look for the entity.
1292        my $table = $self->GetFieldTable($entityName);
1293        # Loop through the fields, pulling out the secondaries.
1294        for my $field (sort keys %{$table}) {
1295            if ($table->{$field}->{relation} ne $entityName) {
1296                # Here we have a secondary field.
1297                $retVal{$field} = $table->{$field}->{type};
1298            }
1299        }
1300        # Return the result.
1301        return %retVal;
1302    }
1303    
1304    =head3 GetFieldRelationName
1305    
1306        my $name = $erdb->GetFieldRelationName($objectName, $fieldName);
1307    
1308    Return the name of the relation containing a specified field.
1309    
1310    =over 4
1311    
1312    =item objectName
1313    
1314    Name of the entity or relationship containing the field.
1315    
1316    =item fieldName
1317    
1318    Name of the relevant field in that entity or relationship.
1319    
1320    =item RETURN
1321    
1322    Returns the name of the database relation containing the field, or C<undef> if
1323    the field does not exist.
1324    
1325    =back
1326    
1327    =cut
1328    
1329    sub GetFieldRelationName {
1330        # Get the parameters.
1331        my ($self, $objectName, $fieldName) = @_;
1332        # Declare the return variable.
1333        my $retVal;
1334        # Get the object field table.
1335        my $table = $self->GetFieldTable($objectName);
1336        # Only proceed if the field exists.
1337        if (exists $table->{$fieldName}) {
1338            # Determine the name of the relation that contains this field.
1339            $retVal = $table->{$fieldName}->{relation};
1340        }
1341        # Return the result.
1342        return $retVal;
1343    }
1344    
1345    =head3 DeleteValue
1346    
1347        my $numDeleted = $erdb->DeleteValue($entityName, $id, $fieldName, $fieldValue);
1348    
1349    Delete secondary field values from the database. This method can be used to delete all
1350    values of a specified field for a particular entity instance, or only a single value.
1351    
1352    Secondary fields are stored in two-column relations separate from an entity's primary
1353    table, and as a result a secondary field can legitimately have no value or multiple
1354    values. Therefore, it makes sense to talk about deleting secondary fields where it
1355    would not make sense for primary fields.
1356    
1357    =over 4
1358    
1359    =item entityName
1360    
1361    Name of the entity from which the fields are to be deleted.
1362    
1363    =item id
1364    
1365    ID of the entity instance to be processed. If the instance is not found, this
1366    method will have no effect. If C<undef> is specified, all values for all of
1367    the entity instances will be deleted.
1368    
1369    =item fieldName
1370    
1371    Name of the field whose values are to be deleted.
1372    
1373    =item fieldValue (optional)
1374    
1375    Value to be deleted. If not specified, then all values of the specified field
1376    will be deleted for the entity instance. If specified, then only the values which
1377    match this parameter will be deleted.
1378    
1379    =item RETURN
1380    
1381    Returns the number of rows deleted.
1382    
1383    =back
1384    
1385    =cut
1386    
1387    sub DeleteValue {
1388        # Get the parameters.
1389        my ($self, $entityName, $id, $fieldName, $fieldValue) = @_;
1390        # Declare the return value.
1391        my $retVal = 0;
1392        # We need to set up an SQL command to do the deletion. First, we
1393        # find the name of the field's relation.
1394        my $table = $self->GetFieldTable($entityName);
1395        my $field = $table->{$fieldName};
1396        my $relation = $field->{relation};
1397        # Make sure this is a secondary field.
1398        if ($relation eq $entityName) {
1399            Confess("Cannot delete values of $fieldName for $entityName.");
1400        } else {
1401            # Set up the SQL command to delete all values.
1402            my $sql = "DELETE FROM $relation";
1403            # Build the filter.
1404            my @filters = ();
1405            my @parms = ();
1406            # Check for a filter by ID.
1407            if (defined $id) {
1408                push @filters, "id = ?";
1409                push @parms, $id;
1410            }
1411            # Check for a filter by value.
1412            if (defined $fieldValue) {
1413                push @filters, "$fieldName = ?";
1414                push @parms, $fieldValue;
1415            }
1416            # Append the filters to the command.
1417            if (@filters) {
1418                $sql .= " WHERE " . join(" AND ", @filters);
1419            }
1420            # Execute the command.
1421            my $dbh = $self->{_dbh};
1422            $retVal = $dbh->SQL($sql, 0, @parms);
1423          }          }
1424        # Return the result.
1425        return $retVal;
1426  }  }
1427    
1428  =head3 LoadTables  =head3 LoadTables
1429    
1430  C<< my $stats = $database->LoadTables($directoryName, $rebuild); >>      my $stats = $erdb->LoadTables($directoryName, $rebuild);
1431    
1432  This method will load the database tables from a directory. The tables must already have been created  This method will load the database tables from a directory. The tables must already have been created
1433  in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name;  in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name;
# Line 480  Line 1470 
1470          $directoryName =~ s!/\\$!!;          $directoryName =~ s!/\\$!!;
1471          # Declare the return variable.          # Declare the return variable.
1472          my $retVal = Stats->new();          my $retVal = Stats->new();
1473          # Get the metadata structure.      # Get the relation names.
1474          my $metaData = $self->{_metaData};      my @relNames = $self->GetTableNames();
1475          # Loop through the entities.      for my $relationName (@relNames) {
         for my $entity (values %{$metaData->{Entities}}) {  
                 # Loop through the entity's relations.  
                 for my $relationName (keys %{$entity->{Relations}}) {  
1476                          # Try to load this relation.                          # Try to load this relation.
1477                          my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);                          my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);
1478                          # Accumulate the statistics.                          # Accumulate the statistics.
1479                          $retVal->Accumulate($result);                          $retVal->Accumulate($result);
1480                  }                  }
         }  
         # Loop through the relationships.  
         for my $relationshipName (keys %{$metaData->{Relationships}}) {  
                 # Try to load this relationship's relation.  
                 my $result = $self->_LoadRelation($directoryName, $relationshipName, $rebuild);  
                 # Accumulate the statistics.  
                 $retVal->Accumulate($result);  
         }  
1481          # Add the duration of the load to the statistical object.          # Add the duration of the load to the statistical object.
1482          $retVal->Add('duration', gettimeofday - $startTime);          $retVal->Add('duration', gettimeofday - $startTime);
1483          # Return the accumulated statistics.          # Return the accumulated statistics.
1484          return $retVal;          return $retVal;
1485  }  }
1486    
1487    
1488  =head3 GetTableNames  =head3 GetTableNames
1489    
1490  C<< my @names = $database->GetTableNames; >>      my @names = $erdb->GetTableNames;
1491    
1492  Return a list of the relations required to implement this database.  Return a list of the relations required to implement this database.
1493    
# Line 524  Line 1504 
1504    
1505  =head3 GetEntityTypes  =head3 GetEntityTypes
1506    
1507  C<< my @names = $database->GetEntityTypes; >>      my @names = $erdb->GetEntityTypes;
1508    
1509  Return a list of the entity type names.  Return a list of the entity type names.
1510    
# Line 539  Line 1519 
1519          return sort keys %{$entityList};          return sort keys %{$entityList};
1520  }  }
1521    
1522    =head3 GetDataTypes
1523    
1524        my %types = ERDB::GetDataTypes();
1525    
1526    Return a table of ERDB data types. The table returned is a hash of hashes.
1527    The keys of the big hash are the datatypes. Each smaller hash has several
1528    values used to manage the data. The most interesting is the SQL type (key
1529    C<sqlType>) and the descriptive node (key C<notes>).
1530    
1531    Note that changing the values in the smaller hashes will seriously break
1532    things, so this data should be treated as read-only.
1533    
1534    =cut
1535    
1536    sub GetDataTypes {
1537        return %TypeTable;
1538    }
1539    
1540    
1541    =head3 IsEntity
1542    
1543        my $flag = $erdb->IsEntity($entityName);
1544    
1545    Return TRUE if the parameter is an entity name, else FALSE.
1546    
1547    =over 4
1548    
1549    =item entityName
1550    
1551    Object name to be tested.
1552    
1553    =item RETURN
1554    
1555    Returns TRUE if the specified string is an entity name, else FALSE.
1556    
1557    =back
1558    
1559    =cut
1560    
1561    sub IsEntity {
1562        # Get the parameters.
1563        my ($self, $entityName) = @_;
1564        # Test to see if it's an entity.
1565        return exists $self->{_metaData}->{Entities}->{$entityName};
1566    }
1567    
1568  =head3 Get  =head3 Get
1569    
1570  C<< my $query = $database->Get(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>      my $query = $erdb->Get(\@objectNames, $filterClause, \@params);
1571    
1572  This method returns a query object for entities of a specified type using a specified filter.  This method returns a query object for entities of a specified type using a specified filter.
1573  The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each  The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each
# Line 549  Line 1575 
1575  following call requests all B<Genome> objects for the genus specified in the variable  following call requests all B<Genome> objects for the genus specified in the variable
1576  $genus.  $genus.
1577    
1578  C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", $genus); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]);
1579    
1580  The WHERE clause contains a single question mark, so there is a single additional  The WHERE clause contains a single question mark, so there is a single additional
1581  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
1582    
1583  C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'");
1584    
1585  however, this version of the call would generate a syntax error if there were any quote  however, this version of the call would generate a syntax error if there were any quote
1586  characters inside the variable C<$genus>.  characters inside the variable C<$genus>.
# Line 566  Line 1592 
1592  It is possible to specify multiple entity and relationship names in order to retrieve more than  It is possible to specify multiple entity and relationship names in order to retrieve more than
1593  one object's data at the same time, which allows highly complex joined queries. For example,  one object's data at the same time, which allows highly complex joined queries. For example,
1594    
1595  C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", $genus); >>      $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]);
1596    
1597  If multiple names are specified, then the query processor will automatically determine a  If multiple names are specified, then the query processor will automatically determine a
1598  join path between the entities and relationships. The algorithm used is very simplistic.  join path between the entities and relationships. The algorithm used is very simplistic.
1599  In particular, you can't specify any entity or relationship more than once, and if a  In particular, if a relationship is recursive, the path is determined by the order in which
1600  relationship is recursive, the path is determined by the order in which the entity  the entity and the relationship appear. For example, consider a recursive relationship
1601  and the relationship appear. For example, consider a recursive relationship B<IsParentOf>  B<IsParentOf> which relates B<People> objects to other B<People> objects. If the join path is
 which relates B<People> objects to other B<People> objects. If the join path is  
1602  coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however,  coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however,
1603  the join path is C<['IsParentOf', 'People']>, then the people returned will be children.  the join path is C<['IsParentOf', 'People']>, then the people returned will be children.
1604    
1605    If an entity or relationship is mentioned twice, the name for the second occurrence will
1606    be suffixed with C<2>, the third occurrence will be suffixed with C<3>, and so forth. So,
1607    for example, if we have C<['Feature', 'HasContig', 'Contig', 'HasContig']>, then the
1608    B<to-link> field of the first B<HasContig> is specified as C<HasContig(to-link)>, while
1609    the B<to-link> field of the second B<HasContig> is specified as C<HasContig2(to-link)>.
1610    
1611  =over 4  =over 4
1612    
1613  =item objectNames  =item objectNames
# Line 597  Line 1628 
1628  with an ORDER BY clause. For example, the following filter string gets all genomes for a  with an ORDER BY clause. For example, the following filter string gets all genomes for a
1629  particular genus and sorts them by species name.  particular genus and sorts them by species name.
1630    
1631  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
1632    
1633    Note that the case is important. Only an uppercase "ORDER BY" with a single space will
1634    be processed. The idea is to make it less likely to find the verb by accident.
1635    
1636  The rules for field references in a sort order are the same as those for field references in the  The rules for field references in a sort order are the same as those for field references in the
1637  filter clause in general; however, odd things may happen if a sort field is from a secondary  filter clause in general; however, odd things may happen if a sort field is from a secondary
1638  relation.  relation.
1639    
1640  =item param1, param2, ..., paramN  Finally, you can limit the number of rows returned by adding a LIMIT clause. The LIMIT must
1641    be the last thing in the filter clause, and it contains only the word "LIMIT" followed by
1642    a positive number. So, for example
1643    
1644        "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10"
1645    
1646  Parameter values to be substituted into the filter clause.  will only return the first ten genomes for the specified genus. The ORDER BY clause is not
1647    required. For example, to just get the first 10 genomes in the B<Genome> table, you could
1648    use
1649    
1650        "LIMIT 10"
1651    
1652    =item params
1653    
1654    Reference to a list of parameter values to be substituted into the filter clause.
1655    
1656  =item RETURN  =item RETURN
1657    
# Line 617  Line 1663 
1663    
1664  sub Get {  sub Get {
1665          # Get the parameters.          # Get the parameters.
1666          my ($self, $objectNames, $filterClause, @params) = @_;      my ($self, $objectNames, $filterClause, $params) = @_;
1667          # Construct the SELECT statement. The general pattern is      # Process the SQL stuff.
1668          #      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1669          # SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN          $self->_SetupSQL($objectNames, $filterClause);
1670          #      # Create the query.
1671          my $dbh = $self->{_dbh};      my $command = "SELECT " . join(".*, ", @{$mappedNameListRef}) .
1672          my $command = "SELECT DISTINCT " . join('.*, ', @{$objectNames}) . ".* FROM " .          ".* $suffix";
1673                                  join(', ', @{$objectNames});      my $sth = $self->_GetStatementHandle($command, $params);
1674          # Check for a filter clause.      # Now we create the relation map, which enables DBQuery to determine the order, name
1675          if ($filterClause) {      # and mapped name for each object in the query.
1676                  # Here we have one, so we convert its field names and add it to the query. First,      my @relationMap = ();
1677                  # We create a copy of the filter string we can work with.      for my $mappedName (@{$mappedNameListRef}) {
1678                  my $filterString = $filterClause;          push @relationMap, [$mappedName, $mappedNameHashRef->{$mappedName}];
                 # Next, we sort the object names by length. This helps protect us from finding  
                 # object names inside other object names when we're doing our search and replace.  
                 my @sortedNames = sort { length($b) - length($a) } @{$objectNames};  
                 # We will also keep a list of conditions to add to the WHERE clause in order to link  
                 # entities and relationships as well as primary relations to secondary ones.  
                 my @joinWhere = ();  
                 # The final preparatory step is to create a hash table of relation names. The  
                 # table begins with the relation names already in the SELECT command.  
                 my %fromNames = ();  
                 for my $objectName (@sortedNames) {  
                         $fromNames{$objectName} = 1;  
                 }  
                 # We are ready to begin. We loop through the object names, replacing each  
                 # object name's field references by the corresponding SQL field reference.  
                 # Along the way, if we find a secondary relation, we will need to add it  
                 # to the FROM clause.  
                 for my $objectName (@sortedNames) {  
                         # Get the length of the object name plus 2. This is the value we add to the  
                         # size of the field name to determine the size of the field reference as a  
                         # whole.  
                         my $nameLength = 2 + length $objectName;  
                         # Get the object's field list.  
                         my $fieldList = $self->_GetFieldTable($objectName);  
                         # Find the field references for this object.  
                         while ($filterString =~ m/$objectName\(([^)]*)\)/g) {  
                                 # At this point, $1 contains the field name, and the current position  
                                 # is set immediately after the final parenthesis. We pull out the name of  
                                 # the field and the position and length of the field reference as a whole.  
                                 my $fieldName = $1;  
                                 my $len = $nameLength + length $fieldName;  
                                 my $pos = pos($filterString) - $len;  
                                 # Insure the field exists.  
                                 if (!exists $fieldList->{$fieldName}) {  
                                         Confess("Field $fieldName not found for object $objectName.");  
                                 } else {  
                                         # Get the field's relation.  
                                         my $relationName = $fieldList->{$fieldName}->{relation};  
                                         # Insure the relation is in the FROM clause.  
                                         if (!exists $fromNames{$relationName}) {  
                                                 # Add the relation to the FROM clause.  
                                                 $command .= ", $relationName";  
                                                 # Create its join sub-clause.  
                                                 push @joinWhere, "$objectName.id = $relationName.id";  
                                                 # Denote we have it available for future fields.  
                                                 $fromNames{$relationName} = 1;  
                                         }  
                                         # Form an SQL field reference from the relation name and the field name.  
                                         my $sqlReference = "$relationName." . _FixName($fieldName);  
                                         # Put it into the filter string in place of the old value.  
                                         substr($filterString, $pos, $len) = $sqlReference;  
                                         # Reposition the search.  
                                         pos $filterString = $pos + length $sqlReference;  
                                 }  
                         }  
                 }  
                 # The next step is to join the objects together. We only need to do this if there  
                 # is more than one object in the object list. We start with the first object and  
                 # run through the objects after it. Note also that we make a safety copy of the  
                 # list before running through it.  
                 my @objectList = @{$objectNames};  
                 my $lastObject = shift @objectList;  
                 # Get the join table.  
                 my $joinTable = $self->{_metaData}->{Joins};  
                 # Loop through the object list.  
                 for my $thisObject (@objectList) {  
                         # Look for a join.  
                         my $joinKey = "$lastObject/$thisObject";  
                         if (!exists $joinTable->{$joinKey}) {  
                                 # Here there's no join, so we throw an error.  
                                 Confess("No join exists to connect from $lastObject to $thisObject.");  
                         } else {  
                                 # Get the join clause and add it to the WHERE list.  
                                 push @joinWhere, $joinTable->{$joinKey};  
                                 # Save this object as the last object for the next iteration.  
                                 $lastObject = $thisObject;  
                         }  
                 }  
                 # Now we need to handle the whole ORDER BY thing. We'll put the order by clause  
                 # in the following variable.  
                 my $orderClause = "";  
                 # Locate the ORDER BY verb (if any).  
                 if ($filterString =~ m/^(.*)ORDER BY/g) {  
                         # Here we have an ORDER BY verb. Split it off of the filter string.  
                         my $pos = pos $filterString;  
                         $orderClause = substr($filterString, $pos);  
                         $filterString = $1;  
                 }  
                 # Add the filter and the join clauses (if any) to the SELECT command.  
                 if ($filterString) {  
                         push @joinWhere, "($filterString)";  
1679                  }                  }
1680                  if (@joinWhere) {      # Return the statement object.
1681                          $command .= " WHERE " . join(' AND ', @joinWhere);      my $retVal = DBQuery::_new($self, $sth, \@relationMap);
1682        return $retVal;
1683                  }                  }
1684                  # Add the sort clause (if any) to the SELECT command.  
1685                  if ($orderClause) {  
1686                          $command .= " ORDER BY $orderClause";  
1687    =head3 Search
1688    
1689        my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params);
1690    
1691    Perform a full text search with filtering. The search will be against a specified object
1692    in the object name list. That object will get an extra field containing the search
1693    relevance. Note that except for the search expression, the parameters of this method are
1694    the same as those for L</Get> and follow the same rules.
1695    
1696    =over 4
1697    
1698    =item searchExpression
1699    
1700    Boolean search expression for the text fields of the target object. The default mode for
1701    a Boolean search expression is OR, but we want the default to be AND, so we will
1702    add a C<+> operator to each word with no other operator before it.
1703    
1704    =item idx
1705    
1706    Index in the I<$objectNames> list of the table to be searched in full-text mode.
1707    
1708    =item objectNames
1709    
1710    List containing the names of the entity and relationship objects to be retrieved.
1711    
1712    =item filterClause
1713    
1714    WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1715    be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
1716    specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
1717    in the filter clause should be added to the parameter list as additional parameters. The
1718    fields in a filter clause can come from primary entity relations, relationship relations,
1719    or secondary entity relations; however, all of the entities and relationships involved must
1720    be included in the list of object names.
1721    
1722    =item params
1723    
1724    Reference to a list of parameter values to be substituted into the filter clause.
1725    
1726    =item RETURN
1727    
1728    Returns a query object for the specified search.
1729    
1730    =back
1731    
1732    =cut
1733    
1734    sub Search {
1735        # Get the parameters.
1736        my ($self, $searchExpression, $idx, $objectNames, $filterClause, $params) = @_;
1737        # Declare the return variable.
1738        my $retVal;
1739        # Create a safety copy of the parameter list. Note we have to be careful to insure
1740        # a parameter list exists before we copy it.
1741        my @myParams = ();
1742        if (defined $params) {
1743            @myParams = @{$params};
1744        }
1745        # Get the first object's structure so we have access to the searchable fields.
1746        my $object1Name = $objectNames->[$idx];
1747        my $object1Structure = $self->_GetStructure($object1Name);
1748        # Get the field list.
1749        if (! exists $object1Structure->{searchFields}) {
1750            Confess("No searchable index for $object1Name.");
1751        } else {
1752            # Get the field list.
1753            my @fields = @{$object1Structure->{searchFields}};
1754            # Clean the search expression.
1755            my $actualKeywords = $self->CleanKeywords($searchExpression);
1756            # Prefix a "+" to each uncontrolled word. This converts the default
1757            # search mode from OR to AND.
1758            $actualKeywords =~ s/(^|\s)(\w|")/$1\+$2/g;
1759            Trace("Actual keywords for search are\n$actualKeywords") if T(3);
1760            # We need two match expressions, one for the filter clause and one in the
1761            # query itself. Both will use a parameter mark, so we need to push the
1762            # search expression onto the front of the parameter list twice.
1763            unshift @myParams, $actualKeywords, $actualKeywords;
1764            # Build the match expression.
1765            my @matchFilterFields = map { "$object1Name." . _FixName($_) } @fields;
1766            my $matchClause = "MATCH (" . join(", ", @matchFilterFields) . ") AGAINST (? IN BOOLEAN MODE)";
1767            # Process the SQL stuff.
1768            my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1769                $self->_SetupSQL($objectNames, $filterClause, $matchClause);
1770            # Create the query. Note that the match clause is inserted at the front of
1771            # the select fields.
1772            my $command = "SELECT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .
1773                ".* $suffix";
1774            my $sth = $self->_GetStatementHandle($command, \@myParams);
1775            # Now we create the relation map, which enables DBQuery to determine the order, name
1776            # and mapped name for each object in the query.
1777            my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
1778            # Return the statement object.
1779            $retVal = DBQuery::_new($self, $sth, \@relationMap, $object1Name);
1780        }
1781        return $retVal;
1782    }
1783    
1784    =head3 GetFlat
1785    
1786        my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field);
1787    
1788    This is a variation of L</GetAll> that asks for only a single field per record and
1789    returns a single flattened list.
1790    
1791    =over 4
1792    
1793    =item objectNames
1794    
1795    List containing the names of the entity and relationship objects to be retrieved.
1796    
1797    =item filterClause
1798    
1799    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1800    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1801    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1802    parameter list as additional parameters. The fields in a filter clause can come from primary
1803    entity relations, relationship relations, or secondary entity relations; however, all of the
1804    entities and relationships involved must be included in the list of object names.
1805    
1806    =item parameterList
1807    
1808    List of the parameters to be substituted in for the parameters marks in the filter clause.
1809    
1810    =item field
1811    
1812    Name of the field to be used to get the elements of the list returned.
1813    
1814    =item RETURN
1815    
1816    Returns a list of values.
1817    
1818    =back
1819    
1820    =cut
1821    #: Return Type @;
1822    sub GetFlat {
1823        # Get the parameters.
1824        my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
1825        # Construct the query.
1826        my $query = $self->Get($objectNames, $filterClause, $parameterList);
1827        # Create the result list.
1828        my @retVal = ();
1829        # Loop through the records, adding the field values found to the result list.
1830        while (my $row = $query->Fetch()) {
1831            push @retVal, $row->Value($field);
1832        }
1833        # Return the list created.
1834        return @retVal;
1835    }
1836    
1837    =head3 SpecialFields
1838    
1839        my %specials = $erdb->SpecialFields($entityName);
1840    
1841    Return a hash mapping special fields in the specified entity to the value of their
1842    C<special> attribute. This enables the subclass to get access to the special field
1843    attributes without needed to plumb the internal ERDB data structures.
1844    
1845    =over 4
1846    
1847    =item entityName
1848    
1849    Name of the entity whose special fields are desired.
1850    
1851    =item RETURN
1852    
1853    Returns a hash. The keys of the hash are the special field names, and the values
1854    are the values from each special field's C<special> attribute.
1855    
1856    =back
1857    
1858    =cut
1859    
1860    sub SpecialFields {
1861        # Get the parameters.
1862        my ($self, $entityName) = @_;
1863        # Declare the return variable.
1864        my %retVal = ();
1865        # Find the entity's data structure.
1866        my $entityData = $self->{_metaData}->{Entities}->{$entityName};
1867        # Loop through its fields, adding each special field to the return hash.
1868        my $fieldHash = $entityData->{Fields};
1869        for my $fieldName (keys %{$fieldHash}) {
1870            my $fieldData = $fieldHash->{$fieldName};
1871            if (exists $fieldData->{special}) {
1872                $retVal{$fieldName} = $fieldData->{special};
1873            }
1874        }
1875        # Return the result.
1876        return %retVal;
1877    }
1878    
1879    =head3 Delete
1880    
1881        my $stats = $erdb->Delete($entityName, $objectID, %options);
1882    
1883    Delete an entity instance from the database. The instance is deleted along with all entity and
1884    relationship instances dependent on it. The definition of I<dependence> is recursive.
1885    
1886    An object is always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many
1887    relationship connected to a dependent entity or if it is the "to" entity connected to a 1-to-many
1888    dependent relationship.
1889    
1890    =over 4
1891    
1892    =item entityName
1893    
1894    Name of the entity type for the instance being deleted.
1895    
1896    =item objectID
1897    
1898    ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),
1899    then it is presumed to by a LIKE pattern.
1900    
1901    =item options
1902    
1903    A hash detailing the options for this delete operation.
1904    
1905    =item RETURN
1906    
1907    Returns a statistics object indicating how many records of each particular table were
1908    deleted.
1909    
1910    =back
1911    
1912    The permissible options for this method are as follows.
1913    
1914    =over 4
1915    
1916    =item testMode
1917    
1918    If TRUE, then the delete statements will be traced, but no changes will be made to the database.
1919    
1920    =item keepRoot
1921    
1922    If TRUE, then the entity instances will not be deleted, only the dependent records.
1923    
1924    =back
1925    
1926    =cut
1927    #: Return Type $%;
1928    sub Delete {
1929        # Get the parameters.
1930        my ($self, $entityName, $objectID, %options) = @_;
1931        # Declare the return variable.
1932        my $retVal = Stats->new();
1933        # Get the DBKernel object.
1934        my $db = $self->{_dbh};
1935        # We're going to generate all the paths branching out from the starting entity. One of
1936        # the things we have to be careful about is preventing loops. We'll use a hash to
1937        # determine if we've hit a loop.
1938        my %alreadyFound = ();
1939        # These next lists will serve as our result stack. We start by pushing object lists onto
1940        # the stack, and then popping them off to do the deletes. This means the deletes will
1941        # start with the longer paths before getting to the shorter ones. That, in turn, makes
1942        # sure we don't delete records that might be needed to forge relationships back to the
1943        # original item. We have two lists-- one for TO-relationships, and one for
1944        # FROM-relationships and entities.
1945        my @fromPathList = ();
1946        my @toPathList = ();
1947        # This final list is used to remember what work still needs to be done. We push paths
1948        # onto the list, then pop them off to extend the paths. We prime it with the starting
1949        # point. Note that we will work hard to insure that the last item on a path in the
1950        # to-do list is always an entity.
1951        my @todoList = ([$entityName]);
1952        while (@todoList) {
1953            # Get the current path.
1954            my $current = pop @todoList;
1955            # Copy it into a list.
1956            my @stackedPath = @{$current};
1957            # Pull off the last item on the path. It will always be an entity.
1958            my $myEntityName = pop @stackedPath;
1959            # Add it to the alreadyFound list.
1960            $alreadyFound{$myEntityName} = 1;
1961            # Figure out if we need to delete this entity.
1962            if ($myEntityName ne $entityName || ! $options{keepRoot}) {
1963                # Get the entity data.
1964                my $entityData = $self->_GetStructure($myEntityName);
1965                # Loop through the entity's relations. A DELETE command will be needed for each of them.
1966                my $relations = $entityData->{Relations};
1967                for my $relation (keys %{$relations}) {
1968                    my @augmentedList = (@stackedPath, $relation);
1969                    push @fromPathList, \@augmentedList;
1970                }
1971            }
1972            # Now we need to look for relationships connected to this entity.
1973            my $relationshipList = $self->{_metaData}->{Relationships};
1974            for my $relationshipName (keys %{$relationshipList}) {
1975                my $relationship = $relationshipList->{$relationshipName};
1976                # Check the FROM field. We're only interested if it's us.
1977                if ($relationship->{from} eq $myEntityName) {
1978                    # Add the path to this relationship.
1979                    my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
1980                    push @fromPathList, \@augmentedList;
1981                    # Check the arity. If it's MM we're done. If it's 1M
1982                    # and the target hasn't been seen yet, we want to
1983                    # stack the entity for future processing.
1984                    if ($relationship->{arity} eq '1M') {
1985                        my $toEntity = $relationship->{to};
1986                        if (! exists $alreadyFound{$toEntity}) {
1987                            # Here we have a new entity that's dependent on
1988                            # the current entity, so we need to stack it.
1989                            my @stackList = (@augmentedList, $toEntity);
1990                            push @fromPathList, \@stackList;
1991                        } else {
1992                            Trace("$toEntity ignored because it occurred previously.") if T(4);
1993                        }
1994                    }
1995                }
1996                # Now check the TO field. In this case only the relationship needs
1997                # deletion.
1998                if ($relationship->{to} eq $myEntityName) {
1999                    my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
2000                    push @toPathList, \@augmentedList;
2001                }
2002            }
2003        }
2004        # Create the first qualifier for the WHERE clause. This selects the
2005        # keys of the primary entity records to be deleted. When we're deleting
2006        # from a dependent table, we construct a join path from the first qualifier
2007        # to the table containing the dependent records to delete.
2008        my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");
2009        # We need to make two passes. The first is through the to-list, and
2010        # the second through the from-list. The from-list is second because
2011        # the to-list may need to pass through some of the entities the
2012        # from-list would delete.
2013        my %stackList = ( from_link => \@fromPathList, to_link => \@toPathList );
2014        # Now it's time to do the deletes. We do it in two passes.
2015        for my $keyName ('to_link', 'from_link') {
2016            # Get the list for this key.
2017            my @pathList = @{$stackList{$keyName}};
2018            Trace(scalar(@pathList) . " entries in path list for $keyName.") if T(3);
2019            # Loop through this list.
2020            while (my $path = pop @pathList) {
2021                # Get the table whose rows are to be deleted.
2022                my @pathTables = @{$path};
2023                # Start the DELETE statement. We need to call DBKernel because the
2024                # syntax of a DELETE-USING varies among DBMSs.
2025                my $target = $pathTables[$#pathTables];
2026                my $stmt = $db->SetUsing(@pathTables);
2027                # Now start the WHERE. The first thing is the ID field from the starting table. That
2028                # starting table will either be the entity relation or one of the entity's
2029                # sub-relations.
2030                $stmt .= " WHERE $pathTables[0].id $qualifier";
2031                # Now we run through the remaining entities in the path, connecting them up.
2032                for (my $i = 1; $i <= $#pathTables; $i += 2) {
2033                    # Connect the current relationship to the preceding entity.
2034                    my ($entity, $rel) = @pathTables[$i-1,$i];
2035                    # The style of connection depends on the direction of the relationship.
2036                    $stmt .= " AND $entity.id = $rel.$keyName";
2037                    if ($i + 1 <= $#pathTables) {
2038                        # Here there's a next entity, so connect that to the relationship's
2039                        # to-link.
2040                        my $entity2 = $pathTables[$i+1];
2041                        $stmt .= " AND $rel.to_link = $entity2.id";
2042                    }
2043                }
2044                # Now we have our desired DELETE statement.
2045                if ($options{testMode}) {
2046                    # Here the user wants to trace without executing.
2047                    Trace($stmt) if T(0);
2048                } else {
2049                    # Here we can delete. Note that the SQL method dies with a confession
2050                    # if an error occurs, so we just go ahead and do it.
2051                    Trace("Executing delete from $target using '$objectID'.") if T(3);
2052                    my $rv = $db->SQL($stmt, 0, $objectID);
2053                    # Accumulate the statistics for this delete. The only rows deleted
2054                    # are from the target table, so we use its name to record the
2055                    # statistic.
2056                    $retVal->Add($target, $rv);
2057                }
2058            }
2059        }
2060        # Return the result.
2061        return $retVal;
2062    }
2063    
2064    =head3 Disconnect
2065    
2066        $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID);
2067    
2068    Disconnect an entity instance from all the objects to which it is related. This
2069    will delete each relationship instance that connects to the specified entity.
2070    
2071    =over 4
2072    
2073    =item relationshipName
2074    
2075    Name of the relationship whose instances are to be deleted.
2076    
2077    =item originEntityName
2078    
2079    Name of the entity that is to be disconnected.
2080    
2081    =item originEntityID
2082    
2083    ID of the entity that is to be disconnected.
2084    
2085    =back
2086    
2087    =cut
2088    
2089    sub Disconnect {
2090        # Get the parameters.
2091        my ($self, $relationshipName, $originEntityName, $originEntityID) = @_;
2092        # Get the relationship descriptor.
2093        my $structure = $self->_GetStructure($relationshipName);
2094        # Insure we have a relationship.
2095        if (! exists $structure->{from}) {
2096            Confess("$relationshipName is not a relationship in the database.");
2097        } else {
2098            # Get the database handle.
2099            my $dbh = $self->{_dbh};
2100            # We'll set this value to 1 if we find our entity.
2101            my $found = 0;
2102            # Loop through the ends of the relationship.
2103            for my $dir ('from', 'to') {
2104                if ($structure->{$dir} eq $originEntityName) {
2105                    $found = 1;
2106                    # Here we want to delete all relationship instances on this side of the
2107                    # entity instance.
2108                    Trace("Disconnecting in $dir direction with ID \"$originEntityID\".");
2109                    # We do this delete in batches to keep it from dragging down the
2110                    # server.
2111                    my $limitClause = ($FIG_Config::delete_limit ? "LIMIT $FIG_Config::delete_limit" : "");
2112                    my $done = 0;
2113                    while (! $done) {
2114                        # Do the delete.
2115                        my $rows = $dbh->SQL("DELETE FROM $relationshipName WHERE ${dir}_link = ? $limitClause", 0, $originEntityID);
2116                        # See if we're done. We're done if no rows were found or the delete is unlimited.
2117                        $done = ($rows == 0 || ! $limitClause);
2118                    }
2119                }
2120            }
2121            # Insure we found the entity on at least one end.
2122            if (! $found) {
2123                Confess("Entity \"$originEntityName\" does not use $relationshipName.");
2124            }
2125        }
2126    }
2127    
2128    =head3 DeleteRow
2129    
2130        $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values);
2131    
2132    Delete a row from a relationship. In most cases, only the from-link and to-link are
2133    needed; however, for relationships with intersection data values can be specified
2134    for the other fields using a hash.
2135    
2136    =over 4
2137    
2138    =item relationshipName
2139    
2140    Name of the relationship from which the row is to be deleted.
2141    
2142    =item fromLink
2143    
2144    ID of the entity instance in the From direction.
2145    
2146    =item toLink
2147    
2148    ID of the entity instance in the To direction.
2149    
2150    =item values
2151    
2152    Reference to a hash of other values to be used for filtering the delete.
2153    
2154    =back
2155    
2156    =cut
2157    
2158    sub DeleteRow {
2159        # Get the parameters.
2160        my ($self, $relationshipName, $fromLink, $toLink, $values) = @_;
2161        # Create a hash of all the filter information.
2162        my %filter = ('from-link' => $fromLink, 'to-link' => $toLink);
2163        if (defined $values) {
2164            for my $key (keys %{$values}) {
2165                $filter{$key} = $values->{$key};
2166            }
2167        }
2168        # Build an SQL statement out of the hash.
2169        my @filters = ();
2170        my @parms = ();
2171        for my $key (keys %filter) {
2172            push @filters, _FixName($key) . " = ?";
2173            push @parms, $filter{$key};
2174        }
2175        Trace("Parms for delete row are " . join(", ", map { "\"$_\"" } @parms) . ".") if T(SQL => 4);
2176        my $command = "DELETE FROM $relationshipName WHERE " .
2177                      join(" AND ", @filters);
2178        # Execute it.
2179        my $dbh = $self->{_dbh};
2180        $dbh->SQL($command, undef, @parms);
2181    }
2182    
2183    =head3 DeleteLike
2184    
2185        my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms);
2186    
2187    Delete all the relationship rows that satisfy a particular filter condition. Unlike a normal
2188    filter, only fields from the relationship itself can be used.
2189    
2190    =over 4
2191    
2192    =item relName
2193    
2194    Name of the relationship whose records are to be deleted.
2195    
2196    =item filter
2197    
2198    A filter clause (L</Get>-style) for the delete query.
2199    
2200    =item parms
2201    
2202    Reference to a list of parameters for the filter clause.
2203    
2204    =item RETURN
2205    
2206    Returns a count of the number of rows deleted.
2207    
2208    =back
2209    
2210    =cut
2211    
2212    sub DeleteLike {
2213        # Get the parameters.
2214        my ($self, $objectName, $filter, $parms) = @_;
2215        # Declare the return variable.
2216        my $retVal;
2217        # Insure the parms argument is an array reference if the caller left it off.
2218        if (! defined($parms)) {
2219            $parms = [];
2220        }
2221        # Insure we have a relationship. The main reason for this is if we delete an entity
2222        # instance we have to yank out a bunch of other stuff with it.
2223        if ($self->IsEntity($objectName)) {
2224            Confess("Cannot use DeleteLike on $objectName, because it is not a relationship.");
2225        } else {
2226            # Create the SQL command suffix to get the desierd records.
2227            my ($suffix) = $self->_SetupSQL([$objectName], $filter);
2228            # Convert it to a DELETE command.
2229            my $command = "DELETE $suffix";
2230            # Execute the command.
2231            my $dbh = $self->{_dbh};
2232            my $result = $dbh->SQL($command, 0, @{$parms});
2233            # Check the results. Note we convert the "0D0" result to a real zero.
2234            # A failure causes an abnormal termination, so the caller isn't going to
2235            # worry about it.
2236            if (! defined $result) {
2237                Confess("Error deleting from $objectName: " . $dbh->errstr());
2238            } elsif ($result == 0) {
2239                $retVal = 0;
2240            } else {
2241                $retVal = $result;
2242            }
2243        }
2244        # Return the result count.
2245        return $retVal;
2246    }
2247    
2248    =head3 SortNeeded
2249    
2250        my $parms = $erdb->SortNeeded($relationName);
2251    
2252    Return the pipe command for the sort that should be applied to the specified
2253    relation when creating the load file.
2254    
2255    For example, if the load file should be sorted ascending by the first
2256    field, this method would return
2257    
2258        sort -k1 -t"\t"
2259    
2260    If the first field is numeric, the method would return
2261    
2262        sort -k1n -t"\t"
2263    
2264    Unfortunately, due to a bug in the C<sort> command, we cannot eliminate duplicate
2265    keys using a sort.
2266    
2267    =over 4
2268    
2269    =item relationName
2270    
2271    Name of the relation to be examined.
2272    
2273    =item
2274    
2275    Returns the sort command to use for sorting the relation, suitable for piping.
2276    
2277    =back
2278    
2279    =cut
2280    #: Return Type $;
2281    sub SortNeeded {
2282        # Get the parameters.
2283        my ($self, $relationName) = @_;
2284        # Declare a descriptor to hold the names of the key fields.
2285        my @keyNames = ();
2286        # Get the relation structure.
2287        my $relationData = $self->_FindRelation($relationName);
2288        # Find out if the relation is a primary entity relation,
2289        # a relationship relation, or a secondary entity relation.
2290        my $entityTable = $self->{_metaData}->{Entities};
2291        my $relationshipTable = $self->{_metaData}->{Relationships};
2292        if (exists $entityTable->{$relationName}) {
2293            # Here we have a primary entity relation.
2294            push @keyNames, "id";
2295        } elsif (exists $relationshipTable->{$relationName}) {
2296            # Here we have a relationship. We sort using the FROM index.
2297            my $relationshipData = $relationshipTable->{$relationName};
2298            my $index = $relationData->{Indexes}->{idxFrom};
2299            push @keyNames, @{$index->{IndexFields}};
2300        } else {
2301            # Here we have a secondary entity relation, so we have a sort on the ID field.
2302            push @keyNames, "id";
2303        }
2304        # Now we parse the key names into sort parameters. First, we prime the return
2305        # string.
2306        my $retVal = "sort -t\"\t\" ";
2307        # Get the relation's field list.
2308        my @fields = @{$relationData->{Fields}};
2309        # Loop through the keys.
2310        for my $keyData (@keyNames) {
2311            # Get the key and the ordering.
2312            my ($keyName, $ordering);
2313            if ($keyData =~ /^([^ ]+) DESC/) {
2314                ($keyName, $ordering) = ($1, "descending");
2315            } else {
2316                ($keyName, $ordering) = ($keyData, "ascending");
2317            }
2318            # Find the key's position and type.
2319            my $fieldSpec;
2320            for (my $i = 0; $i <= $#fields && ! $fieldSpec; $i++) {
2321                my $thisField = $fields[$i];
2322                if ($thisField->{name} eq $keyName) {
2323                    # Get the sort modifier for this field type. The modifier
2324                    # decides whether we're using a character, numeric, or
2325                    # floating-point sort.
2326                    my $modifier = $TypeTable{$thisField->{type}}->{sort};
2327                    # If the index is descending for this field, denote we want
2328                    # to reverse the sort order on this field.
2329                    if ($ordering eq 'descending') {
2330                        $modifier .= "r";
2331                    }
2332                    # Store the position and modifier into the field spec, which
2333                    # will stop the inner loop. Note that the field number is
2334                    # 1-based in the sort command, so we have to increment the
2335                    # index.
2336                    $fieldSpec = ($i + 1) . $modifier;
2337                }
2338            }
2339            # Add this field to the sort command.
2340            $retVal .= " -k$fieldSpec";
2341        }
2342        # Return the result.
2343        return $retVal;
2344    }
2345    
2346    =head3 GetList
2347    
2348        my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params);
2349    
2350    Return a list of object descriptors for the specified objects as determined by the
2351    specified filter clause.
2352    
2353    This method is essentially the same as L</Get> except it returns a list of objects rather
2354    than a query object that can be used to get the results one record at a time.
2355    
2356    =over 4
2357    
2358    =item objectNames
2359    
2360    List containing the names of the entity and relationship objects to be retrieved.
2361    
2362    =item filterClause
2363    
2364    WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
2365    be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
2366    specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
2367    in the filter clause should be added to the parameter list as additional parameters. The
2368    fields in a filter clause can come from primary entity relations, relationship relations,
2369    or secondary entity relations; however, all of the entities and relationships involved must
2370    be included in the list of object names.
2371    
2372    The filter clause can also specify a sort order. To do this, simply follow the filter string
2373    with an ORDER BY clause. For example, the following filter string gets all genomes for a
2374    particular genus and sorts them by species name.
2375    
2376        "Genome(genus) = ? ORDER BY Genome(species)"
2377    
2378    The rules for field references in a sort order are the same as those for field references in the
2379    filter clause in general; however, odd things may happen if a sort field is from a secondary
2380    relation.
2381    
2382    =item params
2383    
2384    Reference to a list of parameter values to be substituted into the filter clause.
2385    
2386    =item RETURN
2387    
2388    Returns a list of B<ERDBObject>s that satisfy the query conditions.
2389    
2390    =back
2391    
2392    =cut
2393    #: Return Type @%
2394    sub GetList {
2395        # Get the parameters.
2396        my ($self, $objectNames, $filterClause, $params) = @_;
2397        # Declare the return variable.
2398        my @retVal = ();
2399        # Perform the query.
2400        my $query = $self->Get($objectNames, $filterClause, $params);
2401        # Loop through the results.
2402        while (my $object = $query->Fetch) {
2403            push @retVal, $object;
2404        }
2405        # Return the result.
2406        return @retVal;
2407    }
2408    
2409    =head3 GetCount
2410    
2411        my $count = $erdb->GetCount(\@objectNames, $filter, \@params);
2412    
2413    Return the number of rows found by a specified query. This method would
2414    normally be used to count the records in a single table. For example, in a
2415    genetics database
2416    
2417        my $count = $erdb->GetCount(['Genome'], 'Genome(genus-species) LIKE ?', ['homo %']);
2418    
2419    would return the number of genomes for the genus I<homo>. It is conceivable, however,
2420    to use it to return records based on a join. For example,
2421    
2422        my $count = $erdb->GetCount(['HasFeature', 'Genome'], 'Genome(genus-species) LIKE ?',
2423                                    ['homo %']);
2424    
2425    would return the number of features for genomes in the genus I<homo>. Note that
2426    only the rows from the first table are counted. If the above command were
2427    
2428        my $count = $erdb->GetCount(['Genome', 'Feature'], 'Genome(genus-species) LIKE ?',
2429                                    ['homo %']);
2430    
2431    it would return the number of genomes, not the number of genome/feature pairs.
2432    
2433    =over 4
2434    
2435    =item objectNames
2436    
2437    Reference to a list of the objects (entities and relationships) included in the
2438    query.
2439    
2440    =item filter
2441    
2442    A filter clause for restricting the query. The rules are the same as for the L</Get>
2443    method.
2444    
2445    =item params
2446    
2447    Reference to a list of the parameter values to be substituted for the parameter marks
2448    in the filter.
2449    
2450    =item RETURN
2451    
2452    Returns a count of the number of records in the first table that would satisfy
2453    the query.
2454    
2455    =back
2456    
2457    =cut
2458    
2459    sub GetCount {
2460        # Get the parameters.
2461        my ($self, $objectNames, $filter, $params) = @_;
2462        # Insure the params argument is an array reference if the caller left it off.
2463        if (! defined($params)) {
2464            $params = [];
2465        }
2466        # Declare the return variable.
2467        my $retVal;
2468        # Find out if we're counting an entity or a relationship.
2469        my $countedField;
2470        if ($self->IsEntity($objectNames->[0])) {
2471            $countedField = "id";
2472        } else {
2473            # For a relationship we count the to-link because it's usually more
2474            # numerous. Note we're automatically converting to the SQL form
2475            # of the field name (to_link vs. to-link).
2476            $countedField = "to_link";
2477        }
2478        # Create the SQL command suffix to get the desired records.
2479        my ($suffix, $mappedNameListRef, $mappedNameHashRef) = $self->_SetupSQL($objectNames,
2480                                                                                $filter);
2481        # Prefix it with text telling it we want a record count.
2482        my $firstObject = $mappedNameListRef->[0];
2483        my $command = "SELECT COUNT($firstObject.$countedField) $suffix";
2484        # Prepare and execute the command.
2485        my $sth = $self->_GetStatementHandle($command, $params);
2486        # Get the count value.
2487        ($retVal) = $sth->fetchrow_array();
2488        # Check for a problem.
2489        if (! defined($retVal)) {
2490            if ($sth->err) {
2491                # Here we had an SQL error.
2492                Confess("Error retrieving row count: " . $sth->errstr());
2493            } else {
2494                # Here we have no result.
2495                Confess("No result attempting to retrieve row count.");
2496            }
2497        }
2498        # Return the result.
2499        return $retVal;
2500    }
2501    
2502    =head3 ComputeObjectSentence
2503    
2504        my $sentence = $erdb->ComputeObjectSentence($objectName);
2505    
2506    Check an object name, and if it is a relationship convert it to a relationship sentence.
2507    
2508    =over 4
2509    
2510    =item objectName
2511    
2512    Name of the entity or relationship.
2513    
2514    =item RETURN
2515    
2516    Returns a string containing the entity name or a relationship sentence.
2517    
2518    =back
2519    
2520    =cut
2521    
2522    sub ComputeObjectSentence {
2523        # Get the parameters.
2524        my ($self, $objectName) = @_;
2525        # Set the default return value.
2526        my $retVal = $objectName;
2527        # Look for the object as a relationship.
2528        my $relTable = $self->{_metaData}->{Relationships};
2529        if (exists $relTable->{$objectName}) {
2530            # Get the relationship sentence.
2531            $retVal = _ComputeRelationshipSentence($objectName, $relTable->{$objectName});
2532        }
2533        # Return the result.
2534        return $retVal;
2535    }
2536    
2537    =head3 DumpRelations
2538    
2539        $erdb->DumpRelations($outputDirectory);
2540    
2541    Write the contents of all the relations to tab-delimited files in the specified directory.
2542    Each file will have the same name as the relation dumped, with an extension of DTX.
2543    
2544    =over 4
2545    
2546    =item outputDirectory
2547    
2548    Name of the directory into which the relation files should be dumped.
2549    
2550    =back
2551    
2552    =cut
2553    
2554    sub DumpRelations {
2555        # Get the parameters.
2556        my ($self, $outputDirectory) = @_;
2557        # Now we need to run through all the relations. First, we loop through the entities.
2558        my $metaData = $self->{_metaData};
2559        my $entities = $metaData->{Entities};
2560        for my $entityName (keys %{$entities}) {
2561            my $entityStructure = $entities->{$entityName};
2562            # Get the entity's relations.
2563            my $relationList = $entityStructure->{Relations};
2564            # Loop through the relations, dumping them.
2565            for my $relationName (keys %{$relationList}) {
2566                my $relation = $relationList->{$relationName};
2567                $self->_DumpRelation($outputDirectory, $relationName, $relation);
2568            }
2569        }
2570        # Next, we loop through the relationships.
2571        my $relationships = $metaData->{Relationships};
2572        for my $relationshipName (keys %{$relationships}) {
2573            my $relationshipStructure = $relationships->{$relationshipName};
2574            # Dump this relationship's relation.
2575            $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});
2576        }
2577    }
2578    
2579    =head3 InsertValue
2580    
2581        $erdb->InsertValue($entityID, $fieldName, $value);
2582    
2583    This method will insert a new value into the database. The value must be one
2584    associated with a secondary relation, since primary values cannot be inserted:
2585    they occur exactly once. Secondary values, on the other hand, can be missing
2586    or multiply-occurring.
2587    
2588    =over 4
2589    
2590    =item entityID
2591    
2592    ID of the object that is to receive the new value.
2593    
2594    =item fieldName
2595    
2596    Field name for the new value-- this includes the entity name, since
2597    field names are of the format I<objectName>C<(>I<fieldName>C<)>.
2598    
2599    =item value
2600    
2601    New value to be put in the field.
2602    
2603    =back
2604    
2605    =cut
2606    
2607    sub InsertValue {
2608        # Get the parameters.
2609        my ($self, $entityID, $fieldName, $value) = @_;
2610        # Parse the entity name and the real field name.
2611        if ($fieldName =~ /^([^(]+)\(([^)]+)\)/) {
2612            my $entityName = $1;
2613            my $fieldTitle = $2;
2614            # Get its descriptor.
2615            if (!$self->IsEntity($entityName)) {
2616                Confess("$entityName is not a valid entity.");
2617            } else {
2618                my $entityData = $self->{_metaData}->{Entities}->{$entityName};
2619                # Find the relation containing this field.
2620                my $fieldHash = $entityData->{Fields};
2621                if (! exists $fieldHash->{$fieldTitle}) {
2622                    Confess("$fieldTitle not found in $entityName.");
2623                } else {
2624                    my $relation = $fieldHash->{$fieldTitle}->{relation};
2625                    if ($relation eq $entityName) {
2626                        Confess("Cannot do InsertValue on primary field $fieldTitle of $entityName.");
2627                    } else {
2628                        # Now we can create an INSERT statement.
2629                        my $dbh = $self->{_dbh};
2630                        my $fixedName = _FixName($fieldTitle);
2631                        my $statement = "INSERT INTO $relation (id, $fixedName) VALUES(?, ?)";
2632                        # Execute the command.
2633                        $dbh->SQL($statement, 0, $entityID, $value);
2634                    }
2635                }
2636            }
2637        } else {
2638            Confess("$fieldName is not a valid field name.");
2639        }
2640    }
2641    
2642    =head3 InsertObject
2643    
2644        $erdb->InsertObject($objectType, \%fieldHash);
2645    
2646    Insert an object into the database. The object is defined by a type name and then a hash
2647    of field names to values. Field values in the primary relation are represented by scalars.
2648    (Note that for relationships, the primary relation is the B<only> relation.)
2649    Field values for the other relations comprising the entity are always list references. For
2650    example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases
2651    C<ZP_00210270.1> and C<gi|46206278>.
2652    
2653        $erdb->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']});
2654    
2655    The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
2656    property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
2657    
2658        $erdb->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'});
2659    
2660    =over 4
2661    
2662    =item newObjectType
2663    
2664    Type name of the object to insert.
2665    
2666    =item fieldHash
2667    
2668    Hash of field names to values.
2669    
2670    =back
2671    
2672    =cut
2673    
2674    sub InsertObject {
2675        # Get the parameters.
2676        my ($self, $newObjectType, $fieldHash) = @_;
2677        # Denote that so far we appear successful.
2678        my $retVal = 1;
2679        # Get the database handle.
2680        my $dbh = $self->{_dbh};
2681        # Get the relation list.
2682        my $relationTable = $self->_GetRelationTable($newObjectType);
2683        # Loop through the relations. We'll build insert statements for each one. If a relation is
2684        # secondary, we may end up generating multiple insert statements. If an error occurs, we
2685        # stop the loop.
2686        my @relationList = keys %{$relationTable};
2687        for (my $i = 0; $retVal && $i <= $#relationList; $i++) {
2688            my $relationName = $relationList[$i];
2689            my $relationDefinition = $relationTable->{$relationName};
2690            # Get the relation's fields. For each field we will collect a value in the corresponding
2691            # position of the @valueList array. If one of the fields is missing, we will add it to the
2692            # @missing list.
2693            my @fieldList = @{$relationDefinition->{Fields}};
2694            my @fieldNameList = ();
2695            my @valueList = ();
2696            my @missing = ();
2697            my $recordCount = 1;
2698            for my $fieldDescriptor (@fieldList) {
2699                # Get the field name and save it. Note we need to fix it up so the hyphens
2700                # are converted to underscores.
2701                my $fieldName = $fieldDescriptor->{name};
2702                push @fieldNameList, _FixName($fieldName);
2703                # Look for the named field in the incoming structure. Note that we are looking
2704                # for the real field name, not the fixed-up one!
2705                if (exists $fieldHash->{$fieldName}) {
2706                    # Here we found the field. Stash it in the value list.
2707                    my $value = $fieldHash->{$fieldName};
2708                    push @valueList, $value;
2709                    # If the value is a list, we may need to increment the record count.
2710                    if (ref $value eq "ARRAY") {
2711                        my $thisCount = @{$value};
2712                        if ($recordCount == 1) {
2713                            # Here we have our first list, so we save its count.
2714                            $recordCount = $thisCount;
2715                        } elsif ($recordCount != $thisCount) {
2716                            # Here we have a second list, so its length has to match the
2717                            # previous lists.
2718                            Trace("Field $value in new $newObjectType object has an invalid list length $thisCount. Expected $recordCount.") if T(0);
2719                            $retVal = 0;
2720                        }
2721                    }
2722                } else {
2723                    # Here the field is not present. Flag it as missing.
2724                    push @missing, $fieldName;
2725                }
2726            }
2727            # If we are the primary relation, add the new-record flag.
2728            if ($relationName eq $newObjectType) {
2729                push @valueList, 1;
2730                push @fieldNameList, "new_record";
2731            }
2732            # Only proceed if there are no missing fields.
2733            if (@missing > 0) {
2734                Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .
2735                    join(' ', @missing)) if T(1);
2736            } else {
2737                # Build the INSERT statement.
2738                my $statement = "INSERT INTO $relationName (" . join (', ', @fieldNameList) .
2739                    ") VALUES (";
2740                # Create a marker list of the proper size and put it in the statement.
2741                my @markers = ();
2742                while (@markers < @fieldNameList) { push @markers, '?'; }
2743                $statement .= join(', ', @markers) . ")";
2744                # We have the insert statement, so prepare it.
2745                my $sth = $dbh->prepare_command($statement);
2746                Trace("Insert statement prepared: $statement") if T(3);
2747                # Now we loop through the values. If a value is scalar, we use it unmodified. If it's
2748                # a list, we use the current element. The values are stored in the @parameterList array.
2749                my $done = 0;
2750                for (my $i = 0; $i < $recordCount; $i++) {
2751                    # Clear the parameter list array.
2752                    my @parameterList = ();
2753                    # Loop through the values.
2754                    for my $value (@valueList) {
2755                        # Check to see if this is a scalar value.
2756                        if (ref $value eq "ARRAY") {
2757                            # Here we have a list value. Pull the current entry.
2758                            push @parameterList, $value->[$i];
2759                        } else {
2760                            # Here we have a scalar value. Use it unmodified.
2761                            push @parameterList, $value;
2762                        }
2763                    }
2764                    # Execute the INSERT statement with the specified parameter list.
2765                    $retVal = $sth->execute(@parameterList);
2766                    if (!$retVal) {
2767                        my $errorString = $sth->errstr();
2768                        Confess("Error inserting into $relationName: $errorString");
2769                    } else {
2770                        Trace("Insert successful using $parameterList[0].") if T(3);
2771                    }
2772                }
2773            }
2774        }
2775        # Return a 1 for backward compatability.
2776        return 1;
2777    }
2778    
2779    =head3 UpdateEntity
2780    
2781        $erdb->UpdateEntity($entityName, $id, \%fields);
2782    
2783    Update the values of an entity. This is an unprotected update, so it should only be
2784    done if the database resides on a database server.
2785    
2786    =over 4
2787    
2788    =item entityName
2789    
2790    Name of the entity to update. (This is the entity type.)
2791    
2792    =item id
2793    
2794    ID of the entity to update. If no entity exists with this ID, an error will be thrown.
2795    
2796    =item fields
2797    
2798    Reference to a hash mapping field names to their new values. All of the fields named
2799    must be in the entity's primary relation, and they cannot any of them be the ID field.
2800    
2801    =back
2802    
2803    =cut
2804    
2805    sub UpdateEntity {
2806        # Get the parameters.
2807        my ($self, $entityName, $id, $fields) = @_;
2808        # Get a list of the field names being updated.
2809        my @fieldList = keys %{$fields};
2810        # Verify that the fields exist.
2811        my $checker = $self->GetFieldTable($entityName);
2812        for my $field (@fieldList) {
2813            if ($field eq 'id') {
2814                Confess("Cannot update the ID field for entity $entityName.");
2815            } elsif ($checker->{$field}->{relation} ne $entityName) {
2816                Confess("Cannot find $field in primary relation of $entityName.");
2817            }
2818        }
2819        # Build the SQL statement.
2820        my @sets = ();
2821        my @valueList = ();
2822        for my $field (@fieldList) {
2823            push @sets, _FixName($field) . " = ?";
2824            push @valueList, $fields->{$field};
2825        }
2826        my $command = "UPDATE $entityName SET " . join(", ", @sets) . " WHERE id = ?";
2827        # Add the ID to the list of binding values.
2828        push @valueList, $id;
2829        # Call SQL to do the work.
2830        my $rows = $self->{_dbh}->SQL($command, 0, @valueList);
2831        # Check for errors.
2832        if ($rows == 0) {
2833            Confess("Entity $id of type $entityName not found.");
2834        }
2835    }
2836    
2837    =head3 LoadTable
2838    
2839        my $results = $erdb->LoadTable($fileName, $relationName, %options);
2840    
2841    Load data from a tab-delimited file into a specified table, optionally re-creating the table
2842    first.
2843    
2844    =over 4
2845    
2846    =item fileName
2847    
2848    Name of the file from which the table data should be loaded.
2849    
2850    =item relationName
2851    
2852    Name of the relation to be loaded. This is the same as the table name.
2853    
2854    =item options
2855    
2856    A hash of load options.
2857    
2858    =item RETURN
2859    
2860    Returns a statistical object containing a list of the error messages.
2861    
2862    =back
2863    
2864    The permissible options are as follows.
2865    
2866    =over 4
2867    
2868    =item truncate
2869    
2870    If TRUE, then the table will be erased before loading.
2871    
2872    =item mode
2873    
2874    Mode in which the load should operate, either C<low_priority> or C<concurrent>.
2875    This option is only applicable to a MySQL database.
2876    
2877    =item partial
2878    
2879    If TRUE, then it is assumed that this is a partial load, and the table will not
2880    be analyzed and compacted at the end.
2881    
2882    =back
2883    
2884    =cut
2885    sub LoadTable {
2886        # Get the parameters.
2887        my ($self, $fileName, $relationName, %options) = @_;
2888        # Create the statistical return object.
2889        my $retVal = _GetLoadStats();
2890        # Trace the fact of the load.
2891        Trace("Loading table $relationName from $fileName") if T(2);
2892        # Get the database handle.
2893        my $dbh = $self->{_dbh};
2894        # Get the input file size.
2895        my $fileSize = -s $fileName;
2896        # Get the relation data.
2897        my $relation = $self->_FindRelation($relationName);
2898        # Check the truncation flag.
2899        if ($options{truncate}) {
2900            Trace("Creating table $relationName") if T(2);
2901            # Compute the row count estimate. We take the size of the load file,
2902            # divide it by the estimated row size, and then multiply by 2 to
2903            # leave extra room. We postulate a minimum row count of 1000 to
2904            # prevent problems with incoming empty load files.
2905            my $rowSize = $self->EstimateRowSize($relationName);
2906            my $estimate = $fileSize * 8 / $rowSize;
2907            if ($estimate < 1000) {
2908                $estimate = 1000;
2909            }
2910            # Re-create the table without its index.
2911            $self->CreateTable($relationName, 0, $estimate);
2912            # If this is a pre-index DBMS, create the index here.
2913            if ($dbh->{_preIndex}) {
2914                eval {
2915                    $self->CreateIndex($relationName);
2916                };
2917                if ($@) {
2918                    $retVal->AddMessage($@);
2919                }
2920            }
2921        }
2922        # Load the table.
2923        my $rv;
2924        eval {
2925            $rv = $dbh->load_table(file => $fileName, tbl => $relationName, style => $options{mode});
2926        };
2927        if (!defined $rv) {
2928            $retVal->AddMessage($@) if ($@);
2929            $retVal->AddMessage("Table load failed for $relationName using $fileName: " . $dbh->error_message);
2930            Trace("Table load failed for $relationName.") if T(1);
2931        } else {
2932            # Here we successfully loaded the table.
2933            $retVal->Add("tables");
2934            my $size = -s $fileName;
2935            Trace("$size bytes loaded into $relationName.") if T(2);
2936            $retVal->Add("bytes", $size);
2937            # If we're rebuilding, we need to create the table indexes.
2938            if ($options{truncate}) {
2939                # Indexes are created here for PostGres. For PostGres, indexes are
2940                # best built at the end. For MySQL, the reverse is true.
2941                if (! $dbh->{_preIndex}) {
2942                    eval {
2943                        $self->CreateIndex($relationName);
2944                    };
2945                    if ($@) {
2946                        $retVal->AddMessage($@);
2947                    }
2948                }
2949                # The full-text index (if any) is always built last, even for MySQL.
2950                # First we need to see if this table has a full-text index. Only
2951                # primary relations are allowed that privilege.
2952                Trace("Checking for full-text index on $relationName.") if T(2);
2953                if ($self->_IsPrimary($relationName)) {
2954                    $self->CreateSearchIndex($relationName);
2955                }
2956            }
2957        }
2958        # Analyze the table to improve performance.
2959        if (! $options{partial}) {
2960            Trace("Analyzing and compacting $relationName.") if T(3);
2961            $dbh->vacuum_it($relationName);
2962        }
2963        Trace("$relationName load completed.") if T(3);
2964        # Return the statistics.
2965        return $retVal;
2966    }
2967    
2968    =head3 CreateSearchIndex
2969    
2970        $erdb->CreateSearchIndex($objectName);
2971    
2972    Check for a full-text search index on the specified entity or relationship object, and
2973    if one is required, rebuild it.
2974    
2975    =over 4
2976    
2977    =item objectName
2978    
2979    Name of the entity or relationship to be indexed.
2980    
2981    =back
2982    
2983    =cut
2984    
2985    sub CreateSearchIndex {
2986        # Get the parameters.
2987        my ($self, $objectName) = @_;
2988        # Get the relation's entity/relationship structure.
2989        my $structure = $self->_GetStructure($objectName);
2990        # Get the database handle.
2991        my $dbh = $self->{_dbh};
2992        Trace("Checking for search fields in $objectName.") if T(3);
2993        # Check for a searchable fields list.
2994        if (exists $structure->{searchFields}) {
2995            # Here we know that we need to create a full-text search index.
2996            # Get an SQL-formatted field name list.
2997            my $fields = join(", ", _FixNames(@{$structure->{searchFields}}));
2998            # Create the index. If it already exists, it will be dropped.
2999            $dbh->create_index(tbl => $objectName, idx => "search_idx",
3000                               flds => $fields, kind => 'fulltext');
3001            Trace("Index created for $fields in $objectName.") if T(2);
3002        }
3003    }
3004    
3005    =head3 DropRelation
3006    
3007        $erdb->DropRelation($relationName);
3008    
3009    Physically drop a relation from the database.
3010    
3011    =over 4
3012    
3013    =item relationName
3014    
3015    Name of the relation to drop. If it does not exist, this method will have
3016    no effect.
3017    
3018    =back
3019    
3020    =cut
3021    
3022    sub DropRelation {
3023        # Get the parameters.
3024        my ($self, $relationName) = @_;
3025        # Get the database handle.
3026        my $dbh = $self->{_dbh};
3027        # Drop the relation. The method used here has no effect if the relation
3028        # does not exist.
3029        Trace("Invoking DB Kernel to drop $relationName.") if T(3);
3030        $dbh->drop_table(tbl => $relationName);
3031    }
3032    
3033    =head3 MatchSqlPattern
3034    
3035        my $matched = ERDB::MatchSqlPattern($value, $pattern);
3036    
3037    Determine whether or not a specified value matches an SQL pattern. An SQL
3038    pattern has two wild card characters: C<%> that matches multiple characters,
3039    and C<_> that matches a single character. These can be escaped using a
3040    backslash (C<\>). We pull this off by converting the SQL pattern to a
3041    PERL regular expression. As per SQL rules, the match is case-insensitive.
3042    
3043    =over 4
3044    
3045    =item value
3046    
3047    Value to be matched against the pattern. Note that an undefined or empty
3048    value will not match anything.
3049    
3050    =item pattern
3051    
3052    SQL pattern against which to match the value. An undefined or empty pattern will
3053    match everything.
3054    
3055    =item RETURN
3056    
3057    Returns TRUE if the value and pattern match, else FALSE.
3058    
3059    =back
3060    
3061    =cut
3062    
3063    sub MatchSqlPattern {
3064        # Get the parameters.
3065        my ($value, $pattern) = @_;
3066        # Declare the return variable.
3067        my $retVal;
3068        # Insure we have a pattern.
3069        if (! defined($pattern) || $pattern eq "") {
3070            $retVal = 1;
3071        } else {
3072            # Break the pattern into pieces around the wildcard characters. Because we
3073            # use parentheses in the split function's delimiter expression, we'll get
3074            # list elements for the delimiters as well as the rest of the string.
3075            my @pieces = split /([_%]|\\[_%])/, $pattern;
3076            # Check some fast special cases.
3077            if ($pattern eq '%') {
3078                # A null pattern matches everything.
3079                $retVal = 1;
3080            } elsif (@pieces == 1) {
3081                # No wildcards, so we have a literal comparison. Note we're case-insensitive.
3082                $retVal = (lc($value) eq lc($pattern));
3083            } elsif (@pieces == 2 && $pieces[1] eq '%') {
3084                # A wildcard at the end, so we have a substring match. This is also case-insensitive.
3085                $retVal = (lc(substr($value, 0, length($pieces[0]))) eq lc($pieces[0]));
3086            } else {
3087                # Okay, we have to do it the hard way. Convert each piece to a PERL pattern.
3088                my $realPattern = "";
3089                for my $piece (@pieces) {
3090                    # Determine the type of piece.
3091                    if ($piece eq "") {
3092                        # Empty pieces are ignored.
3093                    } elsif ($piece eq "%") {
3094                        # Here we have a multi-character wildcard. Note that it can match
3095                        # zero or more characters.
3096                        $realPattern .= ".*"
3097                    } elsif ($piece eq "_") {
3098                        # Here we have a single-character wildcard.
3099                        $realPattern .= ".";
3100                    } elsif ($piece eq "\\%" || $piece eq "\\_") {
3101                        # This is an escape sequence (which is a rare thing, actually).
3102                        $realPattern .= substr($piece, 1, 1);
3103                    } else {
3104                        # Here we have raw text.
3105                        $realPattern .= quotemeta($piece);
3106                    }
3107                }
3108                # Do the match.
3109                $retVal = ($value =~ /^$realPattern$/i ? 1 : 0);
3110            }
3111        }
3112        # Return the result.
3113        return $retVal;
3114    }
3115    
3116    =head3 GetEntity
3117    
3118        my $entityObject = $erdb->GetEntity($entityType, $ID);
3119    
3120    Return an object describing the entity instance with a specified ID.
3121    
3122    =over 4
3123    
3124    =item entityType
3125    
3126    Entity type name.
3127    
3128    =item ID
3129    
3130    ID of the desired entity.
3131    
3132    =item RETURN
3133    
3134    Returns a B<ERDBObject> representing the desired entity instance, or an undefined value if no
3135    instance is found with the specified key.
3136    
3137    =back
3138    
3139    =cut
3140    
3141    sub GetEntity {
3142        # Get the parameters.
3143        my ($self, $entityType, $ID) = @_;
3144        # Create a query.
3145        my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
3146        # Get the first (and only) object.
3147        my $retVal = $query->Fetch();
3148        # Return the result.
3149        return $retVal;
3150    }
3151    
3152    =head3 GetChoices
3153    
3154        my @values = $erdb->GetChoices($entityName, $fieldName);
3155    
3156    Return a list of all the values for the specified field that are represented in the
3157    specified entity.
3158    
3159    Note that if the field is not indexed, then this will be a very slow operation.
3160    
3161    =over 4
3162    
3163    =item entityName
3164    
3165    Name of an entity in the database.
3166    
3167    =item fieldName
3168    
3169    Name of a field belonging to the entity. This is a raw field name without
3170    the standard parenthesized notation used in most calls.
3171    
3172    =item RETURN
3173    
3174    Returns a list of the distinct values for the specified field in the database.
3175    
3176    =back
3177    
3178    =cut
3179    
3180    sub GetChoices {
3181        # Get the parameters.
3182        my ($self, $entityName, $fieldName) = @_;
3183        # Declare the return variable.
3184        my @retVal;
3185        # Get the entity data structure.
3186        my $entityData = $self->_GetStructure($entityName);
3187        # Get the field.
3188        my $fieldHash = $entityData->{Fields};
3189        if (! exists $fieldHash->{$fieldName}) {
3190            Confess("$fieldName not found in $entityName.");
3191        } else {
3192            # Get the name of the relation containing the field.
3193            my $relation = $fieldHash->{$fieldName}->{relation};
3194            # Fix up the field name.
3195            my $realName = _FixName($fieldName);
3196            # Get the database handle.
3197            my $dbh = $self->{_dbh};
3198            # Query the database.
3199            my $results = $dbh->SQL("SELECT DISTINCT $realName FROM $relation");
3200            # Clean the results. They are stored as a list of lists, and we just want the one list.
3201            @retVal = sort map { $_->[0] } @{$results};
3202        }
3203        # Return the result.
3204        return @retVal;
3205    }
3206    
3207    =head3 GetEntityValues
3208    
3209        my @values = $erdb->GetEntityValues($entityType, $ID, \@fields);
3210    
3211    Return a list of values from a specified entity instance. If the entity instance
3212    does not exist, an empty list is returned.
3213    
3214    =over 4
3215    
3216    =item entityType
3217    
3218    Entity type name.
3219    
3220    =item ID
3221    
3222    ID of the desired entity.
3223    
3224    =item fields
3225    
3226    List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.
3227    
3228    =item RETURN
3229    
3230    Returns a flattened list of the values of the specified fields for the specified entity.
3231    
3232    =back
3233    
3234    =cut
3235    
3236    sub GetEntityValues {
3237        # Get the parameters.
3238        my ($self, $entityType, $ID, $fields) = @_;
3239        # Get the specified entity.
3240        my $entity = $self->GetEntity($entityType, $ID);
3241        # Declare the return list.
3242        my @retVal = ();
3243        # If we found the entity, push the values into the return list.
3244        if ($entity) {
3245            push @retVal, $entity->Values($fields);
3246                  }                  }
3247        # Return the result.
3248        return @retVal;
3249          }          }
3250          Trace("SQL query: $command") if T(2);  
3251          Trace("PARMS: '" . (join "', '", @params) . "'") if (T(3) && (@params > 0));  =head3 GetAll
3252          my $sth = $dbh->prepare_command($command);  
3253          # Execute it with the parameters bound in.      my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);
3254          $sth->execute(@params) || Confess("SELECT error" . $sth->errstr());  
3255          # Return the statement object.  Return a list of values taken from the objects returned by a query. The first three
3256          my $retVal = DBQuery::_new($self, $sth, @{$objectNames});  parameters correspond to the parameters of the L</Get> method. The final parameter is
3257    a list of the fields desired from each record found by the query. The field name
3258    syntax is the standard syntax used for fields in the B<ERDB> system--
3259    B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity
3260    or relationship and I<fieldName> is the name of the field.
3261    
3262    The list returned will be a list of lists. Each element of the list will contain
3263    the values returned for the fields specified in the fourth parameter. If one of the
3264    fields specified returns multiple values, they are flattened in with the rest. For
3265    example, the following call will return a list of the features in a particular
3266    spreadsheet cell, and each feature will be represented by a list containing the
3267    feature ID followed by all of its essentiality determinations.
3268    
3269        @query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(essential)']);
3270    
3271    =over 4
3272    
3273    =item objectNames
3274    
3275    List containing the names of the entity and relationship objects to be retrieved.
3276    
3277    =item filterClause
3278    
3279    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
3280    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
3281    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
3282    parameter list as additional parameters. The fields in a filter clause can come from primary
3283    entity relations, relationship relations, or secondary entity relations; however, all of the
3284    entities and relationships involved must be included in the list of object names.
3285    
3286    =item parameterList
3287    
3288    List of the parameters to be substituted in for the parameters marks in the filter clause.
3289    
3290    =item fields
3291    
3292    List of the fields to be returned in each element of the list returned.
3293    
3294    =item count
3295    
3296    Maximum number of records to return. If omitted or 0, all available records will be returned.
3297    
3298    =item RETURN
3299    
3300    Returns a list of list references. Each element of the return list contains the values for the
3301    fields specified in the B<fields> parameter.
3302    
3303    =back
3304    
3305    =cut
3306    #: Return Type @@;
3307    sub GetAll {
3308        # Get the parameters.
3309        my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
3310        # Translate the parameters from a list reference to a list. If the parameter
3311        # list is a scalar we convert it into a singleton list.
3312        my @parmList = ();
3313        if (ref $parameterList eq "ARRAY") {
3314            Trace("GetAll parm list is an array.") if T(4);
3315            @parmList = @{$parameterList};
3316        } else {
3317            Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
3318            push @parmList, $parameterList;
3319        }
3320        # Insure the counter has a value.
3321        if (!defined $count) {
3322            $count = 0;
3323        }
3324        # Add the row limit to the filter clause.
3325        if ($count > 0) {
3326            $filterClause .= " LIMIT $count";
3327        }
3328        # Create the query.
3329        my $query = $self->Get($objectNames, $filterClause, \@parmList);
3330        # Set up a counter of the number of records read.
3331        my $fetched = 0;
3332        # Loop through the records returned, extracting the fields. Note that if the
3333        # counter is non-zero, we stop when the number of records read hits the count.
3334        my @retVal = ();
3335        while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
3336            my @rowData = $row->Values($fields);
3337            push @retVal, \@rowData;
3338            $fetched++;
3339        }
3340        Trace("$fetched rows returned in GetAll.") if T(SQL => 4);
3341        # Return the resulting list.
3342        return @retVal;
3343    }
3344    
3345    =head3 Exists
3346    
3347        my $found = $sprout->Exists($entityName, $entityID);
3348    
3349    Return TRUE if an entity exists, else FALSE.
3350    
3351    =over 4
3352    
3353    =item entityName
3354    
3355    Name of the entity type (e.g. C<Feature>) relevant to the existence check.
3356    
3357    =item entityID
3358    
3359    ID of the entity instance whose existence is to be checked.
3360    
3361    =item RETURN
3362    
3363    Returns TRUE if the entity instance exists, else FALSE.
3364    
3365    =back
3366    
3367    =cut
3368    #: Return Type $;
3369    sub Exists {
3370        # Get the parameters.
3371        my ($self, $entityName, $entityID) = @_;
3372        # Check for the entity instance.
3373        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
3374        my $testInstance = $self->GetEntity($entityName, $entityID);
3375        # Return an existence indicator.
3376        my $retVal = ($testInstance ? 1 : 0);
3377        return $retVal;
3378    }
3379    
3380    =head3 EstimateRowSize
3381    
3382        my $rowSize = $erdb->EstimateRowSize($relName);
3383    
3384    Estimate the row size of the specified relation. The estimated row size is computed by adding
3385    up the average length for each data type.
3386    
3387    =over 4
3388    
3389    =item relName
3390    
3391    Name of the relation whose estimated row size is desired.
3392    
3393    =item RETURN
3394    
3395    Returns an estimate of the row size for the specified relation.
3396    
3397    =back
3398    
3399    =cut
3400    #: Return Type $;
3401    sub EstimateRowSize {
3402        # Get the parameters.
3403        my ($self, $relName) = @_;
3404        # Declare the return variable.
3405        my $retVal = 0;
3406        # Find the relation descriptor.
3407        my $relation = $self->_FindRelation($relName);
3408        # Get the list of fields.
3409        for my $fieldData (@{$relation->{Fields}}) {
3410            # Get the field type and add its length.
3411            my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};