root/branches/release-39/lib/MT/ObjectDriver/Driver/DBI.pm @ 2463

Revision 2463, 16.3 kB (checked in by bchoate, 18 months ago)

Updates to optimize recently_commented_on, category and tag attributes for Entries tag - BugId:79914. Search app can now supply user state - BugId:79906. Fix for 2-digit year bug - BugId:79924

  • Property svn:keywords set to Id Revision
Line 
1# Movable Type (r) Open Source (C) 2001-2008 Six Apart, Ltd.
2# This program is distributed under the terms of the
3# GNU General Public License, version 2.
4#
5# $Id$
6
7package MT::ObjectDriver::Driver::DBI;
8
9use strict;
10use base qw( Data::ObjectDriver::Driver::DBI );
11
12sub init {
13    my $driver = shift;
14    my (%param) = @_;
15    $param{prefix} ||= 'mt_';
16    $driver->SUPER::init(%param);
17    my $opts = $driver->connect_options || {};
18    $opts->{RaiseError} = 0;
19    $driver->connect_options($opts);
20    $driver;
21}
22
23sub configure {
24    my $driver = shift;
25    $driver->dbd->configure($driver, @_);
26}
27
28sub table_exists {
29    my $driver = shift;
30    my ($class) = @_;
31    return $driver->dbd->ddl_class->table_exists($class);
32}
33
34# Be mindful of SQLite when you modify the method.
35# SQLite has its own count method in its DBD.
36sub count {
37    my $driver = shift;
38    my($class, $terms, $args) = @_;
39
40    my $join = $args->{join};
41    my $select = 'COUNT(*)';
42    if ($join && $join->[3]->{unique}) {
43        my $col;
44        if ($join->[3]{unique} =~ m/\D/) {
45            $col = $args->{join}[3]{unique};
46        } else {
47            $col = $class->properties->{primary_key};
48        }
49        my $dbcol = $driver->dbd->db_column_name($class->datasource, $col);
50        $select = "COUNT(DISTINCT $dbcol)";
51    }
52
53    return $driver->_select_aggregate(
54        select   => $select,
55        class    => $class,
56        terms    => $terms,
57        args     => $args,
58        override => {
59                     order  => '',
60                     limit  => undef,
61                     offset => undef,
62                    },
63    );
64}
65
66sub exist {
67    my $driver = shift;
68    my($class, $terms, $args) = @_;
69
70    return $driver->_select_aggregate(
71        select   => '1',
72        class    => $class,
73        terms    => $terms,
74        args     => $args,
75        override => {
76                     order  => '',
77                     limit  => 1,
78                     offset => undef,
79                    },
80    );
81}
82
83sub remove_all {
84    my $driver = shift;
85    my ($class) = @_;
86    return $driver->direct_remove($class);
87}
88
89sub count_group_by {
90    my $driver = shift;
91    my ($class, $terms, $args) = @_;
92
93    $driver->_do_group_by('COUNT(*)', @_);
94}
95
96sub sum_group_by {
97    my $driver = shift;
98    my ($class, $terms, $args) = @_;
99
100    my $sum_column = delete $args->{sum};
101    return unless $sum_column;
102    $sum_column = $driver->_decorate_column_name($class, $sum_column);
103    $args->{sort} = "sum_$sum_column" unless exists $args->{sort};
104    $args->{direction} = 'descend' unless exists $args->{direction};
105    $driver->_do_group_by("SUM($sum_column) AS sum_$sum_column", @_);
106}
107
108sub avg_group_by {
109    my $driver = shift;
110    my ($class, $terms, $args) = @_;
111
112    my $avg_column = delete $args->{avg};
113    return unless $avg_column;
114    $avg_column = $driver->_decorate_column_name($class, $avg_column);
115    $args->{sort} = "avg_$avg_column" unless exists $args->{sort};
116    $args->{direction} = 'descend' unless exists $args->{direction};
117    $driver->_do_group_by("AVG($avg_column) AS avg_$avg_column", @_);
118}
119
120sub max_group_by {
121    my $driver = shift;
122    my ($class, $terms, $args) = @_;
123
124    my $max_column = delete $args->{max};
125    return unless $max_column;
126    $max_column = $driver->_decorate_column_name($class, $max_column);
127    $args->{sort} = "max_$max_column" unless exists $args->{sort};
128    $args->{direction} = 'descend' unless exists $args->{direction};
129    $driver->_do_group_by("MAX($max_column) AS max_$max_column", @_);
130}
131
132sub _do_group_by {
133    my $driver = shift;
134    my ($agg_func, $class, $terms, $args) = @_;
135    my $props = $class->properties;
136    $class->call_trigger('pre_search', $terms, $args);
137    my $order = delete $args->{sort};
138    my $direction = delete $args->{direction};
139    my $limit = exists $args->{limit} ? delete $args->{limit} : undef;
140    my $offset = exists $args->{offset} ? delete $args->{offset} : undef;
141    my $stmt = $driver->prepare_statement($class, $terms, $args);
142
143    ## Ugly. Maybe we need a clear_select method in D::OD::SQL?
144    $stmt->select([]);
145    $stmt->select_map({});
146    $stmt->select_map_reverse({});
147
148    $stmt->add_select($agg_func);
149
150    ## This is the nastiest thing I've ever seen. The caller should really
151    ## just give the full column name, instead, rather than having to
152    ## loop over all of the columns to replace something like
153    ## EXTRACT(year FROM created_on) with EXTRACT(year FROM entry_created_on).
154    my $decorate = $stmt->field_decorator($class);
155
156    my @group = map { $decorate->($_) } @{ $args->{group} };
157    for my $term (@group) {
158        $stmt->add_select($term);
159    }
160    $stmt->group([ map { { column => $_ } } @group ]);
161
162    ## Set statement's ORDER clause if any.
163    if ($order) {
164        if (! ref($order)) {
165            $stmt->order( [ { column => $decorate->($order),
166                desc => $direction eq 'descend' ? 'DESC' : 'ASC'
167            } ] );
168        } else {
169            my @order;
170            foreach my $ord (@$order) {
171                push @order, {
172                    column => $decorate->($ord->{column}),
173                    desc => $ord->{desc},
174                };
175            }
176            $stmt->order(\@order);
177        }
178    }
179
180    my $sql = $stmt->as_sql;
181
182    my $dbh = $driver->r_handle;
183    $driver->start_query($sql, $stmt->bind);
184    my $sth = $dbh->prepare_cached($sql);
185    $sth->execute(@{ $stmt->bind });
186
187    my @bindvars;
188    for (@{ $args->{group} }) {
189        push @bindvars, \my($var);
190    }
191    $sth->bind_columns(undef, \my($count), @bindvars);
192
193    if ($offset) {
194        while ($offset--) {
195            unless ($sth->fetch) {
196                $driver->end_query($sth);
197                return;
198            }
199        }
200    }
201    my $i = 0;
202    return sub {
203        unless ($sth->fetch && defined $count && (!defined $limit || ($i < $limit))) {
204            $sth->finish;
205            $driver->end_query($sth);
206            return;
207        }
208        my @returnvals = map { $$_ } @bindvars;
209        $i++;
210        return($count, @returnvals);
211    }
212}
213
214sub _select_aggregate {
215    my $driver = shift;
216    my %param = @_;
217
218    my($class, $orig_terms, $orig_args) = @param{qw( class terms args )};
219    my $overrides = $param{override};
220    my $select = $param{select};
221
222    ## Handle legacy load-by-id syntax.
223    if($orig_terms && !ref $orig_terms) {
224        $orig_terms = { id => $orig_terms };
225    }
226
227    ## Convert $terms and $args like we would for a search.
228    my $terms;
229    if (ref($orig_terms) eq 'HASH') {
230        $terms = { %$orig_terms };
231    } elsif (ref($orig_terms) eq 'ARRAY') {
232        $terms = [ @$orig_terms ];
233    }
234    my $args  = $orig_args  ? { %$orig_args  } : undef;
235    $class->call_trigger('pre_search', $terms, $args);
236
237    my $stmt = $driver->prepare_statement($class, $terms, $args);
238    ## Remove any unnecessary clauses, because they will cause errors in
239    ## some drivers (and they're not necessary)
240    while(my ($clause, $value) = each %$overrides) {
241        $stmt->$clause($value);
242    }
243    $stmt->select([]);
244    my $sql = "SELECT $select\n" . $stmt->as_sql;
245    $driver->select_one($sql, $stmt->bind);
246}
247
248sub _decorate_column_names_in {
249    my $driver = shift;
250    my ($hash, $class) = @_;
251
252    my $dbd = $driver->dbd;
253    for my $col (keys %$hash) {
254        my $new_col = $dbd->db_column_name($class->datasource, $col);
255        $hash->{$new_col} = delete $hash->{$col};
256    }
257
258    return $hash;
259}
260
261sub _decorate_column_name {
262    my $driver = shift;
263    my ($class, $col) = @_;
264    return $driver->dbd->db_column_name($class->datasource, $col);
265}
266
267sub prepare_statement {
268    my $driver = shift;
269    my($class, $terms, $orig_args) = @_;
270    my $args = defined $orig_args ? { %$orig_args } : {};
271
272    my %stmt_args;
273
274    ## Statements don't know anything about table/column name decoration,
275    ## so for any set of column names we send the statement, we must pre-
276    ## decorate the column names.
277
278    for my $arg (qw( transform range range_incl not null not_null like binary count_distinct )) {
279        if(exists $args->{$arg}) {
280            my %stmt_data = %{ delete $args->{$arg} };
281            $driver->_decorate_column_names_in(\%stmt_data, $class);
282            $stmt_args{$arg} = \%stmt_data;
283        }
284    }
285
286    ## Tell the statement what's a date column.
287    if(my $date_columns = $class->columns_of_type('datetime')) {
288        my %date_columns_hash;
289        @date_columns_hash{@$date_columns} = (1) x scalar @$date_columns;
290        $driver->_decorate_column_names_in(\%date_columns_hash, $class);
291        $stmt_args{date_columns} = \%date_columns_hash;
292    }
293
294    ## Tell the statement what's a lob column.
295    if(my $lob_columns = $class->columns_of_type('text', 'blob')) {
296        my %lob_columns_hash;
297        @lob_columns_hash{@$lob_columns} = (1) x scalar @$lob_columns;
298        $driver->_decorate_column_names_in(\%lob_columns_hash, $class);
299        $stmt_args{lob_columns} = \%lob_columns_hash;
300    }
301
302    my $join = delete $args->{join};
303
304    ## Convert fetchonly args from legacy hashes to Data::ObjectDriver's
305    ## expected arrays.
306    ## TODO: handle this in MT::OD::SQL instead of converting a hash to an
307    ## array to a hash again?
308    if(exists $args->{fetchonly}) {
309        if ('HASH' eq ref $args->{fetchonly}) {
310            $args->{fetchonly} = [ keys %{ $args->{fetchonly} } ];
311        }
312    }
313
314    ## Make sure to include our ORDER BY field in the SELECT fields if
315    ## we're doing a SELECT DISTINCT (for postgres).
316    if($join && $join->[3]->{unique}) {
317        my $sort = $args->{sort};
318        if (my $fonly = $args->{fetchonly}) {
319            if (defined $sort) {
320                unless (grep { $_ eq $sort } @$fonly) {
321                    push @$fonly, $sort;
322                }
323            }
324            $args->{fetchonly} = $fonly;
325        }
326
327        my $j_sort = $join->[3]->{sort};
328        if (my $j_fonly = $join->[3]->{fetchonly}) {
329            if (defined $j_sort) {
330                unless (grep { $_ eq $j_sort } @$j_fonly) {
331                    push @$j_fonly, $j_sort;
332                }
333            }
334            $join->[3]->{fetchonly} = $j_fonly;
335        }
336    }
337
338    my $start_val = $args->{sort} ? delete $args->{start_val} : undef;
339
340    my $stmt = $driver->dbd->sql_class->new(%stmt_args);
341
342    ## START CORE D::OD::Driver::DBI prepare_statement
343    my $dbd = $driver->dbd;
344    my $tbl = $driver->table_for($class);
345
346    if ($tbl) {
347        my $cols = $class->column_names;
348        my %fetch = $args->{fetchonly} ?
349            (map { $_ => 1 } @{ $args->{fetchonly} }) : ();
350        my $skip = $stmt->select_map_reverse;
351        for my $col (@$cols) {
352            next if $skip->{$col};
353            if (keys %fetch) {
354                next unless $fetch{$col};
355            }
356            my $dbcol = $dbd->db_column_name($tbl, $col);
357            $stmt->add_select($dbcol => $col);
358        }
359
360        if ( my $alias = $orig_args->{alias} ) {
361            $stmt->from([ "$tbl $alias" ]);
362        }
363        else {
364            $stmt->from([ $tbl ]);
365        }
366
367        if (defined($terms)) {
368            $stmt->column_mutator(sub {
369                my ($col) = @_;
370                my $db_col = $dbd->db_column_name($tbl, $col);
371                if ( my $alias = $orig_args->{alias} ) {
372                    $db_col = "$alias.$db_col";
373                }
374                return $db_col;
375            });
376            if (ref $terms eq 'ARRAY') {
377                $stmt->add_complex_where($terms);
378            }
379            else {
380                for my $col (keys %$terms) {
381                    $stmt->add_where(join('.', $tbl, $col), $terms->{$col});
382                }
383            }
384            $stmt->column_mutator(undef);
385        }
386
387        ## Set statement's ORDER clause if any.
388        if ($args->{sort} || $args->{direction}) {
389            my $order = $args->{sort} || 'id';
390            if (! ref($order)) {
391                my $dir = $args->{direction} &&
392                          $args->{direction} eq 'descend' ? 'DESC' : 'ASC';
393                $stmt->order({
394                    column => $dbd->db_column_name($tbl, $order),
395                    desc   => $dir,
396                });
397            } else {
398                my @order;
399                foreach my $ord (@$order) {
400                    push @order, {
401                        column => $dbd->db_column_name($tbl, $ord->{column}),
402                        desc => $ord->{desc},
403                    };
404                }
405                $stmt->order(\@order);
406            }
407        }
408
409        if ( my $ft_arg = delete $args->{'freetext'} ) {
410            my @columns = map { $dbd->db_column_name($tbl, $_) } @{ $ft_arg->{'columns'} };
411            $stmt->add_freetext_where( \@columns, $ft_arg->{'search_string'} );
412        }
413    }
414    $stmt->limit($args->{limit}) if $args->{limit};
415    $stmt->offset($args->{offset}) if $args->{offset};
416
417    if (my $terms = $args->{having}) {
418        for my $col (keys %$terms) {
419            $stmt->add_having($col => $terms->{$col});
420        }
421    }
422    ## END
423
424    ## Keep the statement reference we're going to return with, in case
425    ## we have to subselect from it.
426    my $major_stmt = $stmt;
427
428    ## Implement `join` arg like MT::ObjectDriver, for compatibility.
429    if($join) {
430        my ($j_class, $j_col, $j_terms, $j_args) = @$join;
431        my $j_unique;
432        if($j_unique = delete $j_args->{unique}) {
433            $stmt->distinct(1);
434        }
435
436        ## Handle legacy load-by-ID in join.
437        if(defined $j_terms && !ref $j_terms) {
438            ## TODO: don't assume primary key
439            my $key = $j_class->properties->{primary_key};
440            $j_terms = { $key => $j_terms };
441        }
442
443        my $join_stmt = $driver->prepare_statement($j_class, $j_terms, $j_args);  # recursive
444
445        $j_args->{unique} = $j_unique if $j_unique;
446
447        for my $field (qw( from where bind )) {
448            push @{ $stmt->$field() }, @{ $join_stmt->$field() };
449        }
450        $stmt->from_stmt($join_stmt->from_stmt);
451        $stmt->limit($j_args->{limit}) if exists $j_args->{limit};
452        $stmt->offset($j_args->{offset}) if exists $j_args->{offset};
453
454        if($join_stmt->order) {
455            ## Preserve the sort order.
456            my @new_order;
457            for my $sql_stmt ($stmt, $join_stmt) {
458                if(my $order = $sql_stmt->order) {
459                    if('ARRAY' eq ref $order) {
460                        push @new_order, @$order;
461                    } else {
462                        push @new_order, $order;
463                    }
464                }
465            }
466            $stmt->order(\@new_order);
467
468            if ($stmt->distinct) {
469                $major_stmt = $driver->dbd->sql_class->distinct_stmt($stmt);
470            }
471        }
472
473        ## Join across the given column(s).
474        $j_col = [$j_col] unless ref $j_col;
475        my $tuple = $class->primary_key_tuple;
476        COLUMN: foreach my $i (0..$#$j_col) {
477            next unless defined $j_col->[$i];
478            my $t = $tuple->[$i];
479            my $c = $j_col->[$i];
480
481            my $where_col = $driver->_decorate_column_name($class, $t);
482            my $dec_j_col = $driver->_decorate_column_name($j_class, $c);
483            my $where_val = "= $dec_j_col";
484            $stmt->add_where($where_col, \$where_val);
485        }
486    }
487
488    if ($start_val) {
489        ## TODO: support complex primary keys
490        my $col = $args->{sort} || $class->primary_key;
491        if (ref $col eq 'ARRAY') {
492            if (ref $col->[0] eq 'HASH') {
493                # complex 'sort' array/hash structure
494                foreach (@$col) {
495                    $_->{column} = $driver->_decorate_column_name($class, $_->{column});
496                }
497            } else {
498                # primary key as array of column names
499                foreach (@$col) {
500                    $_ = $driver->_decorate_column_name($class, $_);
501                }
502            }
503        } else {
504            $col = $driver->_decorate_column_name($class, $col);
505        }
506        my $op = $args->{direction} eq 'descend' ? '<' : '>';
507        $stmt->add_where($col, { value => $start_val, op => $op });
508    }
509
510    ## Return with this reference, because we might have wrapped $stmt in
511    ## a subselect.
512    return $major_stmt;
513}
514
515sub sql {
516    my $driver = shift;
517    my ($sql) = @_;
518    my $dbh = $driver->rw_handle;
519    if (!ref $sql) {
520        $sql = [ $sql ];
521    }
522    foreach (@$sql) {
523        $dbh->do($_) or return $driver->last_error;
524    }
525    1;
526}   
527
5281;
529__END__
530
531=head1 NAME
532
533MT::ObjectDriver::Driver::DBI
534
535=head1 METHODS
536
537TODO
538
539=head1 AUTHOR & COPYRIGHT
540
541Please see L<MT/AUTHOR & COPYRIGHT>.
542
543=cut
Note: See TracBrowser for help on using the browser.