Pg.pm 9.69 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Dave Miller <davem00@aol.com>
#                 Gayathri Swaminath <gayathrik00@aol.com>
#                 Jeroen Ruigrok van der Werven <asmodai@wxs.nl>
#                 Dave Lawrence <dkl@redhat.com>
#                 Tomas Kopal <Tomas.Kopal@altap.cz>
25
#                 Max Kanat-Alexander <mkanat@bugzilla.org>
26
#                 Lance Larsh <lance.larsh@oracle.com>
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

=head1 NAME

Bugzilla::DB::Pg - Bugzilla database compatibility layer for PostgreSQL

=head1 DESCRIPTION

This module overrides methods of the Bugzilla::DB module with PostgreSQL
specific implementation. It is instantiated by the Bugzilla::DB module
and should never be used directly.

For interface details see L<Bugzilla::DB> and L<DBI>.

=cut

package Bugzilla::DB::Pg;

use strict;

use Bugzilla::Error;
47
use DBD::Pg;
48 49 50 51

# This module extends the DB interface via inheritance
use base qw(Bugzilla::DB);

52
use constant BLOB_TYPE => { pg_type => DBD::Pg::PG_BYTEA };
53

54
sub new {
55 56 57
    my ($class, $params) = @_;
    my ($user, $pass, $host, $dbname, $port) = 
        @$params{qw(db_user db_pass db_host db_name db_port)};
58

59 60 61 62 63
    # The default database name for PostgreSQL. We have
    # to connect to SOME database, even if we have
    # no $dbname parameter.
    $dbname ||= 'template1';

64
    # construct the DSN from the parameters we got
65
    my $dsn = "dbi:Pg:dbname=$dbname";
66
    $dsn .= ";host=$host" if $host;
67
    $dsn .= ";port=$port" if $port;
68 69 70 71 72

    # This stops Pg from printing out lots of "NOTICE" messages when
    # creating tables.
    $dsn .= ";options='-c client_min_messages=warning'";

73 74
    my $attrs = { pg_enable_utf8 => Bugzilla->params->{'utf8'} };

75 76
    my $self = $class->db_new({ dsn => $dsn, user => $user, 
                                pass => $pass, attrs => $attrs });
77 78 79

    # all class local variables stored in DBI derived class needs to have
    # a prefix 'private_'. See DBI documentation.
80
    $self->{private_bz_tables_locked} = "";
81 82
    # Needed by TheSchwartz
    $self->{private_bz_dsn} = $dsn;
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

    bless ($self, $class);

    return $self;
}

# if last_insert_id is supported on PostgreSQL by lowest DBI/DBD version
# supported by Bugzilla, this implementation can be removed.
sub bz_last_key {
    my ($self, $table, $column) = @_;

    my $seq = $table . "_" . $column . "_seq";
    my ($last_insert_id) = $self->selectrow_array("SELECT CURRVAL('$seq')");

    return $last_insert_id;
}

100 101 102 103 104 105
sub sql_group_concat {
    my ($self, $text, $separator) = @_;
    $separator ||= "','";
    return "array_to_string(array_accum($text), $separator)";
}

106 107 108 109 110 111 112 113 114 115 116 117
sub sql_istring {
    my ($self, $string) = @_;

    return "LOWER(${string}::text)";
}

