DB.pm 75.4 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

package Bugzilla::DB;

10
use 5.10.1;
11 12 13 14
use strict;

use DBI;

15
# Inherit the DB class from DBI::db.
16
use parent -norequire, qw(DBI::db);
17

18
use Bugzilla::Constants;
19
use Bugzilla::Install::Requirements;
20
use Bugzilla::Install::Util qw(install_string);
21
use Bugzilla::Install::Localconfig;
22
use Bugzilla::Util;
23
use Bugzilla::Error;
24
use Bugzilla::DB::Schema;
25
use Bugzilla::Version;
26

27
use List::Util qw(max);
28
use Storable qw(dclone);
29

30 31 32 33 34
#####################################################################
# Constants
#####################################################################

use constant BLOB_TYPE => DBI::SQL_BLOB;
35
use constant ISOLATION_LEVEL => 'REPEATABLE READ';
36

37 38 39 40 41 42 43 44 45 46 47 48
# Set default values for what used to be the enum types.  These values
# are no longer stored in localconfig.  If we are upgrading from a
# Bugzilla with enums to a Bugzilla without enums, we use the
# enum values.
#
# The values that you see here are ONLY DEFAULTS. They are only used
# the FIRST time you run checksetup.pl, IF you are NOT upgrading from a
# Bugzilla with enums. After that, they are either controlled through
# the Bugzilla UI or through the DB.
use constant ENUM_DEFAULTS => {
    bug_severity  => ['blocker', 'critical', 'major', 'normal',
                      'minor', 'trivial', 'enhancement'],
49
    priority     => ["Highest", "High", "Normal", "Low", "Lowest", "---"],
50 51
    op_sys       => ["All","Windows","Mac OS","Linux","Other"],
    rep_platform => ["All","PC","Macintosh","Other"],
52 53
    bug_status   => ["UNCONFIRMED","CONFIRMED","IN_PROGRESS","RESOLVED",
                     "VERIFIED"],
54
    resolution   => ["","FIXED","INVALID","WONTFIX", "DUPLICATE","WORKSFORME"],
55 56
};

57 58 59 60 61
# The character that means "OR" in a boolean fulltext search. If empty,
# the database doesn't support OR searches in fulltext searches.
# Used by Bugzilla::Bug::possible_duplicates.
use constant FULLTEXT_OR => '';

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
# These are used in regular expressions to mean "the start or end of a word".
#
# We don't use [[:<:]] and [[:>:]], even though they mean
# "start and end of a word" and are supported by both MySQL and PostgreSQL,
# because they don't work if your search starts or ends with a non-alphanumeric
# character, and there's a fair chance somebody will want to use the "word"
# search to search flags for something like "review+".
#
# We do use [:almum:] because it is supported by at least MySQL and
# PostgreSQL, and hopefully will get us as much Unicode support as possible,
# depending on how well the regexp engines of the various databases support
# Unicode.
use constant WORD_START => '(^|[^[:alnum:]])';
use constant WORD_END   => '($|[^[:alnum:]])';

77 78 79 80 81 82
# On most databases, in order to drop an index, you have to first drop
# the foreign keys that use that index. However, on some databases,
# dropping the FK immediately before dropping the index causes problems
# and doesn't need to be done anyway, so those DBs set this to 0.
use constant INDEX_DROPS_REQUIRE_FK_DROPS => 1;

83 84 85 86 87 88 89 90 91 92 93
#####################################################################
# Overridden Superclass Methods 
#####################################################################

sub quote {
    my $self = shift;
    my $retval = $self->SUPER::quote(@_);
    trick_taint($retval) if defined $retval;
    return $retval;
}

94 95 96 97
#####################################################################
# Connection Methods
#####################################################################

98
sub connect_shadow {
99 100 101
    my $params = Bugzilla->params;
    die "Tried to connect to non-existent shadowdb" 
        unless $params->{'shadowdb'};
102

103 104 105 106 107 108 109 110 111 112
    # Instead of just passing in a new hashref, we locally modify the
    # values of "localconfig", because some drivers access it while
    # connecting.
    my %connect_params = %{ Bugzilla->localconfig };
    $connect_params{db_host} = $params->{'shadowdbhost'};
    $connect_params{db_name} = $params->{'shadowdb'};
    $connect_params{db_port} = $params->{'shadowdbport'};
    $connect_params{db_sock} = $params->{'shadowdbsock'};

    return _connect(\%connect_params);
113 114
}

115
sub connect_main {
116
    my $lc = Bugzilla->localconfig;
117
    return _connect(Bugzilla->localconfig); 
118 119 120
}

sub _connect {
121
    my ($params) = @_;
122

123
    my $driver = $params->{db_driver};
124
    my $pkg_module = DB_MODULE->{lc($driver)}->{db};
125 126

    # do the actual import
127
    eval ("require $pkg_module")
128
        || die ("'$driver' is not a valid choice for \$db_driver in "
129
                . " localconfig: " . $@);
130 131

    # instantiate the correct DB specific module
132
    my $dbh = $pkg_module->new($params);
133 134 135 136 137 138 139

    return $dbh;
}

sub _handle_error {
    require Carp;

140 141 142
    # Cut down the error string to a reasonable size
    $_[0] = substr($_[0], 0, 2000) . ' ... ' . substr($_[0], -2000)
        if length($_[0]) > 4000;
143 144 145 146
    $_[0] = Carp::longmess($_[0]);
    return 0; # Now let DBI handle raising the error
}

147 148 149
sub bz_check_requirements {
    my ($output) = @_;

150 151
    my $lc = Bugzilla->localconfig;
    my $db = DB_MODULE->{lc($lc->{db_driver})};
152

153 154
    # Only certain values are allowed for $db_driver.
    if (!defined $db) {
155
        die "$lc->{db_driver} is not a valid choice for \$db_driver in"
156 157 158 159
            . bz_locations()->{'localconfig'};
    }

    # Check the existence and version of the DBD that we need.
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    my $dbd = $db->{dbd};
    _bz_check_dbd($db, $output);

    # We don't try to connect to the actual database if $db_check is
    # disabled.
    unless ($lc->{db_check}) {
        print "\n" if $output;
        return;
    }

    # And now check the version of the database server itself.
    my $dbh = _get_no_db_connection();
    $dbh->bz_check_server_version($db, $output);

    print "\n" if $output;
}

sub _bz_check_dbd {
    my ($db, $output) = @_;

    my $dbd = $db->{dbd};
181
    unless (have_vers($dbd, $output)) {
182
        my $sql_server = $db->{name};
183 184
        my $command = install_command($dbd);
        my $root    = ROOT_USER;
185 186
        my $dbd_mod = $dbd->{module};
        my $dbd_ver = $dbd->{version};
187
        die <<EOT;
188

189
For $sql_server, Bugzilla requires that perl's $dbd_mod $dbd_ver or later be
190 191 192 193 194 195
installed. To install this module, run the following command (as $root):

    $command

EOT
    }
196
}
197

198 199
sub bz_check_server_version {
    my ($self, $db, $output) = @_;
200

201 202
    my $sql_vers = $self->bz_server_version;
    $self->disconnect;
203

204
    my $sql_want = $db->{db_version};
205
    my $version_ok = vers_cmp($sql_vers, $sql_want) > -1 ? 1 : 0;
206 207

    my $sql_server = $db->{name};
208 209 210 211 212 213
    if ($output) {
        Bugzilla::Install::Requirements::_checking_for({
            package => $sql_server, wanted => $sql_want,
            found   => $sql_vers, ok => $version_ok });
    }

214 215
    # Check what version of the database server is installed and let
    # the user know if the version is too old to be used with Bugzilla.
216
    if (!$version_ok) {
217
        die <<EOT;
218 219 220 221 222 223 224

Your $sql_server v$sql_vers is too old. Bugzilla requires version
$sql_want or later of $sql_server. Please download and install a
newer version.

EOT
    }
225

226 227
    # This is used by subclasses.
    return $sql_vers;
228 229 230 231 232 233 234
}

# Note that this function requires that localconfig exist and
# be valid.
sub bz_create_database {
    my $dbh;
    # See if we can connect to the actual Bugzilla database.
235
    my $conn_success = eval { $dbh = connect_main() };
236
    my $db_name = Bugzilla->localconfig->{db_name};
237 238 239

    if (!$conn_success) {
        $dbh = _get_no_db_connection();
240
        say "Creating database $db_name...";
241 242

        # Try to create the DB, and if we fail print a friendly error.
243 244 245 246 247 248 249 250
        my $success  = eval {
            my @sql = $dbh->_bz_schema->get_create_database_sql($db_name);
            # This ends with 1 because this particular do doesn't always
            # return something.
            $dbh->do($_) foreach @sql; 1;
        };
        if (!$success) {
            my $error = $dbh->errstr || $@;
251
            chomp($error);
252 253 254
            die "The '$db_name' database could not be created.",
                " The error returned was:\n\n    $error\n\n",
                _bz_connect_error_reasons();
255 256 257 258 259 260 261 262 263 264
        }
    }

    $dbh->disconnect;
}

# A helper for bz_create_database and bz_check_requirements.
sub _get_no_db_connection {
    my ($sql_server) = @_;
    my $dbh;
265 266
    my %connect_params = %{ Bugzilla->localconfig };
    $connect_params{db_name} = '';
267
    my $conn_success = eval {
268
        $dbh = _connect(\%connect_params);
269 270
    };
    if (!$conn_success) {
271 272
        my $driver = $connect_params{db_driver};
        my $sql_server = DB_MODULE->{lc($driver)}->{name};
273
        # Can't use $dbh->errstr because $dbh is undef.
274
        my $error = $DBI::errstr || $@;
275
        chomp($error);
276 277
        die "There was an error connecting to $sql_server:\n\n",
            "    $error\n\n", _bz_connect_error_reasons(), "\n";
278 279 280 281 282 283 284 285 286
    }
    return $dbh;    
}

