Schema.pm 114 KB
Newer Older
1 2 3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
#
5 6
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.
7 8 9 10 11 12 13 14 15 16 17

package Bugzilla::DB::Schema;

###########################################################################
#
# Purpose: Object-oriented, DBMS-independent database schema for Bugzilla
#
# This is the base class implementing common methods and abstract schema.
#
###########################################################################

18
use 5.10.1;
19
use strict;
20
use warnings;
21

22
use Bugzilla::Error;
23
use Bugzilla::Hook;
24
use Bugzilla::Util;
25
use Bugzilla::Constants;
26

27
use Carp qw(confess);
28
use Digest::MD5 qw(md5_hex);
29
use Hash::Util qw(lock_value unlock_hash lock_keys unlock_keys);
30
use List::MoreUtils qw(firstidx natatime);
31 32
use Safe;
# Historical, needed for SCHEMA_VERSION = '1.00'
33
use Storable qw(dclone freeze thaw);
34

35
# New SCHEMA_VERSIONs (2+) use this
36 37
use Data::Dumper;

38 39 40 41 42 43
# Whether or not this database can safely create FKs when doing a
# CREATE TABLE statement. This is false for most DBs, because they
# prevent you from creating FKs on tables and columns that don't
# yet exist. (However, in SQLite it's 1 because SQLite allows that.)
use constant FK_ON_CREATE => 0;

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
=head1 NAME

Bugzilla::DB::Schema - Abstract database schema for Bugzilla

=head1 SYNOPSIS

  # Obtain MySQL database schema.
  # Do not do this. Use Bugzilla::DB instead.
  use Bugzilla::DB::Schema;
  my $mysql_schema = new Bugzilla::DB::Schema('Mysql');

  # Recommended way to obtain database schema.
  use Bugzilla::DB;
  my $dbh = Bugzilla->dbh;
  my $schema = $dbh->_bz_schema();

  # Get the list of tables in the Bugzilla database.
  my @tables = $schema->get_table_list();

  # Get the SQL statements need to create the bugs table.
  my @statements = $schema->get_table_ddl('bugs');

  # Get the database-specific SQL data type used to implement
  # the abstract data type INT1.
  my $db_specific_type = $schema->sql_type('INT1');

=head1 DESCRIPTION

This module implements an object-oriented, abstract database schema.
It should be considered package-private to the Bugzilla::DB module.
74 75 76
That means that CGI scripts should never call any function in this
module directly, but should instead rely on methods provided by
Bugzilla::DB.
77

78 79 80 81 82 83 84
=head1 NEW TO SCHEMA.PM?

If this is your first time looking at Schema.pm, especially if
you are making changes to the database, please take a look at
L<http://www.bugzilla.org/docs/developer.html#sql-schema> to learn
more about how this integrates into the rest of Bugzilla.

85
=cut
86

87 88 89 90 91
#--------------------------------------------------------------------------
# Define the Bugzilla abstract database schema and version as constants.

=head1 CONSTANTS

92 93
=over

94 95 96 97
=item C<SCHEMA_VERSION>

The 'version' of the internal schema structure. This version number
is incremented every time the the fundamental structure of Schema
98
internals changes.
99 100 101 102 103 104

This is NOT changed every time a table or a column is added. This 
number is incremented only if the internal structures of this 
Schema would be incompatible with the internal structures of a 
previous Schema version.

105 106 107
In general, unless you are messing around with serialization
and deserialization of the schema, you don't need to worry about
this constant.
108

109
=begin private
110

111
An example of the use of the version number:
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
Today, we store all individual columns like this:

column_name => { TYPE => 'SOMETYPE', NOTNULL => 1 }

Imagine that someday we decide that NOTNULL => 1 is bad, and we want
to change it so that the schema instead uses NULL => 0.

But we have a bunch of Bugzilla installations around the world with a
serialized schema that has NOTNULL in it! When we deserialize that 
structure, it just WILL NOT WORK properly inside of our new Schema object.
So, immediately after deserializing, we need to go through the hash 
and change all NOTNULLs to NULLs and so on.

We know that we need to do that on deserializing because we know that
version 1.00 used NOTNULL. Having made the change to NULL, we would now
be version 1.01.

=end private
131 132 133 134 135

=item C<ABSTRACT_SCHEMA>

The abstract database schema structure consists of a hash reference
in which each key is the name of a table in the Bugzilla database.
136

137 138
The value for each key is a hash reference containing the keys
C<FIELDS> and C<INDEXES> which in turn point to array references
139 140 141 142 143 144 145 146 147 148 149
containing information on the table's fields and indexes. 

A field hash reference should must contain the key C<TYPE>. Optional field
keys include C<PRIMARYKEY>, C<NOTNULL>, and C<DEFAULT>. 

The C<INDEXES> array reference contains index names and information 
regarding the index. If the index name points to an array reference,
then the index is a regular index and the array contains the indexed
columns. If the index name points to a hash reference, then the hash
must contain the key C<FIELDS>. It may also contain the key C<TYPE>,
which can be used to specify the type of index such as UNIQUE or FULLTEXT.
150 151 152

=back

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
=head2 Referential Integrity

Bugzilla::DB::Schema supports "foreign keys", a way of saying
that "Column X may only contain values from Column Y in Table Z".
For example, in Bugzilla, bugs.resolution should only contain
values from the resolution.values field.

It does this by adding an additional item to a column, called C<REFERENCES>.
This is a hash with the following members:

=over

=item C<TABLE>

The table the foreign key points at

=item C<COLUMN>

The column pointed at in that table.

=item C<DELETE>

What to do if the row in the parent table is deleted. Choices are
176
C<RESTRICT>, C<CASCADE>, or C<SET NULL>. 
177 178 179 180 181 182 183 184

C<RESTRICT> means the deletion of the row in the parent table will 
be forbidden by the database if there is a row in I<this> table that 
still refers to it. This is the default, if you don't specify
C<DELETE>.

C<CASCADE> means that this row will be deleted along with that row.

185 186 187 188
C<SET NULL> means that the column will be set to C<NULL> when the parent
row is deleted. Note that this is only valid if the column can actually
be set to C<NULL>. (That is, the column isn't C<NOT NULL>.)

189 190
=item C<UPDATE>

191 192 193 194
What to do if the value in the parent table is updated. You can set this
to C<CASCADE> or C<RESTRICT>, which mean the same thing as they do for
L</DELETE>. This variable defaults to C<CASCADE>, which means "also 
update this column in this table."
195 196 197

=back

198 199
=cut

200
use constant SCHEMA_VERSION  => 3;
201
use constant ADD_COLUMN      => 'ADD COLUMN';
202 203 204
# Multiple FKs can be added using ALTER TABLE ADD CONSTRAINT in one
# SQL statement. This isn't true for all databases.
use constant MULTIPLE_FKS_IN_ALTER => 1;
205 206
# This is a reasonable default that's true for both PostgreSQL and MySQL.
use constant MAX_IDENTIFIER_LEN => 63;
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

use constant FIELD_TABLE_SCHEMA => {
    FIELDS => [
        id       => {TYPE => 'SMALLSERIAL', NOTNULL => 1,
                     PRIMARYKEY => 1},
        value    => {TYPE => 'varchar(64)', NOTNULL => 1},
        sortkey  => {TYPE => 'INT2', NOTNULL => 1, DEFAULT => 0},
        isactive => {TYPE => 'BOOLEAN', NOTNULL => 1,
                     DEFAULT => 'TRUE'},
        visibility_value_id => {TYPE => 'INT2'},
    ],
    # Note that bz_add_field_table should prepend the table name
    # to these index names.
    INDEXES => [
        value_idx   => {FIELDS => ['value'], TYPE => 'UNIQUE'},
        sortkey_idx => ['sortkey', 'value'],
        visibility_value_id_idx => ['visibility_value_id'],
    ],
};

227 228 229 230 231 232 233 234 235 236 237
use constant ABSTRACT_SCHEMA => {

    # BUG-RELATED TABLES
    # ------------------

    # General Bug Information
    # -----------------------
    bugs => {
        FIELDS => [
            bug_id              => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
                                    PRIMARYKEY => 1},
238 239 240
            assigned_to         => {TYPE => 'INT3', NOTNULL => 1,
                                    REFERENCES => {TABLE  => 'profiles',
                                                   COLUMN => 'userid'}},
241 242
            bug_file_loc        => {TYPE => 'MEDIUMTEXT', 
                                    NOTNULL => 1, DEFAULT => "''"},
243 244
            bug_severity        => {TYPE => 'varchar(64)', NOTNULL => 1},
            bug_status          => {TYPE => 'varchar(64)', NOTNULL => 1},
245
            creation_ts         => {TYPE => 'DATETIME'},
246
            delta_ts            => {TYPE => 'DATETIME', NOTNULL => 1},
247
            short_desc          => {TYPE => 'varchar(255)', NOTNULL => 1},
248 249
            op_sys              => {TYPE => 'varchar(64)', NOTNULL => 1},
            priority            => {TYPE => 'varchar(64)', NOTNULL => 1},
250 251 252
            product_id          => {TYPE => 'INT2', NOTNULL => 1,
                                    REFERENCES => {TABLE  => 'products',
                                                   COLUMN => 'id'}},
253
            rep_platform        => {TYPE => 'varchar(64)', NOTNULL => 1},
254 255 256
            reporter            => {TYPE => 'INT3', NOTNULL => 1,
                                    REFERENCES => {TABLE  => 'profiles',
                                                   COLUMN => 'userid'}},
257
            version             => {TYPE => 'varchar(64)', NOTNULL => 1},
258
            component_id        => {TYPE => 'INT3', NOTNULL => 1,
259 260
                                    REFERENCES => {TABLE  => 'components',
                                                   COLUMN => 'id'}},
261 262
            resolution          => {TYPE => 'varchar(64)',
                                    NOTNULL => 1, DEFAULT => "''"},
263
            target_milestone    => {TYPE => 'varchar(64)',
264
                                    NOTNULL => 1, DEFAULT => "'---'"},
265
            qa_contact          => {TYPE => 'INT3',
266 267
                                    REFERENCES => {TABLE  => 'profiles',
                                                   COLUMN => 'userid'}},
268 269
            status_whiteboard   => {TYPE => 'MEDIUMTEXT', NOTNULL => 1,
                                    DEFAULT => "''"},
270
            lastdiffed          => {TYPE => 'DATETIME'},
271 272 273 274 275
            everconfirmed       => {TYPE => 'BOOLEAN', NOTNULL => 1},
            reporter_accessible => {TYPE => 'BOOLEAN',
                                    NOTNULL => 1, DEFAULT => 'TRUE'},
            cclist_accessible   => {TYPE => 'BOOLEAN',
                                    NOTNULL => 1, DEFAULT => 'TRUE'},
276
            estimated_time      => {TYPE => 'decimal(7,2)',
277
                                    NOTNULL => 1, DEFAULT => '0'},
278
            remaining_time      => {TYPE => 'decimal(7,2)',
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
                                    NOTNULL => 1, DEFAULT => '0'},
            deadline            => {TYPE => 'DATETIME'},
        ],
        INDEXES => [
            bugs_assigned_to_idx      => ['assigned_to'],
            bugs_creation_ts_idx      => ['creation_ts'],
            bugs_delta_ts_idx         => ['delta_ts'],
            bugs_bug_severity_idx     => ['bug_severity'],
            bugs_bug_status_idx       => ['bug_status'],
            bugs_op_sys_idx           => ['op_sys'],
            bugs_priority_idx         => ['priority'],
            bugs_product_id_idx       => ['product_id'],
            bugs_reporter_idx         => ['reporter'],
            bugs_version_idx          => ['version'],
            bugs_component_id_idx     => ['component_id'],
            bugs_resolution_idx       => ['resolution'],
            bugs_target_milestone_idx => ['target_milestone'],
            bugs_qa_contact_idx       => ['qa_contact'],
        ],
    },

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    bugs_fulltext => {
        FIELDS => [
            bug_id     => {TYPE => 'INT3', NOTNULL => 1, PRIMARYKEY => 1,
                           REFERENCES => {TABLE  => 'bugs',
                                          COLUMN => 'bug_id',
                                          DELETE => 'CASCADE'}},
            short_desc => {TYPE => 'varchar(255)', NOTNULL => 1},
            # Comments are stored all together in one column for searching.
            # This allows us to examine all comments together when deciding
            # the relevance of a bug in fulltext search.
            comments   => {TYPE => 'LONGTEXT'},
            comments_noprivate => {TYPE => 'LONGTEXT'},
        ],
        INDEXES => [
            bugs_fulltext_short_desc_idx => {FIELDS => ['short_desc'],
                                               TYPE => 'FULLTEXT'},
            bugs_fulltext_comments_idx   => {FIELDS => ['comments'],
                                               TYPE => 'FULLTEXT'},
            bugs_fulltext_comments_noprivate_idx => {
                FIELDS => ['comments_noprivate'], TYPE => 'FULLTEXT'},
        ],
    },

323 324
    bugs_activity => {
        FIELDS => [
325
            id        => {TYPE => 'INTSERIAL', NOTNULL => 1, 
326
                          PRIMARYKEY => 1}, 
327 328 329 330 331 332 333 334
            bug_id    => {TYPE => 'INT3', NOTNULL => 1,
                          REFERENCES    =>  {TABLE  =>  'bugs',
                                             COLUMN =>  'bug_id',
                                             DELETE => 'CASCADE'}},
            attach_id => {TYPE => 'INT3',
                          REFERENCES    =>  {TABLE  =>  'attachments',
                                            COLUMN  =>  'attach_id',
                                            DELETE => 'CASCADE'}},
335 336 337
            who       => {TYPE => 'INT3', NOTNULL => 1,
                          REFERENCES => {TABLE  => 'profiles',
                                         COLUMN => 'userid'}},
338
            bug_when  => {TYPE => 'DATETIME', NOTNULL => 1},
339 340 341
            fieldid   => {TYPE => 'INT3', NOTNULL => 1,
                          REFERENCES    =>  {TABLE  =>  'fielddefs',
                                             COLUMN =>  'id'}},
342
            added     => {TYPE => 'varchar(255)'},
343
            removed   => {TYPE => 'varchar(255)'},
344
            comment_id => {TYPE => 'INT4', 
345 346 347
                           REFERENCES => { TABLE  => 'longdescs',
                                           COLUMN => 'comment_id',
                                           DELETE => 'CASCADE'}},
348 349
        ],
        INDEXES => [
350
            bugs_activity_bug_id_idx  => ['bug_id'],
351
            bugs_activity_who_idx     => ['who'],
352
            bugs_activity_bug_when_idx => ['bug_when'],
353
            bugs_activity_fieldid_idx => ['fieldid'],
354
            bugs_activity_added_idx   => ['added'],
355
            bugs_activity_removed_idx => ['removed'], 
356 357 358
        ],
    },

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    bugs_aliases => {
        FIELDS => [
            alias     => {TYPE => 'varchar(40)', NOTNULL => 1},
            bug_id    => {TYPE => 'INT3',
                          REFERENCES => {TABLE  => 'bugs',
                                         COLUMN => 'bug_id',
                                         DELETE => 'CASCADE'}},
        ],
        INDEXES => [
            bugs_aliases_bug_id_idx => ['bug_id'],
            bugs_aliases_alias_idx  => {FIELDS => ['alias'],
                                        TYPE => 'UNIQUE'},
        ],
    },

374 375
    cc => {
        FIELDS => [
376 377 378 379
            bug_id => {TYPE => 'INT3', NOTNULL => 1,
                       REFERENCES => {TABLE  => 'bugs',
                                      COLUMN => 'bug_id',
                                      DELETE => 'CASCADE'}},
380 381 382 383
            who    => {TYPE => 'INT3', NOTNULL => 1,
                       REFERENCES => {TABLE  => 'profiles',
                                      COLUMN => 'userid',
                                      DELETE => 'CASCADE'}},
384 385
        ],
        INDEXES => [
386
            cc_bug_id_idx => {FIELDS => [qw(bug_id who)],
387 388 389 390 391 392 393
                              TYPE => 'UNIQUE'},
            cc_who_idx    => ['who'],
        ],
    },

    longdescs => {
        FIELDS => [
394
            comment_id      => {TYPE => 'INTSERIAL',  NOTNULL => 1,
395
                                PRIMARYKEY => 1},
396 397 398 399 400 401
            bug_id          => {TYPE => 'INT3',  NOTNULL => 1,
                                REFERENCES => {TABLE => 'bugs',
                                               COLUMN => 'bug_id',
                                               DELETE => 'CASCADE'}},
            who             => {TYPE => 'INT3', NOTNULL => 1,
                                REFERENCES => {TABLE => 'profiles',
402
                                               COLUMN => 'userid'}},
403
            bug_when        => {TYPE => 'DATETIME', NOTNULL => 1},
404
            work_time       => {TYPE => 'decimal(7,2)', NOTNULL => 1,
405
                                DEFAULT => '0'},
406
            thetext         => {TYPE => 'LONGTEXT', NOTNULL => 1},
407 408 409 410
            isprivate       => {TYPE => 'BOOLEAN', NOTNULL => 1,
                                DEFAULT => 'FALSE'},
            already_wrapped => {TYPE => 'BOOLEAN', NOTNULL => 1,
                                DEFAULT => 'FALSE'},
411 412
            type            => {TYPE => 'INT2', NOTNULL => 1,
                                DEFAULT => '0'},
413
            extra_data      => {TYPE => 'varchar(255)'}
414 415
        ],
        INDEXES => [
416
            longdescs_bug_id_idx   => [qw(bug_id work_time)],
417
            longdescs_who_idx     => [qw(who bug_id)],
418
            longdescs_bug_when_idx => ['bug_when'],
419 420 421
        ],
    },

422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
    longdescs_tags => {
        FIELDS => [
            id         => { TYPE => 'MEDIUMSERIAL', NOTNULL => 1, PRIMARYKEY => 1 },
            comment_id => { TYPE => 'INT4',
                            REFERENCES => { TABLE  => 'longdescs',
                                            COLUMN => 'comment_id',
                                            DELETE => 'CASCADE' }},
            tag        => { TYPE => 'varchar(24)',  NOTNULL => 1 },
        ],
        INDEXES => [
            longdescs_tags_idx => { FIELDS => ['comment_id', 'tag'], TYPE => 'UNIQUE' },
        ],
    },

    longdescs_tags_weights => {
        FIELDS => [
            id     => { TYPE => 'MEDIUMSERIAL', NOTNULL => 1, PRIMARYKEY => 1 },
            tag    => { TYPE => 'varchar(24)',  NOTNULL => 1 },
            weight => { TYPE => 'INT3',         NOTNULL => 1 },
        ],
        INDEXES => [
            longdescs_tags_weights_tag_idx => { FIELDS => ['tag'], TYPE => 'UNIQUE' },
        ],
    },

    longdescs_tags_activity => {
        FIELDS => [
            id         => { TYPE => 'MEDIUMSERIAL', NOTNULL => 1, PRIMARYKEY => 1 },
            bug_id     => { TYPE => 'INT3', NOTNULL => 1,
                            REFERENCES =>  { TABLE  =>  'bugs',
                                             COLUMN =>  'bug_id',
                                             DELETE => 'CASCADE' }},
            comment_id => { TYPE => 'INT4',
                            REFERENCES => { TABLE  => 'longdescs',
                                            COLUMN => 'comment_id',
                                            DELETE => 'CASCADE' }},
            who        => { TYPE => 'INT3', NOTNULL => 1,
                            REFERENCES => { TABLE  => 'profiles',
                                            COLUMN => 'userid' }},
            bug_when  => { TYPE => 'DATETIME', NOTNULL => 1 },
            added     => { TYPE => 'varchar(24)' },
            removed   => { TYPE => 'varchar(24)' },
        ],
        INDEXES => [
            longdescs_tags_activity_bug_id_idx  => ['bug_id'],
        ],
    },

470 471
    dependencies => {
        FIELDS => [
472 473 474 475 476 477 478 479
            blocked   => {TYPE => 'INT3', NOTNULL => 1,
                          REFERENCES    =>  {TABLE  =>   'bugs',
                                            COLUMN  =>  'bug_id',
                                            DELETE => 'CASCADE'}},
            dependson => {TYPE => 'INT3', NOTNULL => 1,
                          REFERENCES    =>  {TABLE  =>   'bugs',
                                            COLUMN  =>  'bug_id',
                                            DELETE => 'CASCADE'}},
480 481
        ],
        INDEXES => [
482 483
            dependencies_blocked_idx => {FIELDS => [qw(blocked dependson)],
                                         TYPE   => 'UNIQUE'},
484 485 486 487 488 489 490 491
            dependencies_dependson_idx => ['dependson'],
        ],
    },

    attachments => {
        FIELDS => [
            attach_id    => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
                             PRIMARYKEY => 1},
492 493 494 495
            bug_id       => {TYPE => 'INT3', NOTNULL => 1,
                             REFERENCES    =>  {TABLE  => 'bugs',
                                                COLUMN => 'bug_id',
                                                DELETE => 'CASCADE'}},
496
            creation_ts  => {TYPE => 'DATETIME', NOTNULL => 1},
497
            modification_time => {TYPE => 'DATETIME', NOTNULL => 1},
498 499
            description  => {TYPE => 'TINYTEXT', NOTNULL => 1},
            mimetype     => {TYPE => 'TINYTEXT', NOTNULL => 1},
500 501
            ispatch      => {TYPE => 'BOOLEAN', NOTNULL => 1,
                             DEFAULT => 'FALSE'},
502
            filename     => {TYPE => 'varchar(255)', NOTNULL => 1},
503 504 505
            submitter_id => {TYPE => 'INT3', NOTNULL => 1,
                             REFERENCES => {TABLE => 'profiles',
                                            COLUMN => 'userid'}},
506 507 508 509 510 511 512 513
            isobsolete   => {TYPE => 'BOOLEAN', NOTNULL => 1,
                             DEFAULT => 'FALSE'},
            isprivate    => {TYPE => 'BOOLEAN', NOTNULL => 1,
                             DEFAULT => 'FALSE'},
        ],
        INDEXES => [
            attachments_bug_id_idx => ['bug_id'],
            attachments_creation_ts_idx => ['creation_ts'],
514
            attachments_modification_time_idx => ['modification_time'],
515
            attachments_submitter_id_idx => ['submitter_id', 'bug_id'],
516 517
        ],
    },