sub sql_position {
    my ($self, $fragment, $text) = @_;

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

118
sub sql_regexp {
119 120
    my ($self, $expr, $pattern, $nocheck, $real_pattern) = @_;
    $real_pattern ||= $pattern;
121

122
    $self->bz_check_regexp($real_pattern) if !$nocheck;
123

124
    return "${expr}::text ~* $pattern";
125 126 127
}

sub sql_not_regexp {
128 129
    my ($self, $expr, $pattern, $nocheck, $real_pattern) = @_;
    $real_pattern ||= $pattern;
130

131
    $self->bz_check_regexp($real_pattern) if !$nocheck;
132

133
    return "${expr}::text !~* $pattern" 
134 135 136
}

sub sql_limit {
137
    my ($self, $limit, $offset) = @_;
138 139 140 141 142 143 144 145

    if (defined($offset)) {
        return "LIMIT $limit OFFSET $offset";
    } else {
        return "LIMIT $limit";
    }
}

146 147 148 149 150 151
sub sql_from_days {
    my ($self, $days) = @_;

    return "TO_TIMESTAMP(${days}::int, 'J')::date";
}

152 153 154
sub sql_to_days {
    my ($self, $date) = @_;

155
    return "TO_CHAR(${date}::date, 'J')::int";
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
}

sub sql_date_format {
    my ($self, $date, $format) = @_;
    
    $format = "%Y.%m.%d %H:%i:%s" if !$format;

    $format =~ s/\%Y/YYYY/g;
    $format =~ s/\%y/YY/g;
    $format =~ s/\%m/MM/g;
    $format =~ s/\%d/DD/g;
    $format =~ s/\%a/Dy/g;
    $format =~ s/\%H/HH24/g;
    $format =~ s/\%i/MI/g;
    $format =~ s/\%s/SS/g;

    return "TO_CHAR($date, " . $self->quote($format) . ")";
}

sub sql_interval {
176
    my ($self, $interval, $units) = @_;
177
    
178
    return "$interval * INTERVAL '1 $units'";
179 180
}

181 182 183 184 185 186
sub sql_string_concat {
    my ($self, @params) = @_;
    
    # Postgres 7.3 does not support concatenating of different types, so we
    # need to cast both parameters to text. Version 7.4 seems to handle this
    # properly, so when we stop support 7.3, this can be removed.
187
    return '(CAST(' . join(' AS text) || CAST(', @params) . ' AS text))';
188 189
}

190 191 192 193 194 195 196 197 198
# Tell us whether or not a particular sequence exists in the DB.
sub bz_sequence_exists {
    my ($self, $seq_name) = @_;
    my $exists = $self->selectrow_array(
        'SELECT 1 FROM pg_statio_user_sequences WHERE relname = ?',
        undef, $seq_name);
    return $exists || 0;
}

199 200 201 202 203 204
sub bz_explain {
    my ($self, $sql) = @_;
    my $explain = $self->selectcol_arrayref("EXPLAIN ANALYZE $sql");
    return join("\n", @$explain);
}

205 206 207 208 209 210 211 212
#####################################################################
# Custom Database Setup
#####################################################################

sub bz_setup_database {
    my $self = shift;
    $self->SUPER::bz_setup_database(@_);

213 214 215 216 217 218 219 220 221 222 223 224 225 226
    # Custom Functions
    my $function = 'array_accum';
    my $array_accum = $self->selectrow_array(
        'SELECT 1 FROM pg_proc WHERE proname = ?', undef, $function);
    if (!$array_accum) {
        print "Creating function $function...\n";
        $self->do("CREATE AGGREGATE array_accum (
                       SFUNC = array_append,
                       BASETYPE = anyelement,
                       STYPE = anyarray,
                       INITCOND = '{}' 
                   )");
    }

227 228 229 230
    # PostgreSQL doesn't like having *any* index on the thetext
    # field, because it can't have index data longer than 2770
    # characters on that field.
    $self->bz_drop_index('longdescs', 'longdescs_thetext_idx');
231 232 233 234
    # Same for all the comments fields in the fulltext table.
    $self->bz_drop_index('bugs_fulltext', 'bugs_fulltext_comments_idx');
    $self->bz_drop_index('bugs_fulltext', 
                         'bugs_fulltext_comments_noprivate_idx');
235 236 237 238 239

    # PostgreSQL also wants an index for calling LOWER on
    # login_name, which we do with sql_istrcmp all over the place.
    $self->bz_add_index('profiles', 'profiles_login_name_lower_idx', 
        {FIELDS => ['LOWER(login_name)'], TYPE => 'UNIQUE'});
240 241 242 243 244 245 246 247 248 249 250 251

    # Now that Bugzilla::Object uses sql_istrcmp, other tables
    # also need a LOWER() index.
    _fix_case_differences('fielddefs', 'name');
    $self->bz_add_index('fielddefs', 'fielddefs_name_lower_idx',
        {FIELDS => ['LOWER(name)'], TYPE => 'UNIQUE'});
    _fix_case_differences('keyworddefs', 'name');
    $self->bz_add_index('keyworddefs', 'keyworddefs_name_lower_idx',
        {FIELDS => ['LOWER(name)'], TYPE => 'UNIQUE'});
    _fix_case_differences('products', 'name');
    $self->bz_add_index('products', 'products_name_lower_idx',
        {FIELDS => ['LOWER(name)'], TYPE => 'UNIQUE'});
252 253 254 255 256 257 258 259 260 261

    # bz_rename_column didn't correctly rename the sequence.
    if ($self->bz_column_info('fielddefs', 'id')
        && $self->bz_sequence_exists('fielddefs_fieldid_seq')) 
    {
        print "Fixing fielddefs_fieldid_seq sequence...\n";
        $self->do("ALTER TABLE fielddefs_fieldid_seq RENAME TO fielddefs_id_seq");
        $self->do("ALTER TABLE fielddefs ALTER COLUMN id
                    SET DEFAULT NEXTVAL('fielddefs_id_seq')");
    }
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
}

# Renames things that differ only in case.
sub _fix_case_differences {
    my ($table, $field) = @_;
    my $dbh = Bugzilla->dbh;

    my $duplicates = $dbh->selectcol_arrayref(
          "SELECT DISTINCT LOWER($field) FROM $table 
        GROUP BY LOWER($field) HAVING COUNT(LOWER($field)) > 1");

    foreach my $name (@$duplicates) {
        my $dups = $dbh->selectcol_arrayref(
            "SELECT $field FROM $table WHERE LOWER($field) = ?",
            undef, $name);
        my $primary = shift @$dups;
        foreach my $dup (@$dups) {
            my $new_name = "${dup}_";
            # Make sure the new name isn't *also* a duplicate.
            while (1) {
                last if (!$dbh->selectrow_array(
                             "SELECT 1 FROM $table WHERE LOWER($field) = ?",
                              undef, lc($new_name)));
                $new_name .= "_";
            }
            print "$table '$primary' and '$dup' have names that differ",
                  " only in case.\nRenaming '$dup' to '$new_name'...\n";
            $dbh->do("UPDATE $table SET $field = ? WHERE $field = ?",
                     undef, $new_name, $dup);
        }
    }
293 294
}

295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
#####################################################################
# Custom Schema Information Functions
#####################################################################

# Pg includes the PostgreSQL system tables in table_list_real, so 
# we need to remove those.
sub bz_table_list_real {
    my $self = shift;

    my @full_table_list = $self->SUPER::bz_table_list_real(@_);
    # All PostgreSQL system tables start with "pg_" or "sql_"
    my @table_list = grep(!/(^pg_)|(^sql_)/, @full_table_list);
    return @table_list;
}

310
1;