# Just a helper because we have to re-use this text.
# We don't use this in db_new because it gives away the database
# username, and db_new errors can show up on CGIs.
sub _bz_connect_error_reasons {
    my $lc_file = bz_locations()->{'localconfig'};
287 288
    my $lc      = Bugzilla->localconfig;
    my $db      = DB_MODULE->{lc($lc->{db_driver})};
289 290 291 292 293 294 295 296 297 298
    my $server  = $db->{name};

return <<EOT;
This might have several reasons:

* $server is not running.
* $server is running, but there is a problem either in the
  server configuration or the database access rights. Read the Bugzilla
  Guide in the doc directory. The section about database configuration
  should help.
299
* Your password for the '$lc->{db_user}' user, specified in \$db_pass, is 
300 301 302 303 304 305 306 307
  incorrect, in '$lc_file'.
* There is a subtle problem with Perl, DBI, or $server. Make
  sure all settings in '$lc_file' are correct. If all else fails, set
  '\$db_check' to 0.

EOT
}

308
# List of abstract methods we are checking the derived class implements
309
our @_abstract_methods = qw(new sql_regexp sql_not_regexp sql_limit sql_to_days
310
                            sql_date_format sql_date_math bz_explain
311
                            sql_group_concat);
312

313
# This overridden import method will check implementation of inherited classes
314 315 316 317 318 319 320 321 322 323
# for missing implementation of abstract methods
# See http://perlmonks.thepen.com/44265.html
sub import {
    my $pkg = shift;

    # do not check this module
    if ($pkg ne __PACKAGE__) {
        # make sure all abstract methods are implemented
        foreach my $meth (@_abstract_methods) {
            $pkg->can($meth)
324
                or die("Class $pkg does not define method $meth");
325 326 327 328 329 330 331 332 333 334 335 336 337
        }
    }

    # Now we want to call our superclass implementation.
    # If our superclass is Exporter, which is using caller() to find
    # a namespace to populate, we need to adjust for this extra call.
    # All this can go when we stop using deprecated functions.
    my $is_exporter = $pkg->isa('Exporter');
    $Exporter::ExportLevel++ if $is_exporter;
    $pkg->SUPER::import(@_);
    $Exporter::ExportLevel-- if $is_exporter;
}

338 339 340 341 342 343 344 345 346 347 348 349 350
sub sql_istrcmp {
    my ($self, $left, $right, $op) = @_;
    $op ||= "=";

    return $self->sql_istring($left) . " $op " . $self->sql_istring($right);
}

sub sql_istring {
    my ($self, $string) = @_;

    return "LOWER($string)";
}

351 352 353 354 355 356 357
sub sql_iposition {
    my ($self, $fragment, $text) = @_;
    $fragment = $self->sql_istring($fragment);
    $text = $self->sql_istring($text);
    return $self->sql_position($fragment, $text);
}

358 359 360 361 362 363
sub sql_position {
    my ($self, $fragment, $text) = @_;

    return "POSITION($fragment IN $text)";
}

364 365 366 367
sub sql_group_by {
    my ($self, $needed_columns, $optional_columns) = @_;

    my $expression = "GROUP BY $needed_columns";
368
    $expression .= ", " . $optional_columns if $optional_columns;
369 370 371
    
    return $expression;
}
372

373 374 375
sub sql_string_concat {
    my ($self, @params) = @_;
    
376
    return '(' . join(' || ', @params) . ')';
377 378
}

379 380
sub sql_string_until {
    my ($self, $string, $substring) = @_;
381 382 383 384 385

    my $position = $self->sql_position($substring, $string);
    return "CASE WHEN $position != 0"
             . " THEN SUBSTR($string, 1, $position - 1)"
             . " ELSE $string END";
386 387
}

388
sub sql_in {
389 390 391 392
    my ($self, $column_name, $in_list_ref, $negate) = @_;
    return " $column_name "
             . ($negate ? "NOT " : "")
             . "IN (" . join(',', @$in_list_ref) . ") ";
393 394
}

395 396 397 398 399
sub sql_fulltext_search {
    my ($self, $column, $text) = @_;

    # This is as close as we can get to doing full text search using
    # standard ANSI SQL, without real full text search support. DB specific
400
    # modules should override this, as this will be always much slower.
401 402 403 404

    # make the string lowercase to do case insensitive search
    my $lower_text = lc($text);

405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
    # split the text we're searching for into separate words. As a hack
    # to allow quicksearch to work, if the field starts and ends with
    # a double-quote, then we don't split it into words. We can't use
    # Text::ParseWords here because it gets very confused by unbalanced
    # quotes, which breaks searches like "don't try this" (because of the
    # unbalanced single-quote in "don't").
    my @words;
    if ($lower_text =~ /^"/ and $lower_text =~ /"$/) {
        $lower_text =~ s/^"//;
        $lower_text =~ s/"$//;
        @words = ($lower_text);
    }
    else {
        @words = split(/\s+/, $lower_text);
    }
420

421 422
    # surround the words with wildcards and SQL quotes so we can use them
    # in LIKE search clauses
423
    @words = map($self->quote("\%$_\%"), @words);
424

425
    # untaint words, since they are safe to use now that we've quoted them
426
    trick_taint($_) foreach @words;
427

428 429 430 431
    # turn the words into a set of LIKE search clauses
    @words = map("LOWER($column) LIKE $_", @words);

    # search for occurrences of all specified words in the column
432
    return join (" AND ", @words), "CASE WHEN (" . join(" AND ", @words) . ") THEN 1 ELSE 0 END";
433 434
}

435 436 437 438
#####################################################################
# General Info Methods
#####################################################################

439 440 441 442
# XXX - Needs to be documented.
sub bz_server_version {
    my ($self) = @_;
    return $self->get_info(18); # SQL_DBMS_VER
443 444
}

445 446 447
sub bz_last_key {
    my ($self, $table, $column) = @_;

448 449
    return $self->last_insert_id(Bugzilla->localconfig->{db_name}, undef, 
                                 $table, $column);
450 451
}

452 453 454 455 456 457 458 459 460
sub bz_check_regexp {
    my ($self, $pattern) = @_;

    eval { $self->do("SELECT " . $self->sql_regexp($self->quote("a"), $pattern, 1)) };

    $@ && ThrowUserError('illegal_regexp', 
        { value => $pattern, dberror => $self->errstr }); 
}

461 462 463 464 465 466 467
#####################################################################
# Database Setup
#####################################################################

sub bz_setup_database {
    my ($self) = @_;

468 469 470
    # If we haven't ever stored a serialized schema,
    # set up the bz_schema table and store it.
    $self->_bz_init_schema_storage();
471 472 473 474
   
    # We don't use bz_table_list here, because that uses _bz_real_schema.
    # We actually want the table list from the ABSTRACT_SCHEMA in
    # Bugzilla::DB::Schema.
475
    my @desired_tables = $self->_bz_schema->get_table_list();
476 477
    my $bugs_exists = $self->bz_table_info('bugs');
    if (!$bugs_exists) {
478
        say install_string('db_table_setup');
479
    }
480 481

    foreach my $table_name (@desired_tables) {
482
        $self->bz_add_table($table_name, { silently => !$bugs_exists });
483 484 485
    }
}

486
# This really just exists to get overridden in Bugzilla::DB::Mysql.
487
sub bz_enum_initial_values {
488 489 490 491
    return ENUM_DEFAULTS;
}

sub bz_populate_enum_tables {
492 493 494 495 496
    my ($self) = @_; 

    my $any_severities = $self->selectrow_array(
        'SELECT 1 FROM bug_severity ' . $self->sql_limit(1));
    print install_string('db_enum_setup'), "\n  " if !$any_severities;
497 498 499 500 501

    my $enum_values = $self->bz_enum_initial_values();
    while (my ($table, $values) = each %$enum_values) {
        $self->_bz_populate_enum_table($table, $values);
    }
502 503

    print "\n" if !$any_severities;
504 505
}

506 507 508
sub bz_setup_foreign_keys {
    my ($self) = @_;

509 510 511 512
    # profiles_activity was the first table to get foreign keys,
    # so if it doesn't have them, then we're setting up FKs
    # for the first time, and should be quieter about it.
    my $activity_fk = $self->bz_fk_info('profiles_activity', 'userid');
513 514
    my $any_fks = $activity_fk && $activity_fk->{created};
    if (!$any_fks) {
515
        say get_text('install_fk_setup');
516 517
    }

518
    my @tables = $self->bz_table_list();
519
    foreach my $table (@tables) {
520
        my @columns = $self->bz_table_columns($table);
521
        my %add_fks;
522
        foreach my $column (@columns) {
523 524 525 526 527 528 529 530 531 532 533
            # First we check for any FKs that have created => 0,
            # in the _bz_real_schema. This also picks up FKs with
            # created => 1, but bz_add_fks will ignore those.
            my $fk = $self->bz_fk_info($table, $column);
            # Then we check the abstract schema to see if there
            # should be an FK on this column, but one wasn't set in the
            # _bz_real_schema for some reason. We do this to handle
            # various problems caused by upgrading from versions
            # prior to 4.2, and also to handle problems caused
            # by enabling an extension pre-4.2, disabling it for
            # the 4.2 upgrade, and then re-enabling it later.
534
            unless ($fk && $fk->{created}) {
535 536 537 538 539
                my $standard_def = 
                    $self->_bz_schema->get_column_abstract($table, $column);
                if (exists $standard_def->{REFERENCES}) {
                    $fk = dclone($standard_def->{REFERENCES});
                }
540
            }
541 542

            $add_fks{$column} = $fk if $fk;
543
        }
544
        $self->bz_add_fks($table, \%add_fks, { silently => !$any_fks });
545 546 547
    }
}

548 549 550 551
# This is used by contrib/bzdbcopy.pl, mostly.
sub bz_drop_foreign_keys {
    my ($self) = @_;

552
    my @tables = $self->bz_table_list();
553
    foreach my $table (@tables) {
554
        my @columns = $self->bz_table_columns($table);
555 556 557 558 559 560
        foreach my $column (@columns) {
            $self->bz_drop_fk($table, $column);
        }
    }
}

561 562 563 564
#####################################################################
# Schema Modification Methods
#####################################################################