518 519 520
    attach_data => {
        FIELDS => [
            id      => {TYPE => 'INT3', NOTNULL => 1,
521 522 523 524
                        PRIMARYKEY => 1,
                        REFERENCES  =>  {TABLE  => 'attachments',
                                         COLUMN => 'attach_id',
                                         DELETE => 'CASCADE'}},
525 526 527
            thedata => {TYPE => 'LONGBLOB', NOTNULL => 1},
        ],
    },
528 529 530

    duplicates => {
        FIELDS => [
531 532 533 534
            dupe_of => {TYPE => 'INT3', NOTNULL => 1,
                        REFERENCES => {TABLE  =>  'bugs',
                                       COLUMN =>  'bug_id',
                                       DELETE =>  'CASCADE'}},
535
            dupe    => {TYPE => 'INT3', NOTNULL => 1,
536 537 538 539
                        PRIMARYKEY => 1,
                        REFERENCES => {TABLE  =>  'bugs',
                                       COLUMN =>  'bug_id',
                                       DELETE =>  'CASCADE'}},
540 541 542
        ],
    },

543 544
    bug_see_also => {
        FIELDS => [
545 546
            id     => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
                       PRIMARYKEY => 1},
547 548 549 550
            bug_id => {TYPE => 'INT3', NOTNULL => 1,
                       REFERENCES => {TABLE  => 'bugs',
                                      COLUMN => 'bug_id',
                                      DELETE => 'CASCADE'}},
551
            value  => {TYPE => 'varchar(255)', NOTNULL => 1},
552
            class  => {TYPE => 'varchar(255)', NOTNULL => 1, DEFAULT => "''"},
553 554 555 556 557 558 559
        ],
        INDEXES => [
            bug_see_also_bug_id_idx => {FIELDS => [qw(bug_id value)], 
                                        TYPE   => 'UNIQUE'},
        ],
    },

560 561 562 563 564 565 566
    # Auditing
    # --------

    audit_log => {
        FIELDS => [
            user_id   => {TYPE => 'INT3',
                          REFERENCES => {TABLE  => 'profiles',
567 568
                                         COLUMN => 'userid',
                                         DELETE => 'SET NULL'}},
569 570 571 572 573 574 575
            class     => {TYPE => 'varchar(255)', NOTNULL => 1},
            object_id => {TYPE => 'INT4', NOTNULL => 1},
            field     => {TYPE => 'varchar(64)', NOTNULL => 1},
            removed   => {TYPE => 'MEDIUMTEXT'},
            added     => {TYPE => 'MEDIUMTEXT'},
            at_time   => {TYPE => 'DATETIME', NOTNULL => 1},
        ],
576 577 578
        INDEXES => [
                    audit_log_class_idx => ['class', 'at_time'],
        ],
579 580
    },

581 582 583 584 585
    # Keywords
    # --------

    keyworddefs => {
        FIELDS => [
586
            id          => {TYPE => 'SMALLSERIAL', NOTNULL => 1,
587 588
                            PRIMARYKEY => 1},
            name        => {TYPE => 'varchar(64)', NOTNULL => 1},
589
            description => {TYPE => 'MEDIUMTEXT', NOTNULL => 1},
590 591
        ],
        INDEXES => [
592
            keyworddefs_name_idx   => {FIELDS => ['name'],
593 594 595 596 597 598
                                       TYPE => 'UNIQUE'},
        ],
    },

    keywords => {
        FIELDS => [
599 600 601 602 603 604 605 606 607
            bug_id    => {TYPE => 'INT3', NOTNULL => 1,
                          REFERENCES => {TABLE  => 'bugs',
                                         COLUMN => 'bug_id',
                                         DELETE => 'CASCADE'}},
            keywordid => {TYPE => 'INT2', NOTNULL => 1,
                          REFERENCES => {TABLE  => 'keyworddefs',
                                         COLUMN => 'id',
                                         DELETE => 'CASCADE'}},

608 609
        ],
        INDEXES => [
610
            keywords_bug_id_idx    => {FIELDS => [qw(bug_id keywordid)],
611 612 613 614 615 616 617 618 619 620 621
                                       TYPE => 'UNIQUE'},
            keywords_keywordid_idx => ['keywordid'],
        ],
    },

    # Flags
    # -----

    # "flags" stores one record for each flag on each bug/attachment.
    flags => {
        FIELDS => [
622
            id                => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
623
                                  PRIMARYKEY => 1},
624 625 626 627
            type_id           => {TYPE => 'INT2', NOTNULL => 1,
                                  REFERENCES => {TABLE  => 'flagtypes',
                                                 COLUMN => 'id',
                                                 DELETE => 'CASCADE'}},
628
            status            => {TYPE => 'char(1)', NOTNULL => 1},
629 630 631 632 633 634 635 636
            bug_id            => {TYPE => 'INT3', NOTNULL => 1,
                                  REFERENCES => {TABLE  => 'bugs',
                                                 COLUMN => 'bug_id',
                                                 DELETE => 'CASCADE'}},
            attach_id         => {TYPE => 'INT3',
                                  REFERENCES => {TABLE  => 'attachments',
                                                 COLUMN => 'attach_id',
                                                 DELETE => 'CASCADE'}},
637 638
            creation_date     => {TYPE => 'DATETIME', NOTNULL => 1},
            modification_date => {TYPE => 'DATETIME'},
639
            setter_id         => {TYPE => 'INT3', NOTNULL => 1,
640 641 642 643 644
                                  REFERENCES => {TABLE  => 'profiles',
                                                 COLUMN => 'userid'}},
            requestee_id      => {TYPE => 'INT3',
                                  REFERENCES => {TABLE  => 'profiles',
                                                 COLUMN => 'userid'}},
645 646
        ],
        INDEXES => [
647
            flags_bug_id_idx       => [qw(bug_id attach_id)],
648 649
            flags_setter_id_idx    => ['setter_id'],
            flags_requestee_id_idx => ['requestee_id'],
650
            flags_type_id_idx      => ['type_id'],
651 652 653 654 655 656
        ],
    },

    # "flagtypes" defines the types of flags that can be set.
    flagtypes => {
        FIELDS => [
657
            id               => {TYPE => 'SMALLSERIAL', NOTNULL => 1,
658 659
                                 PRIMARYKEY => 1},
            name             => {TYPE => 'varchar(50)', NOTNULL => 1},
660
            description      => {TYPE => 'MEDIUMTEXT', NOTNULL => 1},
661 662 663 664 665 666 667 668 669 670 671 672 673
            cc_list          => {TYPE => 'varchar(200)'},
            target_type      => {TYPE => 'char(1)', NOTNULL => 1,
                                 DEFAULT => "'b'"},
            is_active        => {TYPE => 'BOOLEAN', NOTNULL => 1,
                                 DEFAULT => 'TRUE'},
            is_requestable   => {TYPE => 'BOOLEAN', NOTNULL => 1,
                                 DEFAULT => 'FALSE'},
            is_requesteeble  => {TYPE => 'BOOLEAN', NOTNULL => 1,
                                 DEFAULT => 'FALSE'},
            is_multiplicable => {TYPE => 'BOOLEAN', NOTNULL => 1,
                                 DEFAULT => 'FALSE'},
            sortkey          => {TYPE => 'INT2', NOTNULL => 1,
                                 DEFAULT => '0'},
674 675
            grant_group_id   => {TYPE => 'INT3',
                                 REFERENCES => {TABLE  => 'groups',
676 677
                                                COLUMN => 'id',
                                                DELETE => 'SET NULL'}},
678 679
            request_group_id => {TYPE => 'INT3',
                                 REFERENCES => {TABLE  => 'groups',
680 681
                                                COLUMN => 'id',
                                                DELETE => 'SET NULL'}},
682 683 684 685 686 687 688 689
        ],
    },

    # "flaginclusions" and "flagexclusions" specify the products/components
    #     a bug/attachment must belong to in order for flags of a given type
    #     to be set for them.
    flaginclusions => {
        FIELDS => [
690 691 692 693 694 695 696 697
            type_id      => {TYPE => 'INT2', NOTNULL => 1,
                             REFERENCES => {TABLE  => 'flagtypes',
                                            COLUMN => 'id',
                                            DELETE => 'CASCADE'}},
            product_id   => {TYPE => 'INT2',
                             REFERENCES => {TABLE  => 'products',
                                            COLUMN => 'id',
                                            DELETE => 'CASCADE'}},
698
            component_id => {TYPE => 'INT3',
699 700 701
                             REFERENCES => {TABLE  => 'components',
                                            COLUMN => 'id',
                                            DELETE => 'CASCADE'}},
702 703
        ],
        INDEXES => [
704 705
            flaginclusions_type_id_idx => { FIELDS => [qw(type_id product_id component_id)],
                                            TYPE   => 'UNIQUE' },
706 707 708 709 710
        ],
    },

    flagexclusions => {
        FIELDS => [
711 712 713 714 715 716 717 718
            type_id      => {TYPE => 'INT2', NOTNULL => 1,
                             REFERENCES => {TABLE  => 'flagtypes',
                                            COLUMN => 'id',
                                            DELETE => 'CASCADE'}},
            product_id   => {TYPE => 'INT2',
                             REFERENCES => {TABLE  => 'products',
                                            COLUMN => 'id',
                                            DELETE => 'CASCADE'}},
719
            component_id => {TYPE => 'INT3',
720 721 722
                             REFERENCES => {TABLE  => 'components',
                                            COLUMN => 'id',
                                            DELETE => 'CASCADE'}},
723 724
        ],
        INDEXES => [
725 726
            flagexclusions_type_id_idx => { FIELDS => [qw(type_id product_id component_id)],
                                            TYPE   => 'UNIQUE' },
727 728 729 730 731 732 733 734
        ],
    },

    # General Field Information
    # -------------------------

    fielddefs => {
        FIELDS => [
735
            id          => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
736 737
                            PRIMARYKEY => 1},
            name        => {TYPE => 'varchar(64)', NOTNULL => 1},
738 739 740 741
            type        => {TYPE => 'INT2', NOTNULL => 1,
                            DEFAULT => FIELD_TYPE_UNKNOWN},
            custom      => {TYPE => 'BOOLEAN', NOTNULL => 1,
                            DEFAULT => 'FALSE'},
742
            description => {TYPE => 'TINYTEXT', NOTNULL => 1},
743
            long_desc   => {TYPE => 'varchar(255)', NOTNULL => 1, DEFAULT => "''"},
744 745 746 747 748
            mailhead    => {TYPE => 'BOOLEAN', NOTNULL => 1,
                            DEFAULT => 'FALSE'},
            sortkey     => {TYPE => 'INT2', NOTNULL => 1},
            obsolete    => {TYPE => 'BOOLEAN', NOTNULL => 1,
                            DEFAULT => 'FALSE'},
749 750
            enter_bug   => {TYPE => 'BOOLEAN', NOTNULL => 1,
                            DEFAULT => 'FALSE'},
751 752
            buglist     => {TYPE => 'BOOLEAN', NOTNULL => 1,
                            DEFAULT => 'FALSE'},
753 754 755
            visibility_field_id => {TYPE => 'INT3', 
                                    REFERENCES => {TABLE  => 'fielddefs',
                                                   COLUMN => 'id'}},
756 757 758
            value_field_id => {TYPE => 'INT3',
                               REFERENCES => {TABLE  => 'fielddefs',
                                              COLUMN => 'id'}},
759
            reverse_desc => {TYPE => 'TINYTEXT'},
760 761
            is_mandatory => {TYPE => 'BOOLEAN', NOTNULL => 1,
                             DEFAULT => 'FALSE'},
762 763
            is_numeric    => {TYPE => 'BOOLEAN', NOTNULL => 1,
                             DEFAULT => 'FALSE'},
764 765
        ],
        INDEXES => [
766
            fielddefs_name_idx    => {FIELDS => ['name'],
767 768
                                      TYPE => 'UNIQUE'},
            fielddefs_sortkey_idx => ['sortkey'],
769
            fielddefs_value_field_id_idx => ['value_field_id'],
770
            fielddefs_is_mandatory_idx => ['is_mandatory'],
771 772 773
        ],
    },

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
    # Field Visibility Information
    # -------------------------

    field_visibility => {
        FIELDS => [
            field_id => {TYPE => 'INT3', 
                         REFERENCES => {TABLE  => 'fielddefs',
                                        COLUMN => 'id',
                                        DELETE => 'CASCADE'}},
            value_id => {TYPE => 'INT2', NOTNULL => 1}
        ],
        INDEXES => [
            field_visibility_field_id_idx => {
                FIELDS => [qw(field_id value_id)],
                TYPE   => 'UNIQUE'
            },
        ],
    },