565
sub bz_add_column {
566
    my ($self, $table, $name, $new_def, $init_value) = @_;
567 568

    # You can't add a NOT NULL column to a table with
569 570 571 572 573 574
    # no DEFAULT statement, unless you have an init_value.
    # SERIAL types are an exception, though, because they can
    # auto-populate.
    if ( $new_def->{NOTNULL} && !exists $new_def->{DEFAULT} 
         && !defined $init_value && $new_def->{TYPE} !~ /SERIAL/)
    {
575 576
        ThrowCodeError('column_not_null_without_default',
                       { name => "$table.$name" });
577 578 579 580 581 582
    }

    my $current_def = $self->bz_column_info($table, $name);

    if (!$current_def) {
        my @statements = $self->_bz_real_schema->get_add_column_ddl(
583 584
            $table, $name, $new_def, 
            defined $init_value ? $self->quote($init_value) : undef);
585 586 587
        print get_text('install_column_add',
                       { column => $name, table => $table }) . "\n"
            if Bugzilla->usage_mode == USAGE_MODE_CMDLINE;
588 589 590
        foreach my $sql (@statements) {
            $self->do($sql);
        }
591 592 593 594 595 596 597 598 599 600 601 602 603 604

        # To make things easier for callers, if they don't specify
        # a REFERENCES item, we pull it from the _bz_schema if the
        # column exists there and has a REFERENCES item.
        # bz_setup_foreign_keys will then add this FK at the end of
        # Install::DB.
        my $col_abstract = 
            $self->_bz_schema->get_column_abstract($table, $name);
        if (exists $col_abstract->{REFERENCES}) {
            my $new_fk = dclone($col_abstract->{REFERENCES});
            $new_fk->{created} = 0;
            $new_def->{REFERENCES} = $new_fk;
        }
        
605 606 607 608 609
        $self->_bz_real_schema->set_column($table, $name, $new_def);
        $self->_bz_store_real_schema;
    }
}

610 611
sub bz_add_fk {
    my ($self, $table, $column, $def) = @_;
612 613 614 615
    $self->bz_add_fks($table, { $column => $def });
}

sub bz_add_fks {
616
    my ($self, $table, $column_fks, $options) = @_;
617

618 619
    my %add_these;
    foreach my $column (keys %$column_fks) {
620 621 622 623 624
        my $current_fk = $self->bz_fk_info($table, $column);
        next if ($current_fk and $current_fk->{created});
        my $new_fk = $column_fks->{$column};
        $self->_check_references($table, $column, $new_fk);
        $add_these{$column} = $new_fk;
625 626 627 628
        if (Bugzilla->usage_mode == USAGE_MODE_CMDLINE 
            and !$options->{silently}) 
        {
            print get_text('install_fk_add',
629 630
                           { table => $table, column => $column, 
                             fk    => $new_fk }), "\n";
631
        }
632 633 634 635 636 637 638 639
    }

    return if !scalar(keys %add_these);

    my @sql = $self->_bz_real_schema->get_add_fks_sql($table, \%add_these);
    $self->do($_) foreach @sql;

    foreach my $column (keys %add_these) {
640 641 642
        my $fk_def = $add_these{$column};
        $fk_def->{created} = 1;
        $self->_bz_real_schema->set_fk($table, $column, $fk_def);
643
    }
644 645

    $self->_bz_store_real_schema();
646 647
}

648
sub bz_alter_column {
649
    my ($self, $table, $name, $new_def, $set_nulls_to) = @_;
650 651 652 653

    my $current_def = $self->bz_column_info($table, $name);

    if (!$self->_bz_schema->columns_equal($current_def, $new_def)) {
654 655 656 657 658 659
        # You can't change a column to be NOT NULL if you have no DEFAULT
        # and no value for $set_nulls_to, if there are any NULL values 
        # in that column.
        if ($new_def->{NOTNULL} && 
            !exists $new_def->{DEFAULT} && !defined $set_nulls_to)
        {
660 661 662
            # Check for NULLs
            my $any_nulls = $self->selectrow_array(
                "SELECT 1 FROM $table WHERE $name IS NULL");
663 664
            ThrowCodeError('column_not_null_no_default_alter', 
                           { name => "$table.$name" }) if ($any_nulls);
665
        }
666 667
        # Preserve foreign key definitions in the Schema object when altering
        # types.
668 669
        if (my $fk = $self->bz_fk_info($table, $name)) {
            $new_def->{REFERENCES} = $fk;
670
        }
671 672
        $self->bz_alter_column_raw($table, $name, $new_def, $current_def,
                                   $set_nulls_to);
673 674 675 676 677
        $self->_bz_real_schema->set_column($table, $name, $new_def);
        $self->_bz_store_real_schema;
    }
}

678

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
# bz_alter_column_raw($table, $name, $new_def, $current_def)
#
# Description: A helper function for bz_alter_column.
#              Alters a column in the database
#              without updating any Schema object. Generally
#              should only be called by bz_alter_column.
#              Used when either: (1) You don't yet have a Schema
#              object but you need to alter a column, for some reason.
#              (2) You need to alter a column for some database-specific
#              reason.
# Params:      $table   - The name of the table the column is on.
#              $name    - The name of the column you're changing.
#              $new_def - The abstract definition that you are changing
#                         this column to.
#              $current_def - (optional) The current definition of the
#                             column. Will be used in the output message,
#                             if given.
696 697
#              $set_nulls_to - The same as the param of the same name
#                              from bz_alter_column.
698 699 700
# Returns:     nothing
#
sub bz_alter_column_raw {
701
    my ($self, $table, $name, $new_def, $current_def, $set_nulls_to) = @_;
702
    my @statements = $self->_bz_real_schema->get_alter_column_ddl(
703 704
        $table, $name, $new_def,
        defined $set_nulls_to ? $self->quote($set_nulls_to) : undef);
705
    my $new_ddl = $self->_bz_schema->get_type_ddl($new_def);
706
    say "Updating column $name in table $table ...";
707
    if (defined $current_def) {
708
        my $old_ddl = $self->_bz_schema->get_type_ddl($current_def);
709
        say "Old: $old_ddl";
710
    }
711
    say "New: $new_ddl";
712 713 714
    $self->do($_) foreach (@statements);
}

715 716 717 718 719 720 721 722 723
sub bz_alter_fk {
    my ($self, $table, $column, $fk_def) = @_;
    my $current_fk = $self->bz_fk_info($table, $column);
    ThrowCodeError('column_alter_nonexistent_fk',
                   { table => $table, column => $column }) if !$current_fk;
    $self->bz_drop_fk($table, $column);
    $self->bz_add_fk($table, $column, $fk_def);
}

724 725 726 727 728 729
sub bz_add_index {
    my ($self, $table, $name, $definition) = @_;

    my $index_exists = $self->bz_index_info($table, $name);

    if (!$index_exists) {
730
        $self->bz_add_index_raw($table, $name, $definition);
731 732 733 734 735
        $self->_bz_real_schema->set_index($table, $name, $definition);
        $self->_bz_store_real_schema;
    }
}

736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
# bz_add_index_raw($table, $name, $silent)
#
# Description: A helper function for bz_add_index.
#              Adds an index to the database
#              without updating any Schema object. Generally
#              should only be called by bz_add_index.
#              Used when you don't yet have a Schema
#              object but you need to add an index, for some reason.
# Params:      $table  - The name of the table the index is on.
#              $name   - The name of the index you're adding.
#              $definition - The abstract index definition, in hashref
#                            or arrayref format.
#              $silent - (optional) If specified and true, don't output
#                        any message about this change.
# Returns:     nothing
#
sub bz_add_index_raw {
    my ($self, $table, $name, $definition, $silent) = @_;
    my @statements = $self->_bz_schema->get_add_index_ddl(
        $table, $name, $definition);
    print "Adding new index '$name' to the $table table ...\n" unless $silent;
    $self->do($_) foreach (@statements);
}

760
sub bz_add_table {
761
    my ($self, $name, $options) = @_;
762 763 764 765

    my $table_exists = $self->bz_table_info($name);

    if (!$table_exists) {
766
        $self->_bz_add_table_raw($name, $options);
767 768 769 770 771 772 773 774
        my $table_def = dclone($self->_bz_schema->get_table_abstract($name));

        my %fields = @{$table_def->{FIELDS}};
        foreach my $col (keys %fields) {
            # Foreign Key references have to be added by Install::DB after
            # initial table creation, because column names have changed
            # over history and it's impossible to keep track of that info
            # in ABSTRACT_SCHEMA.
775 776 777
            next unless exists $fields{$col}->{REFERENCES};
            $fields{$col}->{REFERENCES}->{created} =
                $self->_bz_real_schema->FK_ON_CREATE;
778
        }
779
        
780
        $self->_bz_real_schema->add_table($name, $table_def);
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
        $self->_bz_store_real_schema;
    }
}

# _bz_add_table_raw($name) - Private
#
# Description: A helper function for bz_add_table.
#              Creates a table in the database without
#              updating any Schema object. Generally
#              should only be called by bz_add_table and by
#              _bz_init_schema_storage. Used when you don't
#              yet have a Schema object but you need to
#              add a table, for some reason.
# Params:      $name - The name of the table you're creating. 
#                  The definition for the table is pulled from 
#                  _bz_schema.
# Returns:     nothing
#
sub _bz_add_table_raw {
800
    my ($self, $name, $options) = @_;
801
    my @statements = $self->_bz_schema->get_table_ddl($name);
802 803 804
    if (Bugzilla->usage_mode == USAGE_MODE_CMDLINE
        and !$options->{silently})
    {
805
        say install_string('db_table_new', { table => $name });
806
    }
807 808 809
    $self->do($_) foreach (@statements);
}

810
sub _bz_add_field_table {
811
    my ($self, $name, $schema_ref) = @_;
812 813
    # We do nothing if the table already exists.
    return if $self->bz_table_info($name);
814 815 816 817 818 819 820 821

    # Copy this so that we're not modifying the passed reference.
    # (This avoids modifying a constant in Bugzilla::DB::Schema.)
    my %table_schema = %$schema_ref;
    my %indexes = @{ $table_schema{INDEXES} };
    my %fixed_indexes;
    foreach my $key (keys %indexes) {
        $fixed_indexes{$name . "_" . $key} = $indexes{$key};
822
    }
823 824 825
    # INDEXES is supposed to be an arrayref, so we have to convert back.
    my @indexes_array = %fixed_indexes;
    $table_schema{INDEXES} = \@indexes_array;
826
    # We add this to the abstract schema so that bz_add_table can find it.
827
    $self->_bz_schema->add_table($name, \%table_schema);
828 829 830
    $self->bz_add_table($name);
}