793 794 795 796 797
    # Per-product Field Values
    # ------------------------

    versions => {
        FIELDS => [
798 799
            id         =>  {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
                            PRIMARYKEY => 1},
800
            value      =>  {TYPE => 'varchar(64)', NOTNULL => 1},
801 802 803 804
            product_id =>  {TYPE => 'INT2', NOTNULL => 1,
                            REFERENCES => {TABLE  => 'products',
                                           COLUMN => 'id',
                                           DELETE => 'CASCADE'}},
805 806
            isactive   =>  {TYPE => 'BOOLEAN', NOTNULL => 1, 
                            DEFAULT => 'TRUE'},
807
        ],
808 809 810 811
        INDEXES => [
            versions_product_id_idx => {FIELDS => [qw(product_id value)],
                                        TYPE => 'UNIQUE'},
        ],
812 813 814 815
    },

    milestones => {
        FIELDS => [
816 817
            id         => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1, 
                           PRIMARYKEY => 1},
818 819 820 821
            product_id => {TYPE => 'INT2', NOTNULL => 1,
                           REFERENCES => {TABLE  => 'products',
                                          COLUMN => 'id',
                                          DELETE => 'CASCADE'}},
822
            value      => {TYPE => 'varchar(64)', NOTNULL => 1},
823 824
            sortkey    => {TYPE => 'INT2', NOTNULL => 1,
                           DEFAULT => 0},
825 826
            isactive   => {TYPE => 'BOOLEAN', NOTNULL => 1, 
                           DEFAULT => 'TRUE'},
827 828
        ],
        INDEXES => [
829 830
            milestones_product_id_idx => {FIELDS => [qw(product_id value)],
                                          TYPE => 'UNIQUE'},
831 832 833 834 835 836 837 838
        ],
    },

    # Global Field Values
    # -------------------

    bug_status => {
        FIELDS => [
839
            @{ dclone(FIELD_TABLE_SCHEMA->{FIELDS}) },
840
            is_open  => {TYPE => 'BOOLEAN', NOTNULL => 1, DEFAULT => 'TRUE'},
841

842 843
        ],
        INDEXES => [
844
            bug_status_value_idx  => {FIELDS => ['value'],
845 846
                                       TYPE => 'UNIQUE'},
            bug_status_sortkey_idx => ['sortkey', 'value'],
847
            bug_status_visibility_value_id_idx => ['visibility_value_id'],
848 849 850 851
        ],
    },

    resolution => {
852
        FIELDS => dclone(FIELD_TABLE_SCHEMA->{FIELDS}),
853
        INDEXES => [
854
            resolution_value_idx   => {FIELDS => ['value'],
855 856
                                       TYPE => 'UNIQUE'},
            resolution_sortkey_idx => ['sortkey', 'value'],
857
            resolution_visibility_value_id_idx => ['visibility_value_id'],
858 859 860 861
        ],
    },

    bug_severity => {
862
        FIELDS => dclone(FIELD_TABLE_SCHEMA->{FIELDS}),
863
        INDEXES => [
864
            bug_severity_value_idx   => {FIELDS => ['value'],
865 866
                                         TYPE => 'UNIQUE'},
            bug_severity_sortkey_idx => ['sortkey', 'value'],
867
            bug_severity_visibility_value_id_idx => ['visibility_value_id'],
868 869 870 871
        ],
    },

    priority => {
872
        FIELDS => dclone(FIELD_TABLE_SCHEMA->{FIELDS}),
873
        INDEXES => [
874
            priority_value_idx   => {FIELDS => ['value'],
875 876
                                     TYPE => 'UNIQUE'},
            priority_sortkey_idx => ['sortkey', 'value'],
877
            priority_visibility_value_id_idx => ['visibility_value_id'],
878 879 880 881
        ],
    },

    rep_platform => {
882
        FIELDS => dclone(FIELD_TABLE_SCHEMA->{FIELDS}),
883
        INDEXES => [
884
            rep_platform_value_idx   => {FIELDS => ['value'],
885 886
                                         TYPE => 'UNIQUE'},
            rep_platform_sortkey_idx => ['sortkey', 'value'],
887
            rep_platform_visibility_value_id_idx => ['visibility_value_id'],
888 889 890 891
        ],
    },

    op_sys => {
892
        FIELDS => dclone(FIELD_TABLE_SCHEMA->{FIELDS}),
893
        INDEXES => [
894
            op_sys_value_idx   => {FIELDS => ['value'],
895 896
                                   TYPE => 'UNIQUE'},
            op_sys_sortkey_idx => ['sortkey', 'value'],
897
            op_sys_visibility_value_id_idx => ['visibility_value_id'],
898 899 900
        ],
    },

901 902 903
    status_workflow => {
        FIELDS => [
            # On bug creation, there is no old value.
904 905 906 907 908 909 910 911
            old_status      => {TYPE => 'INT2',
                                REFERENCES => {TABLE  => 'bug_status', 
                                               COLUMN => 'id',
                                               DELETE => 'CASCADE'}},
            new_status      => {TYPE => 'INT2', NOTNULL => 1,
                                REFERENCES => {TABLE  => 'bug_status', 
                                               COLUMN => 'id',
                                               DELETE => 'CASCADE'}},
912 913 914 915 916 917 918 919
            require_comment => {TYPE => 'INT1', NOTNULL => 1, DEFAULT => 0},
        ],
        INDEXES => [
            status_workflow_idx  => {FIELDS => ['old_status', 'new_status'],
                                     TYPE => 'UNIQUE'},
        ],
    },

920 921 922 923 924 925 926 927 928 929 930 931
    # USER INFO
    # ---------

    # General User Information
    # ------------------------

    profiles => {
        FIELDS => [
            userid         => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
                               PRIMARYKEY => 1},
            login_name     => {TYPE => 'varchar(255)', NOTNULL => 1},
            cryptpassword  => {TYPE => 'varchar(128)'},
932 933 934 935
            realname       => {TYPE => 'varchar(255)', NOTNULL => 1,
                               DEFAULT => "''"},
            disabledtext   => {TYPE => 'MEDIUMTEXT', NOTNULL => 1,
                               DEFAULT => "''"},
936 937
            disable_mail   => {TYPE => 'BOOLEAN', NOTNULL => 1,
                               DEFAULT => 'FALSE'},
938 939 940
            mybugslink     => {TYPE => 'BOOLEAN', NOTNULL => 1,
                               DEFAULT => 'TRUE'},
            extern_id      => {TYPE => 'varchar(64)'},
941 942
            is_enabled     => {TYPE => 'BOOLEAN', NOTNULL => 1, 
                               DEFAULT => 'TRUE'}, 
943
            last_seen_date => {TYPE => 'DATETIME'},
944 945
        ],
        INDEXES => [
946 947
            profiles_login_name_idx => {FIELDS => ['login_name'],
                                        TYPE => 'UNIQUE'},
948 949
            profiles_extern_id_idx => {FIELDS => ['extern_id'],
                                       TYPE   => 'UNIQUE'}
950 951 952
        ],
    },

953 954 955
    profile_search => {
        FIELDS => [
            id         => {TYPE => 'INTSERIAL', NOTNULL => 1, PRIMARYKEY => 1},
956 957 958 959
            user_id    => {TYPE => 'INT3', NOTNULL => 1, 
                           REFERENCES => {TABLE  => 'profiles', 
                                          COLUMN => 'userid', 
                                          DELETE => 'CASCADE'}},
960 961 962 963
            bug_list   => {TYPE => 'MEDIUMTEXT', NOTNULL => 1},
            list_order => {TYPE => 'MEDIUMTEXT'},
        ],
        INDEXES => [
964
            profile_search_user_id_idx => [qw(user_id)],
965 966 967
        ],
    },

968 969
    profiles_activity => {
        FIELDS => [
970 971
            id            => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1, 
                              PRIMARYKEY => 1}, 
972 973 974 975 976 977 978
            userid        => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'profiles', 
                                             COLUMN => 'userid',
                                             DELETE => 'CASCADE'}},
            who           => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'profiles',
                                             COLUMN => 'userid'}},
979
            profiles_when => {TYPE => 'DATETIME', NOTNULL => 1},
980 981 982
            fieldid       => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'fielddefs',
                                             COLUMN => 'id'}},
983 984 985 986 987
            oldvalue      => {TYPE => 'TINYTEXT'},
            newvalue      => {TYPE => 'TINYTEXT'},
        ],
        INDEXES => [
            profiles_activity_userid_idx  => ['userid'],
988
            profiles_activity_profiles_when_idx => ['profiles_when'],
989 990 991 992
            profiles_activity_fieldid_idx => ['fieldid'],
        ],
    },

993 994
    email_setting => {
        FIELDS => [
995 996 997 998
            user_id      => {TYPE => 'INT3', NOTNULL => 1,
                             REFERENCES => {TABLE  => 'profiles',
                                            COLUMN => 'userid',
                                            DELETE => 'CASCADE'}},
999 1000 1001 1002
            relationship => {TYPE => 'INT1', NOTNULL => 1},
            event        => {TYPE => 'INT1', NOTNULL => 1},
        ],
        INDEXES => [
1003
            email_setting_user_id_idx  =>
1004 1005
                                    {FIELDS => [qw(user_id relationship event)],
                                     TYPE => 'UNIQUE'},
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        ],
    },

    email_bug_ignore => {
        FIELDS => [
            user_id => {TYPE => 'INT3', NOTNULL => 1,
                        REFERENCES => {TABLE  => 'profiles',
                                       COLUMN => 'userid',
                                       DELETE => 'CASCADE'}},
            bug_id  => {TYPE => 'INT3', NOTNULL => 1,
                        REFERENCES => {TABLE  => 'bugs',
                                       COLUMN => 'bug_id',
                                       DELETE => 'CASCADE'}},
        ],
        INDEXES => [
            email_bug_ignore_user_id_idx => {FIELDS => [qw(user_id bug_id)],
                                             TYPE   => 'UNIQUE'},
1023 1024 1025
        ],
    },