831 832 833 834
sub bz_add_field_tables {
    my ($self, $field) = @_;
    
    $self->_bz_add_field_table($field->name,
835
                               $self->_bz_schema->FIELD_TABLE_SCHEMA, $field->type);
836 837 838
    if ($field->type == FIELD_TYPE_MULTI_SELECT) {
        my $ms_table = "bug_" . $field->name;
        $self->_bz_add_field_table($ms_table,
839
            $self->_bz_schema->MULTI_SELECT_VALUE_TABLE);
840

841 842 843 844 845
        $self->bz_add_fks($ms_table, 
            { bug_id => {TABLE => 'bugs', COLUMN => 'bug_id',
                         DELETE => 'CASCADE'},

              value  => {TABLE  => $field->name, COLUMN => 'value'} });
846 847 848
    }
}

849 850 851 852 853 854 855
sub bz_drop_field_tables {
    my ($self, $field) = @_;
    if ($field->type == FIELD_TYPE_MULTI_SELECT) {
        $self->bz_drop_table('bug_' . $field->name);
    }
    $self->bz_drop_table($field->name);
}
856

857 858 859 860 861 862 863 864
sub bz_drop_column {
    my ($self, $table, $column) = @_;

    my $current_def = $self->bz_column_info($table, $column);

    if ($current_def) {
        my @statements = $self->_bz_real_schema->get_drop_column_ddl(
            $table, $column);
865 866 867
        print get_text('install_column_drop', 
                       { table => $table, column => $column }) . "\n"
            if Bugzilla->usage_mode == USAGE_MODE_CMDLINE;
868
        foreach my $sql (@statements) {
869 870 871 872
            # Because this is a deletion, we don't want to die hard if
            # we fail because of some local customization. If something
            # is already gone, that's fine with us!
            eval { $self->do($sql); } or warn "Failed SQL: [$sql] Error: $@";
873 874 875 876 877 878
        }
        $self->_bz_real_schema->delete_column($table, $column);
        $self->_bz_store_real_schema;
    }
}

879 880 881
sub bz_drop_fk {
    my ($self, $table, $column) = @_;

882 883
    my $fk_def = $self->bz_fk_info($table, $column);
    if ($fk_def and $fk_def->{created}) {
884
        print get_text('install_fk_drop',
885
                       { table => $table, column => $column, fk => $fk_def })
886
            . "\n" if Bugzilla->usage_mode == USAGE_MODE_CMDLINE;
887
        my @statements = 
888
            $self->_bz_real_schema->get_drop_fk_sql($table, $column, $fk_def);
889 890 891 892 893 894
        foreach my $sql (@statements) {
            # Because this is a deletion, we don't want to die hard if
            # we fail because of some local customization. If something
            # is already gone, that's fine with us!
            eval { $self->do($sql); } or warn "Failed SQL: [$sql] Error: $@";
        }
895 896 897 898 899 900
        # Under normal circumstances, we don't permanently drop the fk--
        # we want checksetup to re-create it again later. The only
        # time that FKs get permanently dropped is if the column gets
        # dropped.
        $fk_def->{created} = 0;
        $self->_bz_real_schema->set_fk($table, $column, $fk_def);
901 902 903 904 905
        $self->_bz_store_real_schema;
    }

}

906
sub bz_get_related_fks {
907 908
    my ($self, $table, $column) = @_;
    my @tables = $self->_bz_real_schema->get_table_list();
909
    my @related;
910 911 912
    foreach my $check_table (@tables) {
        my @columns = $self->bz_table_columns($check_table);
        foreach my $check_column (@columns) {
913
            my $fk = $self->bz_fk_info($check_table, $check_column);
914 915 916 917
            if ($fk 
                and (($fk->{TABLE} eq $table and $fk->{COLUMN} eq $column)
                     or ($check_column eq $column and $check_table eq $table)))
            {
918
                push(@related, [$check_table, $check_column, $fk]);
919 920 921 922
            }
        } # foreach $column
    } # foreach $table

923 924 925 926 927 928 929 930 931 932 933
    return \@related;
}

sub bz_drop_related_fks {
    my $self = shift;
    my $related = $self->bz_get_related_fks(@_);
    foreach my $item (@$related) {
        my ($table, $column) = @$item;
        $self->bz_drop_fk($table, $column);
    }
    return $related;
934 935
}

936 937 938 939 940 941
sub bz_drop_index {
    my ($self, $table, $name) = @_;

    my $index_exists = $self->bz_index_info($table, $name);

    if ($index_exists) {
942 943 944 945 946
        if ($self->INDEX_DROPS_REQUIRE_FK_DROPS) {
            # We cannot delete an index used by a FK.
            foreach my $column (@{$index_exists->{FIELDS}}) {
                $self->bz_drop_related_fks($table, $column);
            }
947
        }
948
        $self->bz_drop_index_raw($table, $name);
949 950 951 952 953
        $self->_bz_real_schema->delete_index($table, $name);
        $self->_bz_store_real_schema;        
    }
}

954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
# bz_drop_index_raw($table, $name, $silent)
#
# Description: A helper function for bz_drop_index.
#              Drops an index from the database
#              without updating any Schema object. Generally
#              should only be called by bz_drop_index.
#              Used when either: (1) You don't yet have a Schema 
#              object but you need to drop an index, for some reason.
#              (2) You need to drop an index that somehow got into the
#              database but doesn't exist in Schema.
# Params:      $table  - The name of the table the index is on.
#              $name   - The name of the index you're dropping.
#              $silent - (optional) If specified and true, don't output
#                        any message about this change.
# Returns:     nothing
#
sub bz_drop_index_raw {
    my ($self, $table, $name, $silent) = @_;
    my @statements = $self->_bz_schema->get_drop_index_ddl(
        $table, $name);
    print "Removing index '$name' from the $table table...\n" unless $silent;
975 976 977 978 979 980
    foreach my $sql (@statements) {
        # Because this is a deletion, we don't want to die hard if
        # we fail because of some local customization. If something
        # is already gone, that's fine with us!
        eval { $self->do($sql) } or warn "Failed SQL: [$sql] Error: $@";
    }
981 982
}

983 984 985 986 987 988 989
sub bz_drop_table {
    my ($self, $name) = @_;

    my $table_exists = $self->bz_table_info($name);

    if ($table_exists) {
        my @statements = $self->_bz_schema->get_drop_table_ddl($name);
990 991
        print get_text('install_table_drop', { name => $name }) . "\n"
            if Bugzilla->usage_mode == USAGE_MODE_CMDLINE;
992 993 994 995 996 997
        foreach my $sql (@statements) {
            # Because this is a deletion, we don't want to die hard if
            # we fail because of some local customization. If something
            # is already gone, that's fine with us!
            eval { $self->do($sql); } or warn "Failed SQL: [$sql] Error: $@";
        }
998 999 1000 1001 1002
        $self->_bz_real_schema->delete_table($name);
        $self->_bz_store_real_schema;
    }
}

1003 1004 1005 1006 1007 1008 1009 1010
sub bz_fk_info {
    my ($self, $table, $column) = @_;
    my $col_info = $self->bz_column_info($table, $column);
    return undef if !$col_info;
    my $fk = $col_info->{REFERENCES};
    return $fk;
}

1011 1012 1013 1014 1015 1016 1017
sub bz_rename_column {
    my ($self, $table, $old_name, $new_name) = @_;

    my $old_col_exists  = $self->bz_column_info($table, $old_name);

    if ($old_col_exists) {
        my $already_renamed = $self->bz_column_info($table, $new_name);
1018
            ThrowCodeError('db_rename_conflict',
1019 1020
                           { old => "$table.$old_name", 
                             new => "$table.$new_name" }) if $already_renamed;
1021 1022
        my @statements = $self->_bz_real_schema->get_rename_column_ddl(
            $table, $old_name, $new_name);
1023 1024 1025 1026 1027

        print get_text('install_column_rename', 
                       { old => "$table.$old_name", new => "$table.$new_name" })
               . "\n" if Bugzilla->usage_mode == USAGE_MODE_CMDLINE;

1028 1029 1030 1031 1032 1033 1034 1035
        foreach my $sql (@statements) {
            $self->do($sql);
        }
        $self->_bz_real_schema->rename_column($table, $old_name, $new_name);
        $self->_bz_store_real_schema;
    }
}

1036 1037 1038 1039 1040 1041 1042 1043
sub bz_rename_table {
    my ($self, $old_name, $new_name) = @_;
    my $old_table = $self->bz_table_info($old_name);
    return if !$old_table;

    my $new = $self->bz_table_info($new_name);
    ThrowCodeError('db_rename_conflict', { old => $old_name,
                                           new => $new_name }) if $new;
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055

    # FKs will all have the wrong names unless we drop and then let them
    # be re-created later. Under normal circumstances, checksetup.pl will
    # automatically re-create these dropped FKs at the end of its DB upgrade
    # run, so we don't need to re-create them in this method.
    my @columns = $self->bz_table_columns($old_name);
    foreach my $column (@columns) {
        # these just return silently if there's no FK to drop
        $self->bz_drop_fk($old_name, $column);
        $self->bz_drop_related_fks($old_name, $column);
    }

1056 1057 1058 1059 1060 1061 1062 1063 1064
    my @sql = $self->_bz_real_schema->get_rename_table_sql($old_name, $new_name);
    print get_text('install_table_rename', 
                   { old => $old_name, new => $new_name }) . "\n"
        if Bugzilla->usage_mode == USAGE_MODE_CMDLINE;
    $self->do($_) foreach @sql;
    $self->_bz_real_schema->rename_table($old_name, $new_name);
    $self->_bz_store_real_schema;
}

1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
sub bz_set_next_serial_value {
    my ($self, $table, $column, $value) = @_;
    if (!$value) {
        $value = $self->selectrow_array("SELECT MAX($column) FROM $table") || 0;
        $value++;
    }
    my @sql = $self->_bz_real_schema->get_set_serial_sql($table, $column, $value);
    $self->do($_) foreach @sql;
}

1075 1076 1077 1078
#####################################################################
# Schema Information Methods
#####################################################################