1026 1027
    watch => {
        FIELDS => [
1028 1029 1030 1031 1032 1033 1034 1035
            watcher => {TYPE => 'INT3', NOTNULL => 1,
                        REFERENCES => {TABLE  => 'profiles',
                                       COLUMN => 'userid',
                                       DELETE => 'CASCADE'}},
            watched => {TYPE => 'INT3', NOTNULL => 1,
                        REFERENCES => {TABLE  => 'profiles',
                                       COLUMN => 'userid',
                                       DELETE => 'CASCADE'}},
1036 1037
        ],
        INDEXES => [
1038
            watch_watcher_idx => {FIELDS => [qw(watcher watched)],
1039 1040 1041 1042 1043 1044 1045
                                  TYPE => 'UNIQUE'},
            watch_watched_idx => ['watched'],
        ],
    },

    namedqueries => {
        FIELDS => [
1046 1047
            id           => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
                             PRIMARYKEY => 1},
1048 1049 1050 1051
            userid       => {TYPE => 'INT3', NOTNULL => 1,
                             REFERENCES => {TABLE  => 'profiles',
                                            COLUMN => 'userid',
                                            DELETE => 'CASCADE'}},
1052
            name         => {TYPE => 'varchar(64)', NOTNULL => 1},
1053
            query        => {TYPE => 'LONGTEXT', NOTNULL => 1},
1054 1055
        ],
        INDEXES => [
1056
            namedqueries_userid_idx => {FIELDS => [qw(userid name)],
1057 1058 1059 1060
                                        TYPE => 'UNIQUE'},
        ],
    },

1061 1062
    namedqueries_link_in_footer => {
        FIELDS => [
1063 1064 1065 1066 1067 1068 1069 1070
            namedquery_id => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'namedqueries',
                                             COLUMN => 'id',
                                             DELETE => 'CASCADE'}},
            user_id       => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'profiles',
                                             COLUMN => 'userid',
                                             DELETE => 'CASCADE'}},
1071 1072 1073 1074 1075 1076 1077 1078
        ],
        INDEXES => [
            namedqueries_link_in_footer_id_idx => {FIELDS => [qw(namedquery_id user_id)],
                                                   TYPE => 'UNIQUE'},
            namedqueries_link_in_footer_userid_idx => ['user_id'],
        ],
    },

1079
    tag => {
1080 1081 1082 1083 1084 1085 1086 1087 1088
        FIELDS => [
            id   => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1, PRIMARYKEY => 1},
            name => {TYPE => 'varchar(64)', NOTNULL => 1},
            user_id  => {TYPE => 'INT3', NOTNULL => 1,
                         REFERENCES => {TABLE  => 'profiles',
                                        COLUMN => 'userid',
                                        DELETE => 'CASCADE'}},
        ],
        INDEXES => [
1089
            tag_user_id_idx => {FIELDS => [qw(user_id name)], TYPE => 'UNIQUE'},
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
        ],
    },

    bug_tag => {
        FIELDS => [
            bug_id => {TYPE => 'INT3', NOTNULL => 1,
                       REFERENCES => {TABLE  => 'bugs',
                                      COLUMN => 'bug_id',
                                      DELETE => 'CASCADE'}},
            tag_id => {TYPE => 'INT3', NOTNULL => 1,
1100
                       REFERENCES => {TABLE  => 'tag',
1101 1102 1103 1104 1105 1106 1107 1108
                                      COLUMN => 'id',
                                      DELETE => 'CASCADE'}},
        ],
        INDEXES => [
            bug_tag_bug_id_idx => {FIELDS => [qw(bug_id tag_id)], TYPE => 'UNIQUE'},
        ],
    },

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    reports => {
        FIELDS => [
            id      => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
                        PRIMARYKEY => 1},
            user_id => {TYPE => 'INT3', NOTNULL => 1,
                        REFERENCES => {TABLE  => 'profiles',
                                       COLUMN => 'userid',
                                       DELETE => 'CASCADE'}},
            name    => {TYPE => 'varchar(64)', NOTNULL => 1},
            query   => {TYPE => 'LONGTEXT', NOTNULL => 1},
        ],
        INDEXES => [
            reports_user_id_idx => {FIELDS => [qw(user_id name)],
                                   TYPE => 'UNIQUE'},
        ],
    },

1126 1127 1128
    component_cc => {

        FIELDS => [
1129 1130 1131 1132
            user_id      => {TYPE => 'INT3', NOTNULL => 1,
                             REFERENCES => {TABLE  => 'profiles',
                                            COLUMN => 'userid',
                                            DELETE => 'CASCADE'}},
1133
            component_id => {TYPE => 'INT3', NOTNULL => 1,
1134 1135 1136
                             REFERENCES => {TABLE  => 'components',
                                            COLUMN => 'id',
                                            DELETE => 'CASCADE'}},
1137 1138 1139 1140 1141 1142 1143
        ],
        INDEXES => [
            component_cc_user_id_idx => {FIELDS => [qw(component_id user_id)],
                                         TYPE => 'UNIQUE'},
        ],
    },

1144 1145 1146 1147 1148
    # Authentication
    # --------------

    logincookies => {
        FIELDS => [
1149
            cookie   => {TYPE => 'varchar(16)', NOTNULL => 1,
1150
                         PRIMARYKEY => 1},
1151 1152 1153 1154
            userid   => {TYPE => 'INT3', NOTNULL => 1,
                         REFERENCES => {TABLE  => 'profiles',
                                        COLUMN => 'userid',
                                        DELETE => 'CASCADE'}},
1155
            ipaddr   => {TYPE => 'varchar(40)'},
1156 1157 1158 1159 1160 1161 1162
            lastused => {TYPE => 'DATETIME', NOTNULL => 1},
        ],
        INDEXES => [
            logincookies_lastused_idx => ['lastused'],
        ],
    },

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
    login_failure => {
        FIELDS => [
            user_id    => {TYPE => 'INT3', NOTNULL => 1,
                           REFERENCES => {TABLE  => 'profiles',
                                          COLUMN => 'userid',
                                          DELETE => 'CASCADE'}},
            login_time => {TYPE => 'DATETIME', NOTNULL => 1},
            ip_addr    => {TYPE => 'varchar(40)', NOTNULL => 1},
        ],
        INDEXES => [
            # We do lookups by every item in the table simultaneously, but 
            # having an index with all three items would be the same size as
            # the table. So instead we have an index on just the smallest item, 
            # to speed lookups.
            login_failure_user_id_idx => ['user_id'],
        ],
    },


1182 1183 1184 1185 1186
    # "tokens" stores the tokens users receive when a password or email
    #     change is requested.  Tokens provide an extra measure of security
    #     for these changes.
    tokens => {
        FIELDS => [
1187 1188 1189
            userid    => {TYPE => 'INT3', REFERENCES => {TABLE  => 'profiles',
                                                         COLUMN => 'userid',
                                                         DELETE => 'CASCADE'}},
1190 1191 1192
            issuedate => {TYPE => 'DATETIME', NOTNULL => 1} ,
            token     => {TYPE => 'varchar(16)', NOTNULL => 1,
                          PRIMARYKEY => 1},
1193
            tokentype => {TYPE => 'varchar(16)', NOTNULL => 1} ,
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
            eventdata => {TYPE => 'TINYTEXT'},
        ],
        INDEXES => [
            tokens_userid_idx => ['userid'],
        ],
    },

    # GROUPS
    # ------

    groups => {
        FIELDS => [
            id           => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
                             PRIMARYKEY => 1},
            name         => {TYPE => 'varchar(255)', NOTNULL => 1},
1209
            description  => {TYPE => 'MEDIUMTEXT', NOTNULL => 1},
1210
            isbuggroup   => {TYPE => 'BOOLEAN', NOTNULL => 1},
1211 1212
            userregexp   => {TYPE => 'TINYTEXT', NOTNULL => 1,
                             DEFAULT => "''"},
1213 1214
            isactive     => {TYPE => 'BOOLEAN', NOTNULL => 1,
                             DEFAULT => 'TRUE'},
1215
            icon_url     => {TYPE => 'TINYTEXT'},
1216 1217
        ],
        INDEXES => [
1218
            groups_name_idx => {FIELDS => ['name'], TYPE => 'UNIQUE'},
1219 1220 1221 1222 1223
        ],
    },

    group_control_map => {
        FIELDS => [
1224 1225 1226 1227 1228 1229 1230 1231
            group_id      => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'groups',
                                             COLUMN => 'id',
                                             DELETE => 'CASCADE'}},
            product_id    => {TYPE => 'INT2', NOTNULL => 1,
                              REFERENCES => {TABLE  =>  'products',
                                             COLUMN =>  'id',
                                             DELETE =>  'CASCADE'}},
1232 1233
            entry         => {TYPE => 'BOOLEAN', NOTNULL => 1,
                              DEFAULT => 'FALSE'},
1234 1235 1236 1237
            membercontrol => {TYPE => 'INT1', NOTNULL => 1,
                              DEFAULT => CONTROLMAPNA},
            othercontrol  => {TYPE => 'INT1', NOTNULL => 1,
                              DEFAULT => CONTROLMAPNA},
1238 1239
            canedit       => {TYPE => 'BOOLEAN', NOTNULL => 1,
                              DEFAULT => 'FALSE'},
1240 1241 1242 1243 1244 1245
            editcomponents => {TYPE => 'BOOLEAN', NOTNULL => 1,
                               DEFAULT => 'FALSE'},
            editbugs      => {TYPE => 'BOOLEAN', NOTNULL => 1,
                              DEFAULT => 'FALSE'},
            canconfirm    => {TYPE => 'BOOLEAN', NOTNULL => 1,
                              DEFAULT => 'FALSE'},
1246 1247
        ],
        INDEXES => [
1248
            group_control_map_product_id_idx =>
1249
            {FIELDS => [qw(product_id group_id)], TYPE => 'UNIQUE'},
1250
            group_control_map_group_id_idx    => ['group_id'],
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
        ],
    },

    # "user_group_map" determines the groups that a user belongs to
    # directly or due to regexp and which groups can be blessed by a user.
    #
    # grant_type:
    # if GRANT_DIRECT - record was explicitly granted
    # if GRANT_DERIVED - record was derived from expanding a group hierarchy
    # if GRANT_REGEXP - record was created by evaluating a regexp
    user_group_map => {
        FIELDS => [
1263 1264 1265 1266 1267 1268 1269 1270
            user_id    => {TYPE => 'INT3', NOTNULL => 1,
                           REFERENCES => {TABLE  => 'profiles',
                                          COLUMN => 'userid',
                                          DELETE => 'CASCADE'}},
            group_id   => {TYPE => 'INT3', NOTNULL => 1,
                           REFERENCES => {TABLE  => 'groups',
                                          COLUMN => 'id',
                                          DELETE => 'CASCADE'}},
1271 1272 1273
            isbless    => {TYPE => 'BOOLEAN', NOTNULL => 1,
                           DEFAULT => 'FALSE'},
            grant_type => {TYPE => 'INT1', NOTNULL => 1,
1274
                           DEFAULT => GRANT_DIRECT},
1275 1276
        ],
        INDEXES => [
1277
            user_group_map_user_id_idx =>
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
                {FIELDS => [qw(user_id group_id grant_type isbless)],
                 TYPE => 'UNIQUE'},
        ],
    },

    # This table determines which groups are made a member of another
    # group, given the ability to bless another group, or given
    # visibility to another groups existence and membership
    # grant_type:
    # if GROUP_MEMBERSHIP - member groups are made members of grantor
    # if GROUP_BLESS - member groups may grant membership in grantor
    # if GROUP_VISIBLE - member groups may see grantor group
    group_group_map => {
        FIELDS => [
1292 1293 1294 1295 1296 1297 1298 1299
            member_id  => {TYPE => 'INT3', NOTNULL => 1,
                           REFERENCES => {TABLE  => 'groups',
                                          COLUMN => 'id',
                                          DELETE => 'CASCADE'}},
            grantor_id => {TYPE => 'INT3', NOTNULL => 1,
                           REFERENCES => {TABLE  => 'groups',
                                          COLUMN => 'id',
                                          DELETE => 'CASCADE'}},
1300
            grant_type => {TYPE => 'INT1', NOTNULL => 1,
1301
                           DEFAULT => GROUP_MEMBERSHIP},
1302 1303
        ],
        INDEXES => [
1304
            group_group_map_member_id_idx =>
1305 1306 1307 1308 1309 1310 1311 1312 1313
                {FIELDS => [qw(member_id grantor_id grant_type)],
                 TYPE => 'UNIQUE'},
        ],
    },

    # This table determines which groups a user must be a member of
    # in order to see a bug.
    bug_group_map => {
        FIELDS => [
1314 1315 1316 1317 1318 1319 1320 1321
            bug_id   => {TYPE => 'INT3', NOTNULL => 1,
                         REFERENCES => {TABLE  => 'bugs',
                                        COLUMN => 'bug_id',
                                        DELETE => 'CASCADE'}},
            group_id => {TYPE => 'INT3', NOTNULL => 1,
                         REFERENCES => {TABLE  => 'groups',
                                        COLUMN => 'id',
                                        DELETE => 'CASCADE'}},
1322 1323
        ],
        INDEXES => [
1324
            bug_group_map_bug_id_idx   =>
1325 1326 1327 1328 1329
                {FIELDS => [qw(bug_id group_id)], TYPE => 'UNIQUE'},
            bug_group_map_group_id_idx => ['group_id'],
        ],
    },

1330 1331 1332 1333
    # This table determines which groups a user must be a member of
    # in order to see a named query somebody else shares.
    namedquery_group_map => {
        FIELDS => [
1334 1335 1336 1337 1338 1339 1340 1341
            namedquery_id => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'namedqueries',
                                             COLUMN => 'id',
                                             DELETE => 'CASCADE'}},
            group_id      => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'groups',
                                             COLUMN => 'id',
                                             DELETE => 'CASCADE'}},
1342 1343 1344 1345 1346 1347 1348 1349
        ],
        INDEXES => [
            namedquery_group_map_namedquery_id_idx   =>
                {FIELDS => [qw(namedquery_id)], TYPE => 'UNIQUE'},
            namedquery_group_map_group_id_idx => ['group_id'],
        ],
    },

1350 1351
    category_group_map => {
        FIELDS => [
1352 1353 1354 1355 1356 1357 1358 1359
            category_id => {TYPE => 'INT2', NOTNULL => 1,
                            REFERENCES => {TABLE  => 'series_categories',
                                           COLUMN =>  'id',
                                           DELETE => 'CASCADE'}},
            group_id    => {TYPE => 'INT3', NOTNULL => 1,
                            REFERENCES => {TABLE  => 'groups',
                                           COLUMN => 'id',
                                           DELETE => 'CASCADE'}},
1360 1361
        ],
        INDEXES => [
1362
            category_group_map_category_id_idx =>
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
                {FIELDS => [qw(category_id group_id)], TYPE => 'UNIQUE'},
        ],
    },


    # PRODUCTS
    # --------

    classifications => {
        FIELDS => [
            id          => {TYPE => 'SMALLSERIAL', NOTNULL => 1,
                            PRIMARYKEY => 1},
            name        => {TYPE => 'varchar(64)', NOTNULL => 1},
            description => {TYPE => 'MEDIUMTEXT'},
1377
            sortkey     => {TYPE => 'INT2', NOTNULL => 1, DEFAULT => '0'},
1378 1379
        ],
        INDEXES => [
1380
            classifications_name_idx => {FIELDS => ['name'],
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
                                           TYPE => 'UNIQUE'},
        ],
    },

    products => {
        FIELDS => [
            id                => {TYPE => 'SMALLSERIAL', NOTNULL => 1,
                                  PRIMARYKEY => 1},
            name              => {TYPE => 'varchar(64)', NOTNULL => 1},
            classification_id => {TYPE => 'INT2', NOTNULL => 1,
1391 1392 1393 1394
                                  DEFAULT => '1',
                                  REFERENCES => {TABLE  => 'classifications',
                                                 COLUMN => 'id',
                                                 DELETE => 'CASCADE'}},
1395
            description       => {TYPE => 'MEDIUMTEXT', NOTNULL => 1},
1396 1397
            isactive          => {TYPE => 'BOOLEAN', NOTNULL => 1,
                                  DEFAULT => 1},
1398
            defaultmilestone  => {TYPE => 'varchar(64)',
1399
                                  NOTNULL => 1, DEFAULT => "'---'"},
1400
            allows_unconfirmed => {TYPE => 'BOOLEAN', NOTNULL => 1,
1401
                                   DEFAULT => 'TRUE'},
1402 1403
        ],
        INDEXES => [
1404
            products_name_idx   => {FIELDS => ['name'],
1405 1406 1407 1408 1409 1410
                                    TYPE => 'UNIQUE'},
        ],
    },

    components => {
        FIELDS => [
1411
            id               => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
1412 1413
                                 PRIMARYKEY => 1},
            name             => {TYPE => 'varchar(64)', NOTNULL => 1},
1414 1415 1416 1417
            product_id       => {TYPE => 'INT2', NOTNULL => 1,
                                 REFERENCES => {TABLE  => 'products',
                                                COLUMN => 'id',
                                                DELETE => 'CASCADE'}},
1418 1419 1420 1421 1422 1423 1424
            initialowner     => {TYPE => 'INT3', NOTNULL => 1,
                                 REFERENCES => {TABLE  => 'profiles',
                                                COLUMN => 'userid'}},
            initialqacontact => {TYPE => 'INT3',
                                 REFERENCES => {TABLE  => 'profiles',
                                                COLUMN => 'userid',
                                                DELETE => 'SET NULL'}},
1425
            description      => {TYPE => 'MEDIUMTEXT', NOTNULL => 1},
1426 1427
            isactive         => {TYPE => 'BOOLEAN', NOTNULL => 1, 
                                 DEFAULT => 'TRUE'},
1428 1429
        ],
        INDEXES => [
1430 1431
            components_product_id_idx => {FIELDS => [qw(product_id name)],
                                          TYPE => 'UNIQUE'},
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
            components_name_idx   => ['name'],
        ],
    },

    # CHARTS
    # ------

    series => {
        FIELDS => [
            series_id   => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
                            PRIMARYKEY => 1},
1443 1444 1445
            creator     => {TYPE => 'INT3',
                            REFERENCES => {TABLE  => 'profiles',
                                           COLUMN => 'userid',
1446
                                           DELETE => 'CASCADE'}},
1447 1448 1449 1450 1451 1452 1453 1454
            category    => {TYPE => 'INT2', NOTNULL => 1,
                            REFERENCES => {TABLE  => 'series_categories',
                                           COLUMN => 'id',
                                           DELETE => 'CASCADE'}},
            subcategory => {TYPE => 'INT2', NOTNULL => 1,
                            REFERENCES => {TABLE  => 'series_categories',
                                           COLUMN => 'id',
                                           DELETE => 'CASCADE'}},
1455 1456
            name        => {TYPE => 'varchar(64)', NOTNULL => 1},
            frequency   => {TYPE => 'INT2', NOTNULL => 1},
1457
            query       => {TYPE => 'MEDIUMTEXT', NOTNULL => 1},
1458
            is_public   => {TYPE => 'BOOLEAN', NOTNULL => 1,
1459 1460 1461
                            DEFAULT => 'FALSE'},
        ],
        INDEXES => [
1462 1463 1464
            series_creator_idx  => ['creator'],
            series_category_idx => {FIELDS => [qw(category subcategory name)],
                                    TYPE => 'UNIQUE'},
1465 1466 1467 1468 1469
        ],
    },

    series_data => {
        FIELDS => [
1470 1471 1472 1473
            series_id    => {TYPE => 'INT3', NOTNULL => 1,
                             REFERENCES => {TABLE  => 'series',
                                            COLUMN => 'series_id',
                                            DELETE => 'CASCADE'}},
1474 1475 1476 1477
            series_date  => {TYPE => 'DATETIME', NOTNULL => 1},
            series_value => {TYPE => 'INT3', NOTNULL => 1},
        ],
        INDEXES => [
1478
            series_data_series_id_idx =>
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
                {FIELDS => [qw(series_id series_date)],
                 TYPE => 'UNIQUE'},
        ],
    },

    series_categories => {
        FIELDS => [
            id   => {TYPE => 'SMALLSERIAL', NOTNULL => 1,
                     PRIMARYKEY => 1},
            name => {TYPE => 'varchar(64)', NOTNULL => 1},
        ],
        INDEXES => [
1491 1492
            series_categories_name_idx => {FIELDS => ['name'],
                                           TYPE => 'UNIQUE'},
1493 1494 1495 1496 1497 1498 1499 1500
        ],
    },

    # WHINE SYSTEM
    # ------------

    whine_queries => {
        FIELDS => [
1501 1502
            id            => {TYPE => 'MEDIUMSERIAL', PRIMARYKEY => 1,
                              NOTNULL => 1},
1503 1504 1505 1506
            eventid       => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE => 'whine_events',
                                             COLUMN => 'id',
                                             DELETE => 'CASCADE'}},
1507 1508 1509 1510 1511 1512
            query_name    => {TYPE => 'varchar(64)', NOTNULL => 1,
                              DEFAULT => "''"},
            sortkey       => {TYPE => 'INT2', NOTNULL => 1,
                              DEFAULT => '0'},
            onemailperbug => {TYPE => 'BOOLEAN', NOTNULL => 1,
                              DEFAULT => 'FALSE'},
1513 1514
            title         => {TYPE => 'varchar(128)', NOTNULL => 1,
                              DEFAULT => "''"},
1515 1516 1517 1518 1519 1520 1521 1522
        ],
        INDEXES => [
            whine_queries_eventid_idx => ['eventid'],
        ],
    },

    whine_schedules => {
        FIELDS => [
1523 1524
            id          => {TYPE => 'MEDIUMSERIAL', PRIMARYKEY => 1,
                            NOTNULL => 1},
1525 1526 1527 1528
            eventid     => {TYPE => 'INT3', NOTNULL => 1,
                            REFERENCES => {TABLE  => 'whine_events',
                                           COLUMN => 'id',
                                           DELETE => 'CASCADE'}},
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
            run_day     => {TYPE => 'varchar(32)'},
            run_time    => {TYPE => 'varchar(32)'},
            run_next    => {TYPE => 'DATETIME'},
            mailto      => {TYPE => 'INT3', NOTNULL => 1},
            mailto_type => {TYPE => 'INT2', NOTNULL => 1, DEFAULT => '0'},
        ],
        INDEXES => [
            whine_schedules_run_next_idx => ['run_next'],
            whine_schedules_eventid_idx  => ['eventid'],
        ],
    },

    whine_events => {
        FIELDS => [
1543 1544
            id           => {TYPE => 'MEDIUMSERIAL', PRIMARYKEY => 1,
                             NOTNULL => 1},
1545 1546 1547 1548
            owner_userid => {TYPE => 'INT3', NOTNULL => 1,
                             REFERENCES => {TABLE  => 'profiles', 
                                            COLUMN => 'userid',
                                            DELETE => 'CASCADE'}},
1549 1550
            subject      => {TYPE => 'varchar(128)'},
            body         => {TYPE => 'MEDIUMTEXT'},
1551 1552
            mailifnobugs => {TYPE => 'BOOLEAN', NOTNULL => 1,
                             DEFAULT => 'FALSE'},
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
        ],
    },

    # QUIPS
    # -----

    quips => {
        FIELDS => [
            quipid   => {TYPE => 'MEDIUMSERIAL', NOTNULL => 1,
                         PRIMARYKEY => 1},
1563 1564 1565 1566
            userid   => {TYPE => 'INT3',
                         REFERENCES => {TABLE  => 'profiles', 
                                        COLUMN => 'userid',
                                        DELETE => 'SET NULL'}},
1567
            quip     => {TYPE => 'varchar(512)', NOTNULL => 1},
1568 1569 1570 1571 1572
            approved => {TYPE => 'BOOLEAN', NOTNULL => 1,
                         DEFAULT => 'TRUE'},
        ],
    },

1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
    # SETTINGS
    # --------
    # setting          - each global setting will have exactly one entry
    #                    in this table.
    # setting_value    - stores the list of acceptable values for each
    #                    setting, and a sort index that controls the order
    #                    in which the values are displayed.
    # profile_setting  - If a user has chosen to use a value other than the
    #                    global default for a given setting, it will be
    #                    stored in this table. Note: even if a setting is
    #                    later changed so is_enabled = false, the stored
    #                    value will remain in case it is ever enabled again.
    #
    setting => {
        FIELDS => [
            name          => {TYPE => 'varchar(32)', NOTNULL => 1,
                              PRIMARYKEY => 1}, 
            default_value => {TYPE => 'varchar(32)', NOTNULL => 1},
            is_enabled    => {TYPE => 'BOOLEAN', NOTNULL => 1,
                              DEFAULT => 'TRUE'},
1593
            subclass      => {TYPE => 'varchar(32)'},
1594 1595 1596 1597 1598
        ],
    },

    setting_value => {
        FIELDS => [
1599 1600 1601 1602
            name        => {TYPE => 'varchar(32)', NOTNULL => 1,
                            REFERENCES => {TABLE  => 'setting', 
                                           COLUMN => 'name',
                                           DELETE => 'CASCADE'}},
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
            value       => {TYPE => 'varchar(32)', NOTNULL => 1},
            sortindex   => {TYPE => 'INT2', NOTNULL => 1},
        ],
        INDEXES => [
            setting_value_nv_unique_idx  => {FIELDS => [qw(name value)],
                                             TYPE => 'UNIQUE'},
            setting_value_ns_unique_idx  => {FIELDS => [qw(name sortindex)],
                                             TYPE => 'UNIQUE'},
        ],
     },

    profile_setting => {
        FIELDS => [
1616 1617 1618 1619
            user_id       => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'profiles',
                                             COLUMN => 'userid',
                                             DELETE => 'CASCADE'}},
1620 1621 1622 1623
            setting_name  => {TYPE => 'varchar(32)', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'setting',
                                             COLUMN => 'name',
                                             DELETE => 'CASCADE'}},
1624 1625 1626 1627 1628 1629 1630 1631
            setting_value => {TYPE => 'varchar(32)', NOTNULL => 1},
        ],
        INDEXES => [
            profile_setting_value_unique_idx  => {FIELDS => [qw(user_id setting_name)],
                                                  TYPE => 'UNIQUE'},
        ],
     },

1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
    # BUGMAIL
    # -------

    mail_staging => {
        FIELDS => [
            id      => {TYPE => 'INTSERIAL', PRIMARYKEY => 1, NOTNULL => 1},
            message => {TYPE => 'LONGBLOB', NOTNULL => 1},
        ],
    },

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
    # THESCHWARTZ TABLES
    # ------------------
    # Note: In the standard TheSchwartz schema, most integers are unsigned,
    # but we didn't implement unsigned ints for Bugzilla schemas, so we
    # just create signed ints, which should be fine.

    ts_funcmap => {
        FIELDS => [
            funcid   => {TYPE => 'INTSERIAL', PRIMARYKEY => 1, NOTNULL => 1},
            funcname => {TYPE => 'varchar(255)', NOTNULL => 1},
        ],
        INDEXES => [
            ts_funcmap_funcname_idx => {FIELDS => ['funcname'], 
                                          TYPE => 'UNIQUE'},
        ],
    },

    ts_job => {
        FIELDS => [
            # In a standard TheSchwartz schema, this is a BIGINT, but we
            # don't have those and I didn't want to add them just for this.
            jobid         => {TYPE => 'INTSERIAL', PRIMARYKEY => 1, 
                              NOTNULL => 1},
            funcid        => {TYPE => 'INT4', NOTNULL => 1},
            # In standard TheSchwartz, this is a MEDIUMBLOB.
            arg           => {TYPE => 'LONGBLOB'},
            uniqkey       => {TYPE => 'varchar(255)'},
            insert_time   => {TYPE => 'INT4'},
            run_after     => {TYPE => 'INT4', NOTNULL => 1},
            grabbed_until => {TYPE => 'INT4', NOTNULL => 1},
            priority      => {TYPE => 'INT2'},
            coalesce      => {TYPE => 'varchar(255)'},
        ],
        INDEXES => [
            ts_job_funcid_idx => {FIELDS => [qw(funcid uniqkey)],
                                  TYPE   => 'UNIQUE'},
            # In a standard TheSchewartz schema, these both go in the other
            # direction, but there's no reason to have three indexes that
            # all start with the same column, and our naming scheme doesn't
            # allow it anyhow.
            ts_job_run_after_idx => [qw(run_after funcid)],
            ts_job_coalesce_idx  => [qw(coalesce funcid)],
        ],
    },

    ts_note => {
        FIELDS => [
            # This is a BIGINT in standard TheSchwartz schemas.
            jobid   => {TYPE => 'INT4', NOTNULL => 1},
            notekey => {TYPE => 'varchar(255)'},
            value   => {TYPE => 'LONGBLOB'},
        ],
        INDEXES => [
            ts_note_jobid_idx => {FIELDS => [qw(jobid notekey)], 
                                    TYPE => 'UNIQUE'},
        ],
    },

    ts_error => {
        FIELDS => [
            error_time => {TYPE => 'INT4', NOTNULL => 1},
            jobid      => {TYPE => 'INT4', NOTNULL => 1},
            message    => {TYPE => 'varchar(255)', NOTNULL => 1},
            funcid     => {TYPE => 'INT4', NOTNULL => 1, DEFAULT => 0},
        ],
        INDEXES => [
            ts_error_funcid_idx     => [qw(funcid error_time)],
            ts_error_error_time_idx => ['error_time'],
            ts_error_jobid_idx      => ['jobid'],
        ],
    },

    ts_exitstatus => {
        FIELDS => [
            jobid           => {TYPE => 'INTSERIAL', PRIMARYKEY => 1,
                                NOTNULL => 1},
            funcid          => {TYPE => 'INT4', NOTNULL => 1, DEFAULT => 0},
            status          => {TYPE => 'INT2'},
            completion_time => {TYPE => 'INT4'},
            delete_after    => {TYPE => 'INT4'},
        ],
        INDEXES => [
            ts_exitstatus_funcid_idx       => ['funcid'],
            ts_exitstatus_delete_after_idx => ['delete_after'],
        ],
    },

1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
    # SCHEMA STORAGE
    # --------------

    bz_schema => {
        FIELDS => [
            schema_data => {TYPE => 'LONGBLOB', NOTNULL => 1},
            version     => {TYPE => 'decimal(3,2)', NOTNULL => 1},
        ],
    },