1079 1080 1081
sub _bz_schema {
    my ($self) = @_;
    return $self->{private_bz_schema} if exists $self->{private_bz_schema};
1082 1083 1084
    my @module_parts = split('::', ref $self);
    my $module_name  = pop @module_parts;
    $self->{private_bz_schema} = Bugzilla::DB::Schema->new($module_name);
1085 1086 1087
    return $self->{private_bz_schema};
}

1088 1089 1090 1091
# _bz_get_initial_schema()
#
# Description: A protected method, intended for use only by Bugzilla::DB
#              and subclasses. Used to get the initial Schema that will
1092
#              be written to disk for _bz_init_schema_storage. You probably
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
#              want to use _bz_schema or _bz_real_schema instead of this
#              method.
# Params:      none
# Returns:     A Schema object that can be serialized and written to disk
#              for _bz_init_schema_storage.
sub _bz_get_initial_schema {
    my ($self) = @_;
    return $self->_bz_schema->get_empty_schema();
}

1103 1104
sub bz_column_info {
    my ($self, $table, $column) = @_;
1105 1106 1107 1108
    my $def = $self->_bz_real_schema->get_column_abstract($table, $column);
    # We dclone it so callers can't modify the Schema.
    $def = dclone($def) if defined $def;
    return $def;
1109 1110 1111 1112
}

sub bz_index_info {
    my ($self, $table, $index) = @_;
1113 1114 1115 1116 1117 1118
    my $index_def =
        $self->_bz_real_schema->get_index_abstract($table, $index);
    if (ref($index_def) eq 'ARRAY') {
        $index_def = {FIELDS => $index_def, TYPE => ''};
    }
    return $index_def;
1119 1120
}

1121 1122 1123 1124 1125
sub bz_table_info {
    my ($self, $table) = @_;
    return $self->_bz_real_schema->get_table_abstract($table);
}

1126

1127 1128
sub bz_table_columns {
    my ($self, $table) = @_;
1129
    return $self->_bz_real_schema->get_table_columns($table);
1130 1131
}

1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
sub bz_table_indexes {
    my ($self, $table) = @_;
    my $indexes = $self->_bz_real_schema->get_table_indexes_abstract($table);
    my %return_indexes;
    # We do this so that they're always hashes.
    foreach my $name (keys %$indexes) {
        $return_indexes{$name} = $self->bz_index_info($table, $name);
    }
    return \%return_indexes;
}

1143 1144 1145 1146 1147
sub bz_table_list {
    my ($self) = @_;
    return $self->_bz_real_schema->get_table_list();
}

1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
#####################################################################
# Protected "Real Database" Schema Information Methods
#####################################################################

# Only Bugzilla::DB and subclasses should use these methods.
# If you need a method that does the same thing as one of these
# methods, use the version without _real on the end.

# bz_table_columns_real($table)
#
# Description: Returns a list of columns on a given table
#              as the table actually is, on the disk.
# Params:      $table - Name of the table.
# Returns:     An array of column names.
#
sub bz_table_columns_real {
    my ($self, $table) = @_;
    my $sth = $self->column_info(undef, undef, $table, '%');
    return @{ $self->selectcol_arrayref($sth, {Columns => [4]}) };
}

# bz_table_list_real()
#
# Description: Gets a list of tables in the current
#              database, directly from the disk.
# Params:      none
# Returns:     An array containing table names.
sub bz_table_list_real {
    my ($self) = @_;
    my $table_sth = $self->table_info(undef, undef, undef, "TABLE");
    return @{$self->selectcol_arrayref($table_sth, { Columns => [3] })};
}

1181 1182 1183
#####################################################################
# Transaction Methods
#####################################################################
1184

1185 1186 1187 1188
sub bz_in_transaction {
    return $_[0]->{private_bz_transaction_count} ? 1 : 0;
}

1189 1190 1191
sub bz_start_transaction {
    my ($self) = @_;

1192 1193
    if ($self->bz_in_transaction) {
        $self->{private_bz_transaction_count}++;
1194 1195 1196
    } else {
        # Turn AutoCommit off and start a new transaction
        $self->begin_work();
1197 1198 1199 1200 1201
        # REPEATABLE READ means "We work on a snapshot of the DB that
        # is created when we execute our first SQL statement." It's
        # what we need in Bugzilla to be safe, for what we do.
        # Different DBs have different defaults for their isolation
        # level, so we just set it here manually.
1202 1203 1204 1205
        if ($self->ISOLATION_LEVEL) {
            $self->do('SET TRANSACTION ISOLATION LEVEL ' 
                      . $self->ISOLATION_LEVEL);
        }
1206
        $self->{private_bz_transaction_count} = 1;
1207 1208 1209 1210 1211
    }
}

sub bz_commit_transaction {
    my ($self) = @_;
1212 1213 1214 1215
    
    if ($self->{private_bz_transaction_count} > 1) {
        $self->{private_bz_transaction_count}--;
    } elsif ($self->bz_in_transaction) {
1216
        $self->commit();
1217 1218 1219
        $self->{private_bz_transaction_count} = 0;
    } else {
       ThrowCodeError('not_in_transaction');
1220 1221 1222 1223 1224 1225
    }
}

sub bz_rollback_transaction {
    my ($self) = @_;

1226 1227 1228
    # Unlike start and commit, if we rollback at any point it happens
    # instantly, even if we're in a nested transaction.
    if (!$self->bz_in_transaction) {
1229 1230 1231
        ThrowCodeError("not_in_transaction");
    } else {
        $self->rollback();
1232
        $self->{private_bz_transaction_count} = 0;
1233 1234 1235
    }
}

1236 1237 1238 1239
#####################################################################
# Subclass Helpers
#####################################################################

1240
sub db_new {
1241 1242 1243
    my ($class, $params) = @_;
    my ($dsn, $user, $pass, $override_attrs) = 
        @$params{qw(dsn user pass attrs)};
1244 1245

    # set up default attributes used to connect to the database
1246 1247 1248 1249 1250 1251 1252
    # (may be overridden by DB driver implementations)
    my $attributes = { RaiseError => 0,
                       AutoCommit => 1,
                       PrintError => 0,
                       ShowErrorStatement => 1,
                       HandleError => \&_handle_error,
                       TaintIn => 1,
1253 1254 1255
                       # See https://rt.perl.org/rt3/Public/Bug/Display.html?id=30933
                       # for the reason to use NAME instead of NAME_lc (bug 253696).
                       FetchHashKeyName => 'NAME',
1256 1257 1258 1259 1260 1261 1262
                     };

    if ($override_attrs) {
        foreach my $key (keys %$override_attrs) {
            $attributes->{$key} = $override_attrs->{$key};
        }
    }
1263 1264

    # connect using our known info to the specified db
1265 1266 1267
    my $self = DBI->connect($dsn, $user, $pass, $attributes)
        or die "\nCan't connect to the database.\nError: $DBI::errstr\n"
        . "  Is your database installed and up and running?\n  Do you have"
1268
        . " the correct username and password selected in localconfig?\n\n";
1269 1270 1271 1272

    # RaiseError was only set to 0 so that we could catch the 
    # above "die" condition.
    $self->{RaiseError} = 1;
1273 1274 1275 1276 1277 1278

    bless ($self, $class);

    return $self;
}

1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
#####################################################################
# Private Methods
#####################################################################

=begin private

=head1 PRIVATE METHODS

These methods really are private. Do not override them in subclasses.

=over 4

=item C<_init_bz_schema_storage>

 Description: Initializes the bz_schema table if it contains nothing.
 Params:      none
 Returns:     nothing

=cut

sub _bz_init_schema_storage {
    my ($self) = @_;

1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
    my $table_size;
    eval {
        $table_size = 
            $self->selectrow_array("SELECT COUNT(*) FROM bz_schema");
    };

    if (!$table_size) {
        my $init_schema = $self->_bz_get_initial_schema;
        my $store_me = $init_schema->serialize_abstract();
        my $schema_version = $init_schema->SCHEMA_VERSION;

        # If table_size is not defined, then we hit an error reading the
        # bz_schema table, which means it probably doesn't exist yet. So,
        # we have to create it. If we failed above for some other reason,
        # we'll see the failure here.
        # However, we must create the table after we do get_initial_schema,
        # because some versions of get_initial_schema read that the table
        # exists and then add it to the Schema, where other versions don't.
        if (!defined $table_size) {
            $self->_bz_add_table_raw('bz_schema');
        }
1323

1324
        say install_string('db_schema_init');
1325 1326 1327
        my $sth = $self->prepare("INSERT INTO bz_schema "
                                 ." (schema_data, version) VALUES (?,?)");
        $sth->bind_param(1, $store_me, $self->BLOB_TYPE);
1328
        $sth->bind_param(2, $schema_version);
1329
        $sth->execute();
1330 1331 1332 1333 1334 1335 1336 1337

        # And now we have to update the on-disk schema to hold the bz_schema
        # table, if the bz_schema table didn't exist when we were called.
        if (!defined $table_size) {
            $self->_bz_real_schema->add_table('bz_schema',
                $self->_bz_schema->get_table_abstract('bz_schema'));
            $self->_bz_store_real_schema;
        }
1338 1339 1340 1341 1342 1343 1344 1345
    } 
    # Sanity check
    elsif ($table_size > 1) {
        # We tell them to delete the newer one. Better to have checksetup
        # run migration code too many times than to have it not run the
        # correct migration code at all.
        die "Attempted to initialize the schema but there are already "
            . " $table_size copies of it stored.\nThis should never happen.\n"
1346 1347
            . " Compare the rows of the bz_schema table and delete the "
            . "newer one(s).";
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
    }
}

=item C<_bz_real_schema()>

 Description: Returns a Schema object representing the database
              that is being used in the current installation.
 Params:      none
 Returns:     A C<Bugzilla::DB::Schema> object representing the database
              as it exists on the disk.
1358

1359
=cut
1360