1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
    bug_user_last_visit => {
        FIELDS => [
            id            => {TYPE => 'INTSERIAL', NOTNULL => 1,
                              PRIMARYKEY => 1},
            user_id       => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'profiles',
                                             COLUMN => 'userid',
                                             DELETE => 'CASCADE'}},
            bug_id        => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'bugs',
                                             COLUMN => 'bug_id',
                                             DELETE => 'CASCADE'}},
            last_visit_ts => {TYPE => 'DATETIME', NOTNULL => 1},
        ],
        INDEXES => [
            bug_user_last_visit_idx => {FIELDS => ['user_id', 'bug_id'],
1755 1756
                                        TYPE => 'UNIQUE'},
            bug_user_last_visit_last_visit_ts_idx => ['last_visit_ts'],
1757 1758
        ],
    },
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774

    user_api_keys => {
        FIELDS => [
            id            => {TYPE => 'INTSERIAL', NOTNULL => 1,
                              PRIMARYKEY => 1},
            user_id       => {TYPE => 'INT3', NOTNULL => 1,
                              REFERENCES => {TABLE  => 'profiles',
                                             COLUMN => 'userid',
                                             DELETE => 'CASCADE'}},
            api_key       => {TYPE => 'VARCHAR(40)', NOTNULL => 1},
            description   => {TYPE => 'VARCHAR(255)'},
            revoked       => {TYPE => 'BOOLEAN', NOTNULL => 1,
                              DEFAULT => 'FALSE'},
            last_used     => {TYPE => 'DATETIME'},
        ],
        INDEXES => [
1775 1776
            user_api_keys_api_key_idx => {FIELDS => ['api_key'], TYPE => 'UNIQUE'},
            user_api_keys_user_id_idx => ['user_id'],
1777 1778
        ],
    },
1779
};
1780

1781
# Foreign Keys are added in Bugzilla::DB::bz_add_field_tables
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
use constant MULTI_SELECT_VALUE_TABLE => {
    FIELDS => [
        bug_id => {TYPE => 'INT3', NOTNULL => 1},
        value  => {TYPE => 'varchar(64)', NOTNULL => 1},
    ],
    INDEXES => [
        bug_id_idx => {FIELDS => [qw( bug_id value)], TYPE => 'UNIQUE'},
    ],
};

1792 1793 1794 1795 1796
#--------------------------------------------------------------------------

=head1 METHODS

Note: Methods which can be implemented generically for all DBs are
1797
implemented in this module. If needed, they can be overridden with
1798 1799 1800 1801 1802 1803 1804 1805 1806
DB-specific code in a subclass. Methods which are prefixed with C<_>
are considered protected. Subclasses may override these methods, but
other modules should not invoke these methods directly.

=cut

#--------------------------------------------------------------------------
sub new {

1807 1808
=over

1809 1810 1811 1812 1813 1814 1815 1816 1817
=item C<new>

 Description: Public constructor method used to instantiate objects of this
              class. However, it also can be used as a factory method to
              instantiate database-specific subclasses when an optional
              driver argument is supplied.
 Parameters:  $driver (optional) - Used to specify the type of database.
              This routine C<die>s if no subclass is found for the specified
              driver.
1818 1819
              $schema (optional) - A reference to a hash. Callers external
                  to this package should never use this parameter.
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
 Returns:     new instance of the Schema class or a database-specific subclass

=cut

    my $this = shift;
    my $class = ref($this) || $this;
    my $driver = shift;

    if ($driver) {
        (my $subclass = $driver) =~ s/^(\S)/\U$1/;
        $class .= '::' . $subclass;
        eval "require $class;";
        die "The $class class could not be found ($subclass " .
            "not supported?): $@" if ($@);
    }
    die "$class is an abstract base class. Instantiate a subclass instead."
      if ($class eq __PACKAGE__);

    my $self = {};
    bless $self, $class;
    $self = $self->_initialize(@_);

    return($self);

} #eosub--new
#--------------------------------------------------------------------------
sub _initialize {

=item C<_initialize>

 Description: Protected method that initializes an object after
              instantiation with the abstract schema. All subclasses should
              override this method. The typical subclass implementation
              should first call the C<_initialize> method of the superclass,
              then do any database-specific initialization (especially
              define the database-specific implementation of the all
              abstract data types), and then call the C<_adjust_schema>
              method.
1858 1859 1860 1861 1862
 Parameters:  $abstract_schema (optional) - A reference to a hash. If 
                  provided, this hash will be used as the internal
                  representation of the abstract schema instead of our
                  default abstract schema. This is intended for internal 
                  use only by deserialize_abstract.
1863 1864 1865 1866 1867
 Returns:     the instance of the Schema class

=cut

    my $self = shift;
1868
    my $abstract_schema = shift;
1869

1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
    if (!$abstract_schema) {
        # While ABSTRACT_SCHEMA cannot be modified, $abstract_schema can be.
        # So, we dclone it to prevent anything from mucking with the constant.
        $abstract_schema = dclone(ABSTRACT_SCHEMA);

        # Let extensions add tables, but make sure they can't modify existing
        # tables. If we don't lock/unlock keys, lock_value complains.
        lock_keys(%$abstract_schema);
        foreach my $table (keys %{ABSTRACT_SCHEMA()}) {
            lock_value(%$abstract_schema, $table) 
                if exists $abstract_schema->{$table};
        }
        unlock_keys(%$abstract_schema);
1883
        Bugzilla::Hook::process('db_schema_abstract_schema', 
1884 1885 1886
                                { schema => $abstract_schema });
        unlock_hash(%$abstract_schema);
    }
1887

1888
    $self->{schema} = dclone($abstract_schema);
1889
    $self->{abstract_schema} = $abstract_schema;
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918

    return $self;

} #eosub--_initialize
#--------------------------------------------------------------------------
sub _adjust_schema {

=item C<_adjust_schema>

 Description: Protected method that alters the abstract schema at
              instantiation-time to be database-specific. It is a generic
              enough routine that it can be defined here in the base class.
              It takes the abstract schema and replaces the abstract data
              types with database-specific data types.
 Parameters:  none
 Returns:     the instance of the Schema class

=cut

    my $self = shift;

    # The _initialize method has already set up the db_specific hash with
    # the information on how to implement the abstract data types for the
    # instantiated DBMS-specific subclass.
    my $db_specific = $self->{db_specific};

    # Loop over each table in the abstract database schema.
    foreach my $table (keys %{ $self->{schema} }) {
        my %fields = (@{ $self->{schema}{$table}{FIELDS} });
1919
        # Loop over the field definitions in each table.
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
        foreach my $field_def (values %fields) {
            # If the field type is an abstract data type defined in the
            # $db_specific hash, replace it with the DBMS-specific data type
            # that implements it.
            if (exists($db_specific->{$field_def->{TYPE}})) {
                $field_def->{TYPE} = $db_specific->{$field_def->{TYPE}};
            }
            # Replace abstract default values (such as 'TRUE' and 'FALSE')
            # with their database-specific implementations.
            if (exists($field_def->{DEFAULT})
                && exists($db_specific->{$field_def->{DEFAULT}})) {
                $field_def->{DEFAULT} = $db_specific->{$field_def->{DEFAULT}};
            }
        }
    }

    return $self;

} #eosub--_adjust_schema
#--------------------------------------------------------------------------
sub get_type_ddl {

=item C<get_type_ddl>

1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
=over

=item B<Description>

Public method to convert abstract (database-generic) field specifiers to
database-specific data types suitable for use in a C<CREATE TABLE> or 
C<ALTER TABLE> SQL statment. If no database-specific field type has been
defined for the given field type, then it will just return the same field type.

=item B<Parameters>

=over

=item C<$def> - A reference to a hash of a field containing the following keys:
C<TYPE> (required), C<NOTNULL> (optional), C<DEFAULT> (optional), 
C<PRIMARYKEY> (optional), C<REFERENCES> (optional)

=back

1963
=item B<Returns>
1964 1965 1966

A DDL string suitable for describing a field in a C<CREATE TABLE> or 
C<ALTER TABLE> SQL statement
1967

1968 1969
=back

1970 1971 1972 1973 1974
=cut

    my $self = shift;
    my $finfo = (@_ == 1 && ref($_[0]) eq 'HASH') ? $_[0] : { @_ };
    my $type = $finfo->{TYPE};
1975 1976
    confess "A valid TYPE was not specified for this column (got " 
            . Dumper($finfo) . ")" unless ($type);
1977

1978
    my $default = $finfo->{DEFAULT};
1979 1980 1981 1982 1983 1984
    # Replace any abstract default value (such as 'TRUE' or 'FALSE')
    # with its database-specific implementation.
    if ( defined $default && exists($self->{db_specific}->{$default}) ) {
        $default = $self->{db_specific}->{$default};
    }

1985
    my $type_ddl = $self->convert_type($type);
1986 1987
    # DEFAULT attribute must appear before any column constraints
    # (e.g., NOT NULL), for Oracle
1988
    $type_ddl .= " DEFAULT $default" if (defined($default));
1989
    # PRIMARY KEY must appear before NOT NULL for SQLite.
1990
    $type_ddl .= " PRIMARY KEY" if ($finfo->{PRIMARYKEY});
1991
    $type_ddl .= " NOT NULL" if ($finfo->{NOTNULL});
1992 1993 1994 1995

    return($type_ddl);

} #eosub--get_type_ddl
1996

1997 1998

sub get_fk_ddl {
1999

2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
=item C<_get_fk_ddl>

=over

=item B<Description>

Protected method. Translates the C<REFERENCES> item of a column into SQL.

=item B<Params>

=over

=item C<$table>  - The name of the table the reference is from.
2013

2014
=item C<$column> - The name of the column the reference is from
2015

2016 2017 2018 2019
=item C<$references> - The C<REFERENCES> hashref from a column.

=back

2020 2021 2022 2023 2024 2025
=item B<Returns>

SQL for to define the foreign key, or an empty string if C<$references> 
is undefined.

=back
2026 2027 2028 2029 2030 2031 2032 2033

=cut

    my ($self, $table, $column, $references) = @_;
    return "" if !$references;

    my $update    = $references->{UPDATE} || 'CASCADE';
    my $delete    = $references->{DELETE} || 'RESTRICT';
2034 2035
    my $to_table  = $references->{TABLE}  || confess "No table in reference";
    my $to_column = $references->{COLUMN} || confess "No column in reference";
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
    my $fk_name   = $self->_get_fk_name($table, $column, $references);

    return "\n     CONSTRAINT $fk_name FOREIGN KEY ($column)\n"
         . "     REFERENCES $to_table($to_column)\n"
         . "      ON UPDATE $update ON DELETE $delete";
}

# Generates a name for a Foreign Key. It's separate from get_fk_ddl
# so that certain databases can override it (for shorter identifiers or
# other reasons).
sub _get_fk_name {
    my ($self, $table, $column, $references) = @_;
    my $to_table  = $references->{TABLE}; 
    my $to_column = $references->{COLUMN};
2050 2051 2052 2053 2054 2055 2056
    my $name = "fk_${table}_${column}_${to_table}_${to_column}";

    if (length($name) > $self->MAX_IDENTIFIER_LEN) {
        $name = 'fk_' . $self->_hash_identifier($name);
    }

    return $name;
2057 2058
}

2059 2060 2061 2062 2063 2064 2065 2066
sub _hash_identifier {
    my ($invocant, $value) = @_;
    # We do -7 to allow prefixes like "idx_" or "fk_", or perhaps something
    # longer in the future.
    return substr(md5_hex($value), 0, $invocant->MAX_IDENTIFIER_LEN - 7);
}


2067 2068
sub get_add_fks_sql {
    my ($self, $table, $column_fks) = @_;
2069

2070 2071
    my @add = $self->_column_fks_to_ddl($table, $column_fks);

2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
    my @sql;
    if ($self->MULTIPLE_FKS_IN_ALTER) {
        my $alter = "ALTER TABLE $table ADD " . join(', ADD ', @add);
        push(@sql, $alter);
    }
    else {
        foreach my $fk_string (@add) {
            push(@sql, "ALTER TABLE $table ADD $fk_string");
        }
    }
    return @sql;
2083 2084
}

2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
sub _column_fks_to_ddl {
    my ($self, $table, $column_fks) = @_;
    my @ddl;
    foreach my $column (keys %$column_fks) {
        my $def = $column_fks->{$column};
        my $fk_string = $self->get_fk_ddl($table, $column, $def);
        push(@ddl, $fk_string);
    }
    return @ddl;
}

2096 2097 2098
sub get_drop_fk_sql { 
    my ($self, $table, $column, $references) = @_;
    my $fk_name = $self->_get_fk_name($table, $column, $references);
2099 2100 2101 2102

    return ("ALTER TABLE $table DROP CONSTRAINT $fk_name");
}

2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
sub convert_type {

=item C<convert_type>

Converts a TYPE from the L</ABSTRACT_SCHEMA> format into the real SQL type.

=cut

    my ($self, $type) = @_;
    return $self->{db_specific}->{$type} || $type;
}

2115
sub get_column {
2116

2117
=item C<get_column($table, $column)>
2118

2119
 Description: Public method to get the abstract definition of a column.
2120 2121
 Parameters:  $table - the table name
              $column - a column in the table
2122
 Returns:     a hashref containing information about the column, including its
2123
              type (C<TYPE>), whether or not it can be null (C<NOTNULL>),
2124 2125
              its default value if it has one (C<DEFAULT), etc.
              Returns undef if the table or column does not exist.
2126 2127 2128 2129 2130

=cut

    my($self, $table, $column) = @_;

2131 2132 2133 2134 2135 2136 2137 2138
    # Prevent a possible dereferencing of an undef hash, if the
    # table doesn't exist.
    if (exists $self->{schema}->{$table}) {
        my %fields = (@{ $self->{schema}{$table}{FIELDS} });
        return $fields{$column};
    }
    return undef;
} #eosub--get_column
2139

2140 2141 2142 2143 2144 2145
sub get_table_list {

=item C<get_table_list>

 Description: Public method for discovering what tables should exist in the
              Bugzilla database.
2146

2147
 Parameters:  none
2148

2149
 Returns:     An array of table names, in alphabetical order.
2150 2151 2152 2153

=cut

    my $self = shift;
2154
    return sort keys %{$self->{schema}};   
2155
}
2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171

sub get_table_columns {

=item C<get_table_columns>

 Description: Public method for discovering what columns are in a given
              table in the Bugzilla database.
 Parameters:  $table - the table name
 Returns:     array of column names

=cut

    my($self, $table) = @_;
    my @ddl = ();

    my $thash = $self->{schema}{$table};
2172 2173
    die "Table $table does not exist in the database schema."
        unless (ref($thash));
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184

    my @columns = ();
    my @fields = @{ $thash->{FIELDS} };
    while (@fields) {
        push(@columns, shift(@fields));
        shift(@fields);
    }

    return @columns;

} #eosub--get_table_columns
2185

2186 2187 2188 2189 2190 2191 2192
sub get_table_indexes_abstract {
    my ($self, $table) = @_;
    my $table_def = $self->get_table_abstract($table);
    my %indexes = @{$table_def->{INDEXES} || []};
    return \%indexes;
}

2193 2194 2195 2196 2197
sub get_create_database_sql {
    my ($self, $name) = @_;
    return ("CREATE DATABASE $name");
}

2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
sub get_table_ddl {

=item C<get_table_ddl>

 Description: Public method to generate the SQL statements needed to create
              the a given table and its indexes in the Bugzilla database.
              Subclasses may override or extend this method, if needed, but
              subclasses probably should override C<_get_create_table_ddl>
              or C<_get_create_index_ddl> instead.
 Parameters:  $table - the table name
 Returns:     an array of strings containing SQL statements

=cut

    my($self, $table) = @_;
    my @ddl = ();

2215 2216
    die "Table $table does not exist in the database schema."
        unless (ref($self->{schema}{$table}));
2217 2218 2219 2220 2221 2222 2223 2224

    my $create_table = $self->_get_create_table_ddl($table);
    push(@ddl, $create_table) if $create_table;

    my @indexes = @{ $self->{schema}{$table}{INDEXES} || [] };
    while (@indexes) {
        my $index_name = shift(@indexes);
        my $index_info = shift(@indexes);
2225 2226
        my $index_sql  = $self->get_add_index_ddl($table, $index_name, 
                                                  $index_info);
2227 2228 2229 2230 2231 2232 2233 2234 2235
        push(@ddl, $index_sql) if $index_sql;
    }

    push(@ddl, @{ $self->{schema}{$table}{DB_EXTRAS} })
      if (ref($self->{schema}{$table}{DB_EXTRAS}));

    return @ddl;

} #eosub--get_table_ddl
2236

2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
sub _get_create_table_ddl {

=item C<_get_create_table_ddl>

 Description: Protected method to generate the "create table" SQL statement
              for a given table.
 Parameters:  $table - the table name
 Returns:     a string containing the DDL statement for the specified table

=cut

    my($self, $table) = @_;

    my $thash = $self->{schema}{$table};
2251
    die "Table $table does not exist in the database schema."
2252
        unless ref $thash;
2253

2254
    my (@col_lines, @fk_lines);
2255 2256 2257 2258
    my @fields = @{ $thash->{FIELDS} };
    while (@fields) {
        my $field = shift(@fields);
        my $finfo = shift(@fields);
2259 2260 2261
        push(@col_lines, "\t$field\t" . $self->get_type_ddl($finfo));
        if ($self->FK_ON_CREATE and $finfo->{REFERENCES}) {
            my $fk = $finfo->{REFERENCES};
2262
            my $fk_ddl = $self->get_fk_ddl($table, $field, $fk);
2263 2264
            push(@fk_lines, $fk_ddl);
        }
2265
    }
2266 2267 2268 2269
    
    my $sql = "CREATE TABLE $table (\n" . join(",\n", @col_lines, @fk_lines)
              . "\n)";
    return $sql
2270

2271
} 
2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286

sub _get_create_index_ddl {

=item C<_get_create_index_ddl>

 Description: Protected method to generate a "create index" SQL statement
              for a given table and index.
 Parameters:  $table_name - the name of the table
              $index_name - the name of the index
              $index_fields - a reference to an array of field names
              $index_type (optional) - specify type of index (e.g., UNIQUE)
 Returns:     a string containing the DDL statement

=cut

2287
    my ($self, $table_name, $index_name, $index_fields, $index_type) = @_;
2288 2289

    my $sql = "CREATE ";
2290
    $sql .= "$index_type " if ($index_type && $index_type eq 'UNIQUE');
2291 2292 2293 2294 2295 2296 2297
    $sql .= "INDEX $index_name ON $table_name \(" .
      join(", ", @$index_fields) . "\)";

    return($sql);

} #eosub--_get_create_index_ddl
#--------------------------------------------------------------------------
2298 2299

sub get_add_column_ddl {
2300

2301
=item C<get_add_column_ddl($table, $column, \%definition, $init_value)>
2302 2303 2304 2305 2306 2307

 Description: Generate SQL to add a column to a table.
 Params:      $table - The table containing the column.
              $column - The name of the column being added.
              \%definition - The new definition for the column,
                  in standard C<ABSTRACT_SCHEMA> format.
2308 2309 2310
              $init_value - (optional) An initial value to set 
                            the column to. Should already be SQL-quoted
                            if necessary.
2311 2312 2313
 Returns:     An array of SQL statements.

=cut
2314

2315 2316
    my ($self, $table, $column, $definition, $init_value) = @_;
    my @statements;
2317
    push(@statements, "ALTER TABLE $table ". $self->ADD_COLUMN ." $column " .
2318
        $self->get_type_ddl($definition));
2319

2320 2321 2322 2323
    # XXX - Note that although this works for MySQL, most databases will fail
    # before this point, if we haven't set a default.
    (push(@statements, "UPDATE $table SET $column = $init_value"))
        if defined $init_value;
2324

2325
    if (defined $definition->{REFERENCES}) {
2326 2327
        push(@statements, $self->get_add_fks_sql($table, { $column =>
                                                           $definition->{REFERENCES} }));
2328 2329
    }

2330
    return (@statements);
2331 2332
}

2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
sub get_add_index_ddl {

=item C<get_add_index_ddl>

 Description: Gets SQL for creating an index.
              NOTE: Subclasses should not override this function. Instead,
              if they need to specify a custom CREATE INDEX statement, 
              they should override C<_get_create_index_ddl>
 Params:      $table - The name of the table the index will be on.
              $name  - The name of the new index.
              $definition - An index definition. Either a hashref 
                            with FIELDS and TYPE or an arrayref 
                            containing a list of columns.
 Returns:     An array of SQL statements that will create the 
              requested index.

=cut

    my ($self, $table, $name, $definition) = @_;

    my ($index_fields, $index_type);
    # Index defs can be arrays or hashes
    if (ref($definition) eq 'HASH') {
        $index_fields = $definition->{FIELDS};
        $index_type = $definition->{TYPE};
    } else {
        $index_fields = $definition;
        $index_type = '';
    }
    
    return $self->_get_create_index_ddl($table, $name, $index_fields, 
                                        $index_type);
}

2367 2368
sub get_alter_column_ddl {

2369
=item C<get_alter_column_ddl($table, $column, \%definition)>
2370 2371 2372 2373 2374 2375 2376 2377

 Description: Generate SQL to alter a column in a table.
              The column that you are altering must exist,
              and the table that it lives in must exist.
 Params:      $table - The table containing the column.
              $column - The name of the column being changed.
              \%definition - The new definition for the column,
                  in standard C<ABSTRACT_SCHEMA> format.
2378 2379 2380 2381 2382
              $set_nulls_to - A value to set NULL values to, if
                  your new definition is NOT NULL and contains
                  no DEFAULT, and when there is a possibility
                  that the column could contain NULLs. $set_nulls_to
                  should be already SQL-quoted if necessary.
2383 2384 2385 2386
 Returns:     An array of SQL statements.

=cut

2387 2388
    my $self = shift;
    my ($table, $column, $new_def, $set_nulls_to) = @_;
2389 2390 2391 2392 2393 2394 2395

    my @statements;
    my $old_def = $self->get_column_abstract($table, $column);
    my $specific = $self->{db_specific};

    # If the types have changed, we have to deal with that.
    if (uc(trim($old_def->{TYPE})) ne uc(trim($new_def->{TYPE}))) {
2396 2397
        push(@statements, $self->_get_alter_type_sql($table, $column, 
                                                     $new_def, $old_def));
2398 2399 2400 2401
    }

    my $default = $new_def->{DEFAULT};
    my $default_old = $old_def->{DEFAULT};
2402 2403 2404 2405

    if (defined $default) {
        $default = $specific->{$default} if exists $specific->{$default};
    }
2406 2407 2408 2409
    # This first condition prevents "uninitialized value" errors.
    if (!defined $default && !defined $default_old) {
        # Do Nothing
    }
2410
    # If we went from having a default to not having one
2411
    elsif (!defined $default && defined $default_old) {
2412 2413 2414
        push(@statements, "ALTER TABLE $table ALTER COLUMN $column"
                        . " DROP DEFAULT");
    }
2415
    # If we went from no default to a default, or we changed the default.
2416
    elsif ( (defined $default && !defined $default_old) || 
2417 2418
            ($default ne $default_old) ) 
    {
2419 2420 2421 2422
        push(@statements, "ALTER TABLE $table ALTER COLUMN $column "
                         . " SET DEFAULT $default");
    }

2423 2424
    # If we went from NULL to NOT NULL.
    if (!$old_def->{NOTNULL} && $new_def->{NOTNULL}) {
2425
        push(@statements, $self->_set_nulls_sql(@_));
2426
        push(@statements, "ALTER TABLE $table ALTER COLUMN $column"
2427
                        . " SET NOT NULL");
2428 2429 2430 2431 2432 2433 2434
    }
    # If we went from NOT NULL to NULL
    elsif ($old_def->{NOTNULL} && !$new_def->{NOTNULL}) {
        push(@statements, "ALTER TABLE $table ALTER COLUMN $column"
                        . " DROP NOT NULL");
    }

2435 2436
    # If we went from not being a PRIMARY KEY to being a PRIMARY KEY.
    if (!$old_def->{PRIMARYKEY} && $new_def->{PRIMARYKEY}) {
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
        push(@statements, "ALTER TABLE $table ADD PRIMARY KEY ($column)");
    }
    # If we went from being a PK to not being a PK
    elsif ( $old_def->{PRIMARYKEY} && !$new_def->{PRIMARYKEY} ) {
        push(@statements, "ALTER TABLE $table DROP PRIMARY KEY");
    }

    return @statements;
}

2447 2448
# Helps handle any fields that were NULL before, if we have a default,
# when doing an ALTER COLUMN.
2449 2450
sub _set_nulls_sql {
    my ($self, $table, $column, $new_def, $set_nulls_to) = @_;
2451 2452
    my $default = $new_def->{DEFAULT};
    # If we have a set_nulls_to, that overrides the DEFAULT 
2453 2454
    # (although nobody would usually specify both a default and 
    # a set_nulls_to.)
2455 2456 2457 2458 2459
    $default = $set_nulls_to if defined $set_nulls_to;
    if (defined $default) {
         my $specific = $self->{db_specific};
         $default = $specific->{$default} if exists $specific->{$default};
    }
2460
    my @sql;
2461 2462
    if (defined $default) {
        push(@sql, "UPDATE $table SET $column = $default"
2463 2464 2465 2466 2467
                . "  WHERE $column IS NULL");
    }
    return @sql;
}

2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
sub get_drop_index_ddl {

=item C<get_drop_index_ddl($table, $name)>

 Description: Generates SQL statements to drop an index.
 Params:      $table - The table the index is on.
              $name  - The name of the index being dropped.
 Returns:     An array of SQL statements.

=cut
2478

2479 2480 2481 2482 2483 2484 2485
    my ($self, $table, $name) = @_;

    # Although ANSI SQL-92 doesn't specify a method of dropping an index,
    # many DBs support this syntax.
    return ("DROP INDEX $name");
}

2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
sub get_drop_column_ddl {

=item C<get_drop_column_ddl($table, $column)>

 Description: Generate SQL to drop a column from a table.
 Params:      $table - The table containing the column.
              $column - The name of the column being dropped.
 Returns:     An array of SQL statements.

=cut

    my ($self, $table, $column) = @_;
    return ("ALTER TABLE $table DROP COLUMN $column");
}

2501 2502 2503 2504 2505 2506 2507
=item C<get_drop_table_ddl($table)>

 Description: Generate SQL to drop a table from the database.
 Params:      $table - The name of the table to drop.
 Returns:     An array of SQL statements.

=cut
2508

2509 2510 2511 2512 2513
sub get_drop_table_ddl {
    my ($self, $table) = @_;
    return ("DROP TABLE $table");
}

2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
sub get_rename_column_ddl {

=item C<get_rename_column_ddl($table, $old_name, $new_name)>

 Description: Generate SQL to change the name of a column in a table.
              NOTE: ANSI SQL contains no simple way to rename a column,
                    so this function is ABSTRACT and must be implemented
                    by subclasses.
 Params:      $table - The table containing the column to be renamed.
              $old_name - The name of the column being renamed.
              $new_name - The name the column is changing to.
 Returns:     An array of SQL statements.

=cut

    die "ANSI SQL has no way to rename a column, and your database driver\n"
        . " has not implemented a method.";
}

2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563

sub get_rename_table_sql {

=item C<get_rename_table_sql>

=over

=item B<Description>

Gets SQL to rename a table in the database.

=item B<Params>

=over

=item C<$old_name> - The current name of the table.

=item C<$new_name> - The new name of the table.

=back

=item B<Returns>: An array of SQL statements to rename a table.

=back

=cut

    my ($self, $old_name, $new_name) = @_;
    return ("ALTER TABLE $old_name RENAME TO $new_name");
}

2564 2565 2566 2567 2568 2569 2570 2571
=item C<delete_table($name)>

 Description: Deletes a table from this Schema object.
              Dies if you try to delete a table that doesn't exist.
 Params:      $name - The name of the table to delete.
 Returns:     nothing

=cut
2572

2573 2574 2575 2576 2577 2578 2579 2580 2581 2582
sub delete_table {
    my ($self, $name) = @_;

    die "Attempted to delete nonexistent table '$name'." unless
        $self->get_table_abstract($name);

    delete $self->{abstract_schema}->{$name};
    delete $self->{schema}->{$name};
}

2583
sub get_column_abstract {
2584

2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
=item C<get_column_abstract($table, $column)>

 Description: A column definition from the abstract internal schema.
              cross-database format.
 Params:      $table - The name of the table
              $column - The name of the column that you want
 Returns:     A hash reference. For the format, see the docs for
              C<ABSTRACT_SCHEMA>.
              Returns undef if the column or table does not exist.

=cut

    my ($self, $table, $column) = @_;

    # Prevent a possible dereferencing of an undef hash, if the
    # table doesn't exist.
2601
    if ($self->get_table_abstract($table)) {
2602 2603
        my %fields = (@{ $self->{abstract_schema}{$table}{FIELDS} });
        return $fields{$column};
2604 2605 2606 2607
    }
    return undef;
}

2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620
=item C<get_indexes_on_column_abstract($table, $column)>

 Description: Gets a list of indexes that are on a given column.
 Params:      $table - The table the column is on.
              $column - The name of the column.
 Returns:     Indexes in the standard format of an INDEX
              entry on a table. That is, key-value pairs
              where the key is the index name and the value
              is the index definition.
              If there are no indexes on that column, we return
              undef.

=cut
2621

2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
sub get_indexes_on_column_abstract {
    my ($self, $table, $column) = @_;
    my %ret_hash;

    my $table_def = $self->get_table_abstract($table);
    if ($table_def && exists $table_def->{INDEXES}) {
        my %indexes = (@{ $table_def->{INDEXES} });
        foreach my $index_name (keys %indexes) {
            my $col_list;
            # Get the column list, depending on whether the index
            # is in hashref or arrayref format.
            if (ref($indexes{$index_name}) eq 'HASH') {
                $col_list = $indexes{$index_name}->{FIELDS};
            } else {
                $col_list = $indexes{$index_name};
            }

            if(grep($_ eq $column, @$col_list)) {
                $ret_hash{$index_name} = dclone($indexes{$index_name});
            }
        }
    }

    return %ret_hash;
}

2648 2649
sub get_index_abstract {

2650
=item C<get_index_abstract($table, $index)>
2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664

 Description: Returns an index definition from the internal abstract schema.
 Params:      $table - The table the index is on.
              $index - The name of the index.
 Returns:     A hash reference representing an index definition.
              See the C<ABSTRACT_SCHEMA> docs for details.
              Returns undef if the index does not exist.

=cut

    my ($self, $table, $index) = @_;

    # Prevent a possible dereferencing of an undef hash, if the
    # table doesn't exist.
2665 2666 2667
    my $index_table = $self->get_table_abstract($table);
    if ($index_table && exists $index_table->{INDEXES}) {
        my %indexes = (@{ $index_table->{INDEXES} });
2668
        return $indexes{$index};
2669 2670 2671
    }
    return undef;
}
2672