1361 1362 1363 1364
sub _bz_real_schema {
    my ($self) = @_;
    return $self->{private_real_schema} if exists $self->{private_real_schema};

1365 1366 1367 1368 1369 1370 1371
    my $bz_schema;
    unless ($bz_schema = Bugzilla->memcached->get({ key => 'bz_schema' })) {
        $bz_schema = $self->selectrow_arrayref(
            "SELECT schema_data, version FROM bz_schema"
        );
        Bugzilla->memcached->set({ key => 'bz_schema', value => $bz_schema });
    }
1372

1373
    (die "_bz_real_schema tried to read the bz_schema table but it's empty!")
1374
        if !$bz_schema;
1375

1376 1377
    $self->{private_real_schema} =
        $self->_bz_schema->deserialize_abstract($bz_schema->[0], $bz_schema->[1]);
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391

    return $self->{private_real_schema};
}

=item C<_bz_store_real_schema()>

 Description: Stores the _bz_real_schema structures in the database
              for later recovery. Call this function whenever you make
              a change to the _bz_real_schema.
 Params:      none
 Returns:     nothing

 Precondition: $self->{_bz_real_schema} must exist.

1392 1393 1394 1395
=back

=end private

1396
=cut
1397

1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
sub _bz_store_real_schema {
    my ($self) = @_;

    # Make sure that there's a schema to update
    my $table_size = $self->selectrow_array("SELECT COUNT(*) FROM bz_schema");

    die "Attempted to update the bz_schema table but there's nothing "
        . "there to update. Run checksetup." unless $table_size;

    # We want to store the current object, not one
    # that we read from the database. So we use the actual hash
    # member instead of the subroutine call. If the hash
    # member is not defined, we will (and should) fail.
1411 1412 1413
    my $update_schema = $self->{private_real_schema};
    my $store_me = $update_schema->serialize_abstract();
    my $schema_version = $update_schema->SCHEMA_VERSION;
1414 1415 1416
    my $sth = $self->prepare("UPDATE bz_schema 
                                 SET schema_data = ?, version = ?");
    $sth->bind_param(1, $store_me, $self->BLOB_TYPE);
1417
    $sth->bind_param(2, $schema_version);
1418
    $sth->execute();
1419 1420

    Bugzilla->memcached->clear({ key => 'bz_schema' });
1421 1422
}

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
# For bz_populate_enum_tables
sub _bz_populate_enum_table {
    my ($self, $table, $valuelist) = @_;

    my $sql_table = $self->quote_identifier($table);

    # Check if there are any table entries
    my $table_size = $self->selectrow_array("SELECT COUNT(*) FROM $sql_table");

    # If the table is empty...
    if (!$table_size) {
1434
        print " $table";
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
        my $insert = $self->prepare(
            "INSERT INTO $sql_table (value,sortkey) VALUES (?,?)");
        my $sortorder = 0;
        my $maxlen    = max(map(length($_), @$valuelist)) + 2;
        foreach my $value (@$valuelist) {
            $sortorder += 100;
            $insert->execute($value, $sortorder);
        }
    }
}

1446 1447 1448
# This is used before adding a foreign key to a column, to make sure
# that the database won't fail adding the key.
sub _check_references {
1449 1450 1451
    my ($self, $table, $column, $fk) = @_;
    my $foreign_table = $fk->{TABLE};
    my $foreign_column = $fk->{COLUMN};
1452

1453 1454 1455 1456
    # We use table aliases because sometimes we join a table to itself,
    # and we can't use the same table name on both sides of the join.
    # We also can't use the words "table" or "foreign" because those are
    # reserved words.
1457
    my $bad_values = $self->selectcol_arrayref(
1458 1459 1460 1461 1462
        "SELECT DISTINCT tabl.$column 
           FROM $table AS tabl LEFT JOIN $foreign_table AS forn
                ON tabl.$column = forn.$foreign_column
          WHERE forn.$foreign_column IS NULL
                AND tabl.$column IS NOT NULL");
1463 1464

    if (@$bad_values) {
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
        my $delete_action = $fk->{DELETE} || '';
        if ($delete_action eq 'CASCADE') {
            $self->do("DELETE FROM $table WHERE $column IN (" 
                      . join(',', ('?') x @$bad_values)  . ")",
                      undef, @$bad_values);
            if (Bugzilla->usage_mode == USAGE_MODE_CMDLINE) {
                print "\n", get_text('install_fk_invalid_fixed',
                    { table => $table, column => $column,
                      foreign_table => $foreign_table,
                      foreign_column => $foreign_column,
                      'values' => $bad_values, action => 'delete' }), "\n";
            }
        }
        elsif ($delete_action eq 'SET NULL') {
            $self->do("UPDATE $table SET $column = NULL
                        WHERE $column IN ("
                      . join(',', ('?') x @$bad_values)  . ")",
                      undef, @$bad_values);
            if (Bugzilla->usage_mode == USAGE_MODE_CMDLINE) {
                print "\n", get_text('install_fk_invalid_fixed',
                    { table => $table, column => $column,
                      foreign_table => $foreign_table, 
                      foreign_column => $foreign_column,
                      'values' => $bad_values, action => 'null' }), "\n";
            }
        }
        else {
1492
            die "\n", get_text('install_fk_invalid',
1493 1494 1495 1496 1497
                { table => $table, column => $column,
                  foreign_table => $foreign_table,
                  foreign_column => $foreign_column,
                 'values' => $bad_values }), "\n";
        }
1498 1499 1500
    }
}

1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
1;

__END__

=head1 NAME

Bugzilla::DB - Database access routines, using L<DBI>

=head1 SYNOPSIS

1511 1512 1513
  # Obtain db handle
  use Bugzilla::DB;
  my $dbh = Bugzilla->dbh;
1514

1515 1516 1517 1518 1519 1520 1521 1522
  # prepare a query using DB methods
  my $sth = $dbh->prepare("SELECT " .
                          $dbh->sql_date_format("creation_ts", "%Y%m%d") .
                          " FROM bugs WHERE bug_status != 'RESOLVED' " .
                          $dbh->sql_limit(1));

  # Execute the query
  $sth->execute;
1523

1524 1525
  # Get the results
  my @result = $sth->fetchrow_array;
1526

1527
  # Schema Modification
1528
  $dbh->bz_add_column($table, $name, \%definition, $init_value);
1529
  $dbh->bz_add_index($table, $name, $definition);
1530
  $dbh->bz_add_table($name);
1531
  $dbh->bz_drop_index($table, $name);
1532
  $dbh->bz_drop_table($name);
1533
  $dbh->bz_alter_column($table, $name, \%new_def, $set_nulls_to);
1534 1535
  $dbh->bz_drop_column($table, $column);
  $dbh->bz_rename_column($table, $old_name, $new_name);
1536

1537
  # Schema Information
1538 1539 1540
  my $column = $dbh->bz_column_info($table, $column);
  my $index  = $dbh->bz_index_info($table, $index);

1541 1542
=head1 DESCRIPTION

1543 1544 1545 1546 1547 1548 1549 1550
Functions in this module allows creation of a database handle to connect
to the Bugzilla database. This should never be done directly; all users
should use the L<Bugzilla> module to access the current C<dbh> instead.

This module also contains methods extending the returned handle with
functionality which is different between databases allowing for easy
customization for particular database via inheritance. These methods
should be always preffered over hard-coding SQL commands.
1551

1552 1553 1554 1555 1556
=head1 CONSTANTS

Subclasses of Bugzilla::DB are required to define certain constants. These
constants are required to be subroutines or "use constant" variables.

1557
=over
1558

1559 1560 1561 1562 1563
=item C<BLOB_TYPE>

The C<\%attr> argument that must be passed to bind_param in order to 
correctly escape a C<LONGBLOB> type.

1564 1565 1566 1567 1568 1569 1570 1571
=item C<ISOLATION_LEVEL>

The argument that this database should send to 
C<SET TRANSACTION ISOLATION LEVEL> when starting a transaction. If you
override this in a subclass, the isolation level you choose should
be as strict as or more strict than the default isolation level defined in
L<Bugzilla::DB>.

1572 1573 1574
=back


1575 1576 1577 1578 1579 1580
=head1 CONNECTION

A new database handle to the required database can be created using this
module. This is normally done by the L<Bugzilla> module, and so these routines
should not be called from anywhere else.

1581 1582
=head2 Functions

1583
=over
1584 1585 1586

=item C<connect_main>

1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
=over

=item B<Description>

Function to connect to the main database, returning a new database handle.

=item B<Params>

=over

=item C<$no_db_name> (optional) - If true, connect to the database
server, but don't connect to a specific database. This is only used 
when creating a database. After you create the database, you should 
re-create a new Bugzilla::DB object without using this parameter. 

=back

=item B<Returns>

New instance of the DB class

=back
1609 1610 1611

=item C<connect_shadow>

1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
=over

=item B<Description>

Function to connect to the shadow database, returning a new database handle.
This routine C<die>s if no shadow database is configured.

=item B<Params> (none)

=item B<Returns>

A new instance of the DB class

=back

=item C<bz_check_requirements>

=over

=item B<Description>

Checks to make sure that you have the correct DBD and database version 
installed for the database that Bugzilla will be using. Prints a message 
and exits if you don't pass the requirements.

If C<$db_check> is false (from F<localconfig>), we won't check the 
database version.

=item B<Params>

=over

=item C<$output> - C<true> if the function should display informational 
output about what it's doing, such as versions found.
1646

1647 1648 1649 1650 1651
=back

=item B<Returns> (nothing)

=back
1652 1653


1654
=item C<bz_create_database>
1655

1656
=over
1657

1658
=item B<Description>
1659

1660 1661 1662
Creates an empty database with the name C<$db_name>, if that database 
doesn't already exist. Prints an error message and exits if we can't 
create the database.
1663

1664
=item B<Params> (none)
1665

1666 1667 1668
=item B<Returns> (nothing)

=back
1669

1670 1671
=item C<_connect>

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
=over

=item B<Description>

Internal function, creates and returns a new, connected instance of the 
correct DB class.  This routine C<die>s if no driver is specified.

=item B<Params>

=over

=item C<$driver> - name of the database driver to use

=item C<$host> - host running the database we are connecting to

=item C<$dbname> - name of the database to connect to

=item C<$port> - port the database is listening on

=item C<$sock> - socket the database is listening on

=item C<$user> - username used to log in to the database

=item C<$pass> - password used to log in to the database

=back

=item B<Returns>

A new instance of the DB class

=back
1704 1705 1706

=item C<_handle_error>

1707 1708
Function passed to the DBI::connect call for error handling. It shortens the 
error for printing.
1709 1710 1711

=item C<import>

1712 1713 1714
Overrides the standard import method to check that derived class
implements all required abstract methods. Also calls original implementation 
in its super class.
1715 1716 1717

=back

1718
=head1 ABSTRACT METHODS
1719

1720
Note: Methods which can be implemented generically for all DBs are implemented in
1721
this module. If needed, they can be overridden with DB specific code.
1722 1723 1724 1725
Methods which do not have standard implementation are abstract and must
be implemented for all supported databases separately.
To avoid confusion with standard DBI methods, all methods returning string with
formatted SQL command have prefix C<sql_>. All other methods have prefix C<bz_>.
1726

1727 1728 1729
=head2 Constructor

=over
1730

1731 1732
=item C<new>

1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
=over

=item B<Description>

Constructor.  Abstract method, should be overridden by database specific 
code.

=item B<Params>

=over 

=item C<$user> - username used to log in to the database

=item C<$pass> - password used to log in to the database

=item C<$host> - host running the database we are connecting to

=item C<$dbname> - name of the database to connect to

=item C<$port> - port the database is listening on

=item C<$sock> - socket the database is listening on

=back

=item B<Returns>

A new instance of the DB class

=item B<Note>

The constructor should create a DSN from the parameters provided and
then call C<db_new()> method of its super class to create a new
class instance. See L<db_new> description in this module. As per
DBI documentation, all class variables must be prefixed with
"private_". See L<DBI>.

=back

=back

=head2 SQL Generation

=over
1777 1778 1779

=item C<sql_regexp>

1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
=over

=item B<Description>

Outputs SQL regular expression operator for POSIX regex
searches (case insensitive) in format suitable for a given
database.

Abstract method, should be overridden by database specific code.

=item B<Params>

=over

=item C<$expr> - SQL expression for the text to be searched (scalar)

=item C<$pattern> - the regular expression to search for (scalar)

1798 1799 1800 1801 1802
=item C<$nocheck> - true if the pattern should not be tested; false otherwise (boolean)

=item C<$real_pattern> - the real regular expression to search for.
This argument is used when C<$pattern> is a placeholder ('?').

1803 1804 1805 1806 1807 1808 1809
=back

=item B<Returns>

Formatted SQL for regular expression search (e.g. REGEXP) (scalar)

=back
1810 1811 1812

=item C<sql_not_regexp>

1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
=over

=item B<Description>

Outputs SQL regular expression operator for negative POSIX
regex searches (case insensitive) in format suitable for a given
database.

Abstract method, should be overridden by database specific code.

=item B<Params>

1825
Same as L</sql_regexp>.
1826 1827 1828 1829 1830 1831 1832

=item B<Returns>

Formatted SQL for negative regular expression search (e.g. NOT REGEXP) 
(scalar)

=back
1833 1834 1835

=item C<sql_limit>

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
=over

=item B<Description>

Returns SQL syntax for limiting results to some number of rows
with optional offset if not starting from the begining.

Abstract method, should be overridden by database specific code.

=item B<Params>

=over

=item C<$limit> - number of rows to return from query (scalar)

1851
=item C<$offset> - number of rows to skip before counting (scalar)
1852 1853 1854 1855 1856 1857 1858 1859 1860

=back

=item B<Returns>

Formatted SQL for limiting number of rows returned from query
with optional offset (e.g. LIMIT 1, 1) (scalar)

=back
1861

1862 1863
=item C<sql_from_days>

1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
=over

=item B<Description>

Outputs SQL syntax for converting Julian days to date.

Abstract method, should be overridden by database specific code.

=item B<Params>

=over

=item C<$days> - days to convert to date

=back

=item B<Returns>

Formatted SQL for returning Julian days in dates. (scalar)

=back
1885

1886 1887
=item C<sql_to_days>

1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
=over

=item B<Description>

Outputs SQL syntax for converting date to Julian days.

Abstract method, should be overridden by database specific code.

=item B<Params>

=over

=item C<$date> - date to convert to days

=back

=item B<Returns>

Formatted SQL for returning date fields in Julian days. (scalar)

=back
1909 1910 1911

=item C<sql_date_format>

1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
=over

=item B<Description>

Outputs SQL syntax for formatting dates.

Abstract method, should be overridden by database specific code.

=item B<Params>

=over

=item C<$date> - date or name of date type column (scalar)

=item C<$format> - format string for date output (scalar)
(C<%Y> = year, four digits, C<%y> = year, two digits, C<%m> = month,
C<%d> = day, C<%a> = weekday name, 3 letters, C<%H> = hour 00-23,
C<%i> = minute, C<%s> = second)

=back

=item B<Returns>

Formatted SQL for date formatting (scalar)

=back
1938

1939
=item C<sql_date_math>
1940

1941 1942 1943 1944
=over

=item B<Description>

1945
Outputs proper SQL syntax for adding some amount of time to a date.
1946 1947 1948 1949 1950 1951 1952

Abstract method, should be overridden by database specific code.

=item B<Params>

=over

1953
=item C<$date>
1954

1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
C<string> The date being added to or subtracted from.

=item C<$operator>

C<string> Either C<-> or C<+>, depending on whether you're subtracting
or adding.

=item C<$interval>

C<integer> The time interval you're adding or subtracting (e.g. C<30>)

=item C<$units> 

C<string> the units the interval is in (e.g. 'MINUTE')
1969 1970 1971 1972 1973

=back

=item B<Returns>

1974
Formatted SQL for adding or subtracting a date and some amount of time (scalar)
1975 1976

=back
1977

1978 1979
=item C<sql_position>

1980 1981 1982 1983
=over

=item B<Description>

1984
Outputs proper SQL syntax determining position of a substring
1985 1986 1987
(fragment) withing a string (text). Note: if the substring or
text are string constants, they must be properly quoted (e.g. "'pattern'").

1988 1989 1990
It searches for the string in a case-sensitive manner. If you want to do
a case-insensitive search, use L</sql_iposition>.

1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
=item B<Params>

=over

=item C<$fragment> - the string fragment we are searching for (scalar)

=item C<$text> - the text to search (scalar)

=back

=item B<Returns>

Formatted SQL for substring search (scalar)

=back
2006

2007 2008 2009 2010
=item C<sql_iposition>

Just like L</sql_position>, but case-insensitive.

2011 2012
=item C<sql_group_by>

2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
=over

=item B<Description>

Outputs proper SQL syntax for grouping the result of a query.

For ANSI SQL databases, we need to group by all columns we are
querying for (except for columns used in aggregate functions).
Some databases require (or even allow) to specify only one
or few columns if the result is uniquely defined. For those
databases, the default implementation needs to be overloaded.

=item B<Params>

=over

=item C<$needed_columns> - string with comma separated list of columns
we need to group by to get expected result (scalar)

=item C<$optional_columns> - string with comma separated list of all
other columns we are querying for, but which are not in the required list.

=back

=item B<Returns>

Formatted SQL for row grouping (scalar)

=back
2042

2043 2044
=item C<sql_string_concat>

2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
=over

=item B<Description>

Returns SQL syntax for concatenating multiple strings (constants
or values from table columns) together.

=item B<Params>

=over

=item C<@params> - array of column names or strings to concatenate

=back

=item B<Returns>

Formatted SQL for concatenating specified strings

=back
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083

=item C<sql_string_until>

=over

=item B<Description>

Returns SQL for truncating a string at the first occurrence of a certain
substring.

=item B<Params>

Note that both parameters need to be sql-quoted.

=item C<$string> The string we're truncating

=item C<$substring> The substring we're truncating at.

=back
2084 2085 2086

=item C<sql_fulltext_search>

2087 2088 2089 2090
=over

=item B<Description>

2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
Returns one or two SQL expressions for performing a full text search for
specified text on a given column.

If one value is returned, it is a numeric expression that indicates
a match with a positive value and a non-match with zero. In this case,
the DB must support casting numeric expresions to booleans.

If two values are returned, then the first value is a boolean expression
that indicates the presence of a match, and the second value is a numeric
expression that can be used for ranking.
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122

There is a ANSI SQL version of this method implemented using LIKE operator,
but it's not a real full text search. DB specific modules should override 
this, as this generic implementation will be always much slower. This 
generic implementation returns 'relevance' as 0 for no match, or 1 for a 
match.

=item B<Params>

=over

=item C<$column> - name of column to search (scalar)

=item C<$text> - text to search for (scalar)

=back

=item B<Returns>

Formatted SQL for full text search

=back
2123

2124 2125
=item C<sql_istrcmp>

2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
=over

=item B<Description>

Returns SQL for a case-insensitive string comparison.

=item B<Params>

=over

=item C<$left> - What should be on the left-hand-side of the operation.

=item C<$right> - What should be on the right-hand-side of the operation.

=item C<$op> (optional) - What the operation is. Should be a  valid ANSI 
SQL comparison operator, such as C<=>, C<E<lt>>, C<LIKE>, etc. Defaults 
to C<=> if not specified.

=back

=item B<Returns>

A SQL statement that will run the comparison in a case-insensitive fashion.

=item B<Note>

Uses L</sql_istring>, so it has the same performance concerns.
Try to avoid using this function unless absolutely necessary.

Subclass Implementors: Override sql_istring instead of this
function, most of the time (this function uses sql_istring).

=back
2159 2160 2161

=item C<sql_istring>

2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
=over

=item B<Description>

Returns SQL syntax "preparing" a string or text column for case-insensitive 
comparison.

=item B<Params>

=over

=item C<$string> - string to convert (scalar)

=back

=item B<Returns>

Formatted SQL making the string case insensitive.

=item B<Note>

The default implementation simply calls LOWER on the parameter.
If this is used to search on a text column with index, the index
will not be usually used unless it was created as LOWER(column).

=back
2188

2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
=item C<sql_in>

=over

=item B<Description>

Returns SQL syntax for the C<IN ()> operator. 

Only necessary where an C<IN> clause can have more than 1000 items.

=item B<Params>

=over

=item C<$column_name> - Column name (e.g. C<bug_id>)

=item C<$in_list_ref> - an arrayref containing values for C<IN ()>

=back

=item B<Returns>

Formatted SQL for the C<IN> operator.

=back

2215 2216 2217
=back


2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
=head1 IMPLEMENTED METHODS

These methods are implemented in Bugzilla::DB, and only need
to be implemented in subclasses if you need to override them for 
database-compatibility reasons.

=head2 General Information Methods

These methods return information about data in the database.

2228
=over
2229

2230 2231
=item C<bz_last_key>

2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
=over

=item B<Description>

Returns the last serial number, usually from a previous INSERT.

Must be executed directly following the relevant INSERT.
This base implementation uses L<DBI/last_insert_id>. If the
DBD supports it, it is the preffered way to obtain the last
serial index. If it is not supported, the DB-specific code
needs to override this function.

=item B<Params>

=over

=item C<$table> - name of table containing serial column (scalar)

=item C<$column> - name of column containing serial data type (scalar)

=back

=item B<Returns>

Last inserted ID (scalar)

=back

=back
2261

2262 2263 2264 2265 2266
=head2 Database Setup Methods

These methods are used by the Bugzilla installation programs to set up
the database.

2267 2268 2269 2270 2271 2272 2273
=over

=item C<bz_populate_enum_tables>

=over

=item B<Description>
2274

2275 2276 2277 2278
For an upgrade or an initial installation, populates the tables that hold 
the legal values for the old "enum" fields: C<bug_severity>, 
C<resolution>, etc. Prints out information if it inserts anything into the
DB.
2279

2280
=item B<Params> (none)
2281

2282
=item B<Returns> (nothing)
2283

2284
=back
2285 2286 2287 2288

=back


2289 2290
=head2 Schema Modification Methods

2291 2292 2293 2294 2295 2296
These methods modify the current Bugzilla Schema.

Where a parameter says "Abstract index/column definition", it returns/takes
information in the formats defined for indexes and columns in
C<Bugzilla::DB::Schema::ABSTRACT_SCHEMA>.

2297
=over
2298

2299
=item C<bz_add_column>
2300

2301
=over
2302

2303
=item B<Description>
2304

2305 2306 2307 2308
Adds a new column to a table in the database. Prints out a brief statement 
that it did so, to stdout. Note that you cannot add a NOT NULL column that 
has no default -- the database won't know what to set all the NULL
values to.
2309

2310
=item B<Params>
2311

2312
=over
2313

2314
=item C<$table> - the table where the column is being added
2315

2316
=item C<$name> - the name of the new column
2317

2318
=item C<\%definition> - Abstract column definition for the new column
2319

2320 2321
=item C<$init_value> (optional) - An initial value to set the column
to. Required if your column is NOT NULL and has no DEFAULT set.
2322

2323 2324 2325 2326 2327 2328 2329 2330 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 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
=back

=item B<Returns> (nothing)

=back

=item C<bz_add_index>

=over

=item B<Description>

Adds a new index to a table in the database. Prints out a brief statement 
that it did so, to stdout. If the index already exists, we will do nothing.

=item B<Params>

=over

=item C<$table> - The table the new index is on.

=item C<$name>  - A name for the new index.

=item C<$definition> - An abstract index definition. Either a hashref 
or an arrayref.

=back

=item B<Returns> (nothing)

=back

=item C<bz_add_table>

=over

=item B<Description>

Creates a new table in the database, based on the definition for that 
table in the abstract schema.

Note that unlike the other 'add' functions, this does not take a 
definition, but always creates the table as it exists in
L<Bugzilla::DB::Schema/ABSTRACT_SCHEMA>.

If a table with that name already exists, then this function returns 
silently.

=item B<Params>

=over

=item C<$name> - The name of the table you want to create.

=back

=item B<Returns> (nothing)
2380

2381 2382
=back

2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
=item C<bz_drop_index>

=over

=item B<Description>

Removes an index from the database. Prints out a brief statement that it 
did so, to stdout. If the index doesn't exist, we do nothing.

=item B<Params>

=over

=item C<$table> - The table that the index is on.

=item C<$name> - The name of the index that you want to drop.

=back

=item B<Returns> (nothing)

=back

=item C<bz_drop_table>

=over

=item B<Description>

Drops a table from the database. If the table doesn't exist, we just 
return silently.

=item B<Params>

=over

=item C<$name> - The name of the table to drop.

=back

=item B<Returns> (nothing)

=back

=item C<bz_alter_column>

=over

=item B<Description>

Changes the data type of a column in a table. Prints out the changes 
being made to stdout. If the new type is the same as the old type, 
the function returns without changing anything.

=item B<Params>

=over

=item C<$table> - the table where the column is

=item C<$name> - the name of the column you want to change

=item C<\%new_def> - An abstract column definition for the new 
data type of the columm

=item C<$set_nulls_to> (Optional) - If you are changing the column
to be NOT NULL, you probably also want to set any existing NULL columns 
to a particular value. Specify that value here. B<NOTE>: The value should 
not already be SQL-quoted.

=back

=item B<Returns> (nothing)

=back

=item C<bz_drop_column>

=over

=item B<Description>

Removes a column from a database table. If the column doesn't exist, we 
return without doing anything. If we do anything, we print a short 
message to C<stdout> about the change.

=item B<Params>

=over

=item C<$table> - The table where the column is

=item C<$column> - The name of the column you want to drop

=back

=item B<Returns> (nothing)

=back

=item C<bz_rename_column>

=over

=item B<Description>

Renames a column in a database table. If the C<$old_name> column 
doesn't exist, we return without doing anything. If C<$old_name> 
and C<$new_name> both already exist in the table specified, we fail.

=item B<Params>

=over

=item C<$table> - The name of the table containing the column 
that you want to rename

=item C<$old_name> - The current name of the column that you want to rename

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

=back

=item B<Returns> (nothing)

=back

2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534
=item C<bz_rename_table>

=over

=item B<Description>

Renames a table in the database. Does nothing if the table doesn't exist.

Throws an error if the old table exists and there is already a table 
with the new name.

=item B<Params>

=over

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

=item C<$new_name> - What you're renaming the table to.

=back

=item B<Returns> (nothing)

=back

2535
=back
2536

2537 2538
=head2 Schema Information Methods

2539 2540 2541 2542
These methods return information about the current Bugzilla database
schema, as it currently exists on the disk. 

Where a parameter says "Abstract index/column definition", it returns/takes
2543 2544
information in the formats defined for indexes and columns for
L<Bugzilla::DB::Schema/ABSTRACT_SCHEMA>.
2545

2546 2547 2548 2549 2550
=over

=item C<bz_column_info>

=over
2551

2552
=item B<Description>
2553

2554
Get abstract column definition.
2555

2556
=item B<Params>
2557

2558 2559 2560 2561 2562
=over

=item C<$table> - The name of the table the column is in.

=item C<$column> - The name of the column.
2563 2564 2565

=back

2566
=item B<Returns>
2567

2568 2569
An abstract column definition for that column. If the table or column 
does not exist, we return C<undef>.
2570

2571
=back
2572

2573
=item C<bz_index_info>
2574

2575
=over
2576

2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
=item B<Description>

Get abstract index definition.

=item B<Params>

=over

=item C<$table> - The table the index is on.

=item C<$index> - The name of the index.

=back

=item B<Returns>

An abstract index definition for that index, always in hashref format. 
The hashref will always contain the C<TYPE> element, but it will
be an empty string if it's just a normal index.

If the index does not exist, we return C<undef>.

=back
2600

2601 2602 2603
=back


2604 2605 2606 2607 2608
=head2 Transaction Methods

These methods deal with the starting and stopping of transactions 
in the database.

2609
=over
2610

2611 2612 2613 2614 2615
=item C<bz_in_transaction>

Returns C<1> if we are currently in the middle of an uncommitted transaction,
C<0> otherwise.

2616 2617
=item C<bz_start_transaction>

2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
Starts a transaction.

It is OK to call C<bz_start_transaction> when you are already inside of
a transaction. However, you must call L</bz_commit_transaction> as many
times as you called C<bz_start_transaction>, in order for your transaction
to actually commit.

Bugzilla uses C<REPEATABLE READ> transactions.

Returns nothing and takes no parameters.
2628 2629 2630

=item C<bz_commit_transaction>

2631 2632
Ends a transaction, commiting all changes. Returns nothing and takes
no parameters.
2633 2634 2635

=item C<bz_rollback_transaction>

2636 2637
Ends a transaction, rolling back all changes. Returns nothing and takes 
no parameters.
2638

2639 2640 2641
=back


2642 2643 2644 2645 2646
=head1 SUBCLASS HELPERS

Methods in this class are intended to be used by subclasses to help them
with their functions.

2647
=over
2648

2649 2650
=item C<db_new>

2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
=over

=item B<Description>

Constructor

=item B<Params>

=over

=item C<$dsn> - database connection string

=item C<$user> - username used to log in to the database

=item C<$pass> - password used to log in to the database

2667 2668 2669
=item C<\%override_attrs> - set of attributes for DB connection (optional).
You only have to set attributes that you want to be different from
the default attributes set inside of C<db_new>.
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682

=back

=item B<Returns>

A new instance of the DB class

=item B<Note>

The name of this constructor is not C<new>, as that would make
our check for implementation of C<new> by derived class useless.

=back
2683

2684
=back
2685

2686

2687 2688 2689 2690
=head1 SEE ALSO

L<DBI>

2691
L<Bugzilla::Constants/DB_MODULE>
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751

=head1 B<Methods in need of POD>

=over

=item bz_add_fks

=item bz_add_fk

=item bz_drop_index_raw

=item bz_table_info

=item bz_add_index_raw

=item bz_get_related_fks

=item quote

=item bz_drop_fk

=item bz_drop_field_tables

=item bz_drop_related_fks

=item bz_table_columns

=item bz_drop_foreign_keys

=item bz_alter_column_raw

=item bz_table_list_real

=item bz_fk_info

=item bz_setup_database

=item bz_setup_foreign_keys

=item bz_table_indexes

=item bz_check_regexp

=item bz_enum_initial_values

=item bz_alter_fk

=item bz_set_next_serial_value

=item bz_table_list

=item bz_table_columns_real

=item bz_check_server_version

=item bz_server_version

=item bz_add_field_tables

=back