2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
=item C<get_table_abstract($table)>

 Description: Gets the abstract definition for a table in this Schema
              object.
 Params:      $table - The name of the table you want a definition for.
 Returns:     An abstract table definition, or undef if the table doesn't
              exist.

=cut

sub get_table_abstract {
    my ($self, $table) = @_;
    return $self->{abstract_schema}->{$table};
}

=item C<add_table($name, \%definition)>

 Description: Creates a new table in this Schema object.
              If you do not specify a definition, we will
              simply create an empty table.
 Params:      $name - The name for the new table.
              \%definition (optional) - An abstract definition for
                  the new table.
 Returns:     nothing

=cut
2699

2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714
sub add_table {
    my ($self, $name, $definition) = @_;
    (die "Table already exists: $name")
        if exists $self->{abstract_schema}->{$name};
    if ($definition) {
        $self->{abstract_schema}->{$name} = dclone($definition);
        $self->{schema} = dclone($self->{abstract_schema});
        $self->_adjust_schema();
    }
    else {
        $self->{abstract_schema}->{$name} = {FIELDS => []};
        $self->{schema}->{$name}          = {FIELDS => []};
    }
}

2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731


sub rename_table {

=item C<rename_table>

Renames a table from C<$old_name> to C<$new_name> in this Schema object.

=cut


    my ($self, $old_name, $new_name) = @_;
    my $table = $self->get_table_abstract($old_name);
    $self->delete_table($old_name);
    $self->add_table($new_name, $table);
}

2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746
sub delete_column {

=item C<delete_column($table, $column)>

 Description: Deletes a column from this Schema object.
 Params:      $table - Name of the table that the column is in.
                       The table must exist, or we will fail.
              $column  - Name of the column to delete.
 Returns:     nothing

=cut

    my ($self, $table, $column) = @_;

    my $abstract_fields = $self->{abstract_schema}{$table}{FIELDS};
2747
    my $name_position = firstidx { $_ eq $column } @$abstract_fields;
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
    die "Attempted to delete nonexistent column ${table}.${column}" 
        if $name_position == -1;
    # Delete the key/value pair from the array.
    splice(@$abstract_fields, $name_position, 2);

    $self->{schema} = dclone($self->{abstract_schema});
    $self->_adjust_schema();
}

sub rename_column {

2759
=item C<rename_column($table, $old_name, $new_name)>
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776

 Description: Renames a column on a table in the Schema object.
              The column that you are renaming must exist.
 Params:      $table - The table the column is on.
              $old_name - The current name of the column.
              $new_name - The new name of hte column.
 Returns:     nothing

=cut

    my ($self, $table, $old_name, $new_name) = @_;
    my $def = $self->get_column_abstract($table, $old_name);
    die "Renaming a column that doesn't exist" if !$def;
    $self->delete_column($table, $old_name);
    $self->set_column($table, $new_name, $def);
}

2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796
sub set_column {

=item C<set_column($table, $column, \%new_def)>

 Description: Changes the definition of a column in this Schema object.
              If the column doesn't exist, it will be added.
              The table that you specify must already exist in the Schema.
              NOTE: This does not affect the database on the disk.
              Use the C<Bugzilla::DB> "Schema Modification Methods"
              if you want to do that.
 Params:      $table - The name of the table that the column is on.
              $column - The name of the column.
              \%new_def - The new definition for the column, in 
                  C<ABSTRACT_SCHEMA> format.
 Returns:     nothing

=cut

    my ($self, $table, $column, $new_def) = @_;

2797
    my $fields = $self->{abstract_schema}{$table}{FIELDS};
2798 2799 2800
    $self->_set_object($table, $column, $new_def, $fields);
}

2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822
=item C<set_fk($table, $column \%fk_def)>

Sets the C<REFERENCES> item on the specified column.

=cut

sub set_fk {
    my ($self, $table, $column, $fk_def) = @_;
    # Don't want to modify the source def before we explicitly set it below.
    # This is just us being extra-cautious.
    my $column_def = dclone($self->get_column_abstract($table, $column));
    die "Tried to set an fk on $table.$column, but that column doesn't exist"
        if !$column_def;
    if ($fk_def) {
        $column_def->{REFERENCES} = $fk_def;
    }
    else {
        delete $column_def->{REFERENCES};
    }
    $self->set_column($table, $column, $column_def);
}

2823
sub set_index {
2824

2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842
=item C<set_index($table, $name, $definition)>

 Description: Changes the definition of an index in this Schema object.
              If the index doesn't exist, it will be added.
              The table that you specify must already exist in the Schema.
              NOTE: This does not affect the database on the disk.
              Use the C<Bugzilla::DB> "Schema Modification Methods"
              if you want to do that.
 Params:      $table      - The table the index is on.
              $name       - The name of the index.
              $definition - A hashref or an arrayref. An index 
                            definition in C<ABSTRACT_SCHEMA> format.
 Returns:     nothing

=cut

    my ($self, $table, $name, $definition) = @_;

2843 2844 2845 2846 2847
    if ( exists $self->{abstract_schema}{$table}
         && !exists $self->{abstract_schema}{$table}{INDEXES} ) {
        $self->{abstract_schema}{$table}{INDEXES} = [];
    }

2848
    my $indexes = $self->{abstract_schema}{$table}{INDEXES};
2849 2850 2851 2852 2853 2854 2855 2856 2857
    $self->_set_object($table, $name, $definition, $indexes);
}

# A private helper for set_index and set_column.
# This does the actual "work" of those two functions.
# $array_to_change is an arrayref.
sub _set_object {
    my ($self, $table, $name, $definition, $array_to_change) = @_;

2858
    my $obj_position = (firstidx { $_ eq $name } @$array_to_change) + 1;
2859 2860 2861 2862
    # If the object doesn't exist, then add it.
    if (!$obj_position) {
        push(@$array_to_change, $name);
        push(@$array_to_change, $definition);
2863
    }
2864
    # We're modifying an existing object in the Schema.
2865
    else {
2866
        splice(@$array_to_change, $obj_position, 1, $definition);
2867 2868
    }

2869
    $self->{schema} = dclone($self->{abstract_schema});
2870 2871 2872
    $self->_adjust_schema();
}

2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
=item C<delete_index($table, $name)>

 Description: Removes an index definition from this Schema object.
              If the index doesn't exist, we will fail.
              The table that you specify must exist in the Schema.
              NOTE: This does not affect the database on the disk.
              Use the C<Bugzilla::DB> "Schema Modification Methods"
              if you want to do that.
 Params:      $table - The table the index is on.
              $name  - The name of the index that we're removing.
 Returns:     nothing

=cut
2886

2887 2888 2889 2890
sub delete_index {
    my ($self, $table, $name) = @_;

    my $indexes = $self->{abstract_schema}{$table}{INDEXES};
2891
    my $name_position = firstidx { $_ eq $name } @$indexes;
2892 2893 2894 2895 2896 2897 2898 2899
    die "Attempted to delete nonexistent index $name on the $table table" 
        if $name_position == -1;
    # Delete the key/value pair from the array.
    splice(@$indexes, $name_position, 2);
    $self->{schema} = dclone($self->{abstract_schema});
    $self->_adjust_schema();
}

2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
sub columns_equal {

=item C<columns_equal($col_one, $col_two)>

 Description: Tells you if two columns have entirely identical definitions.
              The TYPE field's value will be compared case-insensitive.
              However, all other fields will be case-sensitive.
 Params:      $col_one, $col_two - The columns to compare. Hash 
                  references, in C<ABSTRACT_SCHEMA> format.
 Returns:     C<1> if the columns are identical, C<0> if they are not.
2910 2911 2912

=back

2913 2914 2915 2916 2917 2918 2919 2920 2921
=cut

    my $self = shift;
    my $col_one = dclone(shift);
    my $col_two = dclone(shift);

    $col_one->{TYPE} = uc($col_one->{TYPE});
    $col_two->{TYPE} = uc($col_two->{TYPE});

2922 2923 2924
    # We don't care about foreign keys when comparing column definitions.
    delete $col_one->{REFERENCES};
    delete $col_two->{REFERENCES};
2925

2926 2927
    my @col_one_array = %$col_one;
    my @col_two_array = %$col_two;
2928 2929 2930

    my ($removed, $added) = diff_arrays(\@col_one_array, \@col_two_array);

2931
    # If there are no differences between the arrays, then they are equal.
2932
    return !scalar(@$removed) && !scalar(@$added) ? 1 : 0;
2933 2934
}

2935 2936 2937

=head1 SERIALIZATION/DESERIALIZATION

2938 2939
=over 4

2940 2941 2942 2943 2944 2945 2946 2947 2948 2949
=item C<serialize_abstract()>

 Description: Serializes the "abstract" schema into a format
              that deserialize_abstract() can read in. This is
              a method, called on a Schema instance.
 Parameters:  none
 Returns:     A scalar containing the serialized, abstract schema.
              Do not attempt to manipulate this data directly,
              as the format may change at any time in the future.
              The only thing you should do with the returned value
2950 2951
              is either store it somewhere (coupled with appropriate 
              SCHEMA_VERSION) or deserialize it.
2952 2953

=cut
2954

2955 2956
sub serialize_abstract {
    my ($self) = @_;
2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967
    
    # Make it ok to eval
    local $Data::Dumper::Purity = 1;
    
    # Avoid cross-refs
    local $Data::Dumper::Deepcopy = 1;
    
    # Always sort keys to allow textual compare
    local $Data::Dumper::Sortkeys = 1;
    
    return Dumper($self->{abstract_schema});
2968 2969 2970 2971 2972 2973 2974
}

=item C<deserialize_abstract($serialized, $version)>

 Description: Used for when you've read a serialized Schema off the disk,
              and you want a Schema object that represents that data.
 Params:      $serialized - scalar. The serialized data.
2975
              $version - A number. The "version"
2976 2977 2978 2979 2980 2981
                  of the Schema that did the serialization.
                  See the docs for C<SCHEMA_VERSION> for more details.
 Returns:     A Schema object. It will have the methods of (and work 
              in the same fashion as) the current version of Schema. 
              However, it will represent the serialized data instead of
              ABSTRACT_SCHEMA.
2982

2983
=cut
2984

2985 2986 2987
sub deserialize_abstract {
    my ($class, $serialized, $version) = @_;

2988
    my $thawed_hash;
2989
    if ($version < 2) {
2990 2991 2992 2993 2994 2995 2996 2997
        $thawed_hash = thaw($serialized);
    }
    else {
        my $cpt = new Safe;
        $cpt->reval($serialized) ||
            die "Unable to restore cached schema: " . $@;
        $thawed_hash = ${$cpt->varglob('VAR1')};
    }
2998

2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
    # Version 2 didn't have the "created" key for REFERENCES items.
    if ($version < 3) {
        my $standard = $class->new()->{abstract_schema};
        foreach my $table_name (keys %$thawed_hash) {
            my %standard_fields = 
                @{ $standard->{$table_name}->{FIELDS} || [] };
            my $table = $thawed_hash->{$table_name};
            my %fields = @{ $table->{FIELDS} || [] };
            while (my ($field, $def) = each %fields) {
                if (exists $def->{REFERENCES}) {
                    $def->{REFERENCES}->{created} = 1;
                }
            }
        }
    }

3015
    return $class->new(undef, $thawed_hash);
3016 3017
}

3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
#####################################################################
# Class Methods
#####################################################################

=back

=head1 CLASS METHODS

These methods are generally called on the class instead of on a specific
object.

3029 3030
=over

3031 3032 3033 3034 3035 3036 3037
=item C<get_empty_schema()>

 Description: Returns a Schema that has no tables. In effect, this
              Schema is totally "empty."
 Params:      none
 Returns:     A "empty" Schema object.

3038 3039
=back

3040 3041 3042 3043
=cut

sub get_empty_schema {
    my ($class) = @_;
3044
    return $class->deserialize_abstract(Dumper({}), SCHEMA_VERSION);
3045 3046
}

3047 3048
1;

3049
__END__
3050 3051 3052

=head1 ABSTRACT DATA TYPES

3053 3054 3055 3056 3057
The size and range data provided here is only
intended as a guide.  See your database's Bugzilla
module (in this directory) for the most up-to-date
values for these data types.  The following
abstract data types are used:
3058 3059 3060 3061 3062

=over 4

=item C<BOOLEAN>

3063 3064
Logical value 0 or 1 where 1 is true, 0 is false.

3065 3066
=item C<INT1>

3067 3068
Integer values (-128 - 127 or 0 - 255 unsigned).

3069 3070
=item C<INT2>

3071 3072
Integer values (-32,768 - 32767 or 0 - 65,535 unsigned).

3073 3074
=item C<INT3>

3075 3076
Integer values (-8,388,608 - 8,388,607 or 0 - 16,777,215 unsigned)

3077 3078
=item C<INT4>

3079 3080 3081
Integer values (-2,147,483,648 - 2,147,483,647 or 0 - 4,294,967,295 
unsigned)

3082 3083
=item C<SMALLSERIAL>

3084
An auto-increment L</INT2>
3085

3086 3087
=item C<MEDIUMSERIAL>

3088 3089
An auto-increment L</INT3>

3090 3091
=item C<INTSERIAL>

3092 3093
An auto-increment L</INT4>

3094 3095
=item C<TINYTEXT>

3096
Variable length string of characters up to 255 (2^8 - 1) characters wide.
3097

3098 3099
=item C<MEDIUMTEXT>

3100 3101
Variable length string of characters up to 4000 characters wide.
May be longer on some databases.
3102

3103
=item C<LONGTEXT>
3104

3105
Variable length string of characters up to 16M (2^24 - 1) characters wide.
3106

3107 3108
=item C<LONGBLOB>

3109 3110
Variable length string of binary data up to 4M (2^32 - 1) bytes wide

3111 3112
=item C<DATETIME>

3113 3114 3115 3116 3117 3118 3119
DATETIME support varies from database to database, however, it's generally 
safe to say that DATETIME entries support all date/time combinations greater
than 1900-01-01 00:00:00.  Note that the format used is C<YYYY-MM-DD hh:mm:ss>
to be safe, though it's possible that your database may not require
leading zeros.  For greatest compatibility, however, please make sure dates 
are formatted as above for queries to guarantee consistent results.

3120 3121 3122 3123
=back

Database-specific subclasses should define the implementation for these data
types as a hash reference stored internally in the schema object as
3124
C<db_specific>. This is typically done in overridden L<_initialize> method.
3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140

The following abstract boolean values should also be defined on a
database-specific basis:

=over 4

=item C<TRUE>

=item C<FALSE>

=back

=head1 SEE ALSO

L<Bugzilla::DB>

3141 3142
L<http://www.bugzilla.org/docs/developer.html#sql-schema>

3143
=cut
3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159

=head1 B<Methods in need of POD>

=over

=item get_table_indexes_abstract

=item get_create_database_sql

=item get_add_fks_sql

=item get_fk_ddl

=item get_drop_fk_sql

=back