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

Revision 2475, 16.5 kB (checked in by fumiakiy, 18 months ago)

Group_by methods now returns an iterator that can be finished early. BugId:79888

  • 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        if (@_ && ($_[0] eq 'finish')) {
204            if ($sth) {
205                $sth->finish;
206                $driver->end_query($sth);
207            }
208            undef $sth;
209            return;
210        }
211
212        unless ($sth->fetch && defined $count && (!defined $limit || ($i < $limit))) {
213            $sth->finish;
214            $driver->end_query($sth);
215            return;
216        }
217        my @returnvals = map { $$_ } @bindvars;
218        $i++;
219        return($count, @returnvals);
220    }
221}
222
223sub _select_aggregate {
224    my $driver = shift;
225    my %param = @_;
226
227    my($class, $orig_terms, $orig_args) = @param{qw( class terms args )};
228    my $overrides = $param{override};
229    my $select = $param{select};
230
231    ## Handle legacy load-by-id syntax.
232    if($orig_terms && !ref $orig_terms) {
233        $orig_terms = { id => $orig_terms };
234    }
235
236    ## Convert $terms and $args like we would for a search.
237    my $terms;
238    if (ref($orig_terms) eq 'HASH') {
239        $terms = { %$orig_terms };
240    } elsif (ref($orig_terms) eq 'ARRAY') {
241        $terms = [ @$orig_terms ];
242    }
243    my $args  = $orig_args  ? { %$orig_args  } : undef;
244    $class->call_trigger('pre_search', $terms, $args);
245
246    my $stmt = $driver->prepare_statement($class, $terms, $args);
247    ## Remove any unnecessary clauses, because they will cause errors in
248    ## some drivers (and they're not necessary)
249    while(my ($clause, $value) = each %$overrides) {
250        $stmt->$clause($value);
251    }
252    $stmt->select([]);
253    my $sql = "SELECT $select\n" . $stmt->as_sql;
254    $driver->select_one($sql, $stmt->bind);
255}
256
257sub _decorate_column_names_in {
258    my $driver = shift;
259    my ($hash, $class) = @_;
260
261    my $dbd = $driver->dbd;
262    for my $col (keys %$hash) {
263        my $new_col = $dbd->db_column_name($class->datasource, $col);
264        $hash->{$new_col} = delete $hash->{$col};
265    }
266
267    return $hash;
268}
269
270sub _decorate_column_name {
271    my $driver = shift;
272    my ($class, $col) = @_;
273    return $driver->dbd->db_column_name($class->datasource, $col);
274}
275
276sub prepare_statement {
277    my $driver = shift;
278    my($class, $terms, $orig_args) = @_;
279    my $args = defined $orig_args ? { %$orig_args } : {};
280
281    my %stmt_args;
282
283    ## Statements don't know anything about table/column name decoration,
284    ## so for any set of column names we send the statement, we must pre-
285    ## decorate the column names.
286
287    for my $arg (qw( transform range range_incl not null not_null like binary count_distinct )) {
288        if(exists $args->{$arg}) {
289            my %stmt_data = %{ delete $args->{$arg} };
290            $driver->_decorate_column_names_in(\%stmt_data, $class);
291            $stmt_args{$arg} = \%stmt_data;
292        }
293    }
294
295    ## Tell the statement what's a date column.
296    if(my $date_columns = $class->columns_of_type('datetime')) {
297        my %date_columns_hash;
298        @date_columns_hash{@$date_columns} = (1) x scalar @$date_columns;
299        $driver->_decorate_column_names_in(\%date_columns_hash, $class);
300        $stmt_args{date_columns} = \%date_columns_hash;
301    }
302
303    ## Tell the statement what's a lob column.
304    if(my $lob_columns = $class->columns_of_type('text', 'blob')) {
305        my %lob_columns_hash;
306        @lob_columns_hash{@$lob_columns} = (1) x scalar @$lob_columns;
307        $driver->_decorate_column_names_in(\%lob_columns_hash, $class);
308        $stmt_args{lob_columns} = \%lob_columns_hash;
309    }
310
311    my $join = delete $args->{join};
312
313    ## Convert fetchonly args from legacy hashes to Data::ObjectDriver's
314    ## expected arrays.
315    ## TODO: handle this in MT::OD::SQL instead of converting a hash to an
316    ## array to a hash again?
317    if(exists $args->{fetchonly}) {
318        if ('HASH' eq ref $args->{fetchonly}) {
319            $args->{fetchonly} = [ keys %{ $args->{fetchonly} } ];
320        }
321    }
322
323    ## Make sure to include our ORDER BY field in the SELECT fields if
324    ## we're doing a SELECT DISTINCT (for postgres).
325    if($join && $join->[3]->{unique}) {
326        my $sort = $args->{sort};
327        if (my $fonly = $args->{fetchonly}) {
328            if (defined $sort) {
329                unless (grep { $_ eq $sort } @$fonly) {
330                    push @$fonly, $sort;
331                }
332            }
333            $args->{fetchonly} = $fonly;
334        }
335
336        my $j_sort = $join->[3]->{sort};
337        if (my $j_fonly = $join->[3]->{fetchonly}) {
338            if (defined $j_sort) {
339                unless (grep { $_ eq $j_sort } @$j_fonly) {
340                    push @$j_fonly, $j_sort;
341                }
342            }
343            $join->[3]->{fetchonly} = $j_fonly;
344        }
345    }
346
347    my $start_val = $args->{sort} ? delete $args->{start_val} : undef;
348
349    my $stmt = $driver->dbd->sql_class->new(%stmt_args);
350
351    ## START CORE D::OD::Driver::DBI prepare_statement
352    my $dbd = $driver->dbd;
353    my $tbl = $driver->table_for($class);
354
355    if ($tbl) {
356        my $cols = $class->column_names;
357        my %fetch = $args->{fetchonly} ?
358            (map { $_ => 1 } @{ $args->{fetchonly} }) : ();
359        my $skip = $stmt->select_map_reverse;
360        for my $col (@$cols) {
361            next if $skip->{$col};
362            if (keys %fetch) {
363                next unless $fetch{$col};
364            }
365            my $dbcol = $dbd->db_column_name($tbl, $col);
366            $stmt->add_select($dbcol => $col);
367        }
368
369        if ( my $alias = $orig_args->{alias} ) {
370            $stmt->from([ "$tbl $alias" ]);
371        }
372        else {
373            $stmt->from([ $tbl ]);
374        }
375
376        if (defined($terms)) {
377            $stmt->column_mutator(sub {
378                my ($col) = @_;
379                my $db_col = $dbd->db_column_name($tbl, $col);
380                if ( my $alias = $orig_args->{alias} ) {
381                    $db_col = "$alias.$db_col";
382                }
383                return $db_col;
384            });
385            if (ref $terms eq 'ARRAY') {
386                $stmt->add_complex_where($terms);
387            }
388            else {
389                for my $col (keys %$terms) {
390                    $stmt->add_where(join('.', $tbl, $col), $terms->{$col});
391                }
392            }
393            $stmt->column_mutator(undef);
394        }
395
396        ## Set statement's ORDER clause if any.
397        if ($args->{sort} || $args->{direction}) {
398            my $order = $args->{sort} || 'id';
399            if (! ref($order)) {
400                my $dir = $args->{direction} &&
401                          $args->{direction} eq 'descend' ? 'DESC' : 'ASC';
402                $stmt->order({
403                    column => $dbd->db_column_name($tbl, $order),
404                    desc   => $dir,
405                });
406            } else {
407                my @order;
408                foreach my $ord (@$order) {
409                    push @order, {
410                        column => $dbd->db_column_name($tbl, $ord->{column}),
411                        desc => $ord->{desc},
412                    };
413                }
414                $stmt->order(\@order);
415            }
416        }
417
418        if ( my $ft_arg = delete $args->{'freetext'} ) {
419            my @columns = map { $dbd->db_column_name($tbl, $_) } @{ $ft_arg->{'columns'} };
420            $stmt->add_freetext_where( \@columns, $ft_arg->{'search_string'} );
421        }
422    }
423    $stmt->limit($args->{limit}) if $args->{limit};
424    $stmt->offset($args->{offset}) if $args->{offset};
425
426    if (my $terms = $args->{having}) {
427        for my $col (keys %$terms) {
428            $stmt->add_having($col => $terms->{$col});
429        }
430    }
431    ## END
432
433    ## Keep the statement reference we're going to return with, in case
434    ## we have to subselect from it.
435    my $major_stmt = $stmt;
436
437    ## Implement `join` arg like MT::ObjectDriver, for compatibility.
438    if($join) {
439        my ($j_class, $j_col, $j_terms, $j_args) = @$join;
440        my $j_unique;
441        if($j_unique = delete $j_args->{unique}) {
442            $stmt->distinct(1);
443        }
444
445        ## Handle legacy load-by-ID in join.
446        if(defined $j_terms && !ref $j_terms) {
447            ## TODO: don't assume primary key
448            my $key = $j_class->properties->{primary_key};
449            $j_terms = { $key => $j_terms };
450        }
451
452        my $join_stmt = $driver->prepare_statement($j_class, $j_terms, $j_args);  # recursive
453
454        $j_args->{unique} = $j_unique if $j_unique;
455
456        for my $field (qw( from where bind )) {
457            push @{ $stmt->$field() }, @{ $join_stmt->$field() };
458        }
459        $stmt->from_stmt($join_stmt->from_stmt);
460        $stmt->limit($j_args->{limit}) if exists $j_args->{limit};
461        $stmt->offset($j_args->{offset}) if exists $j_args->{offset};
462
463        if($join_stmt->order) {
464            ## Preserve the sort order.
465            my @new_order;
466            for my $sql_stmt ($stmt, $join_stmt) {
467                if(my $order = $sql_stmt->order) {
468                    if('ARRAY' eq ref $order) {
469                        push @new_order, @$order;
470                    } else {
471                        push @new_order, $order;
472                    }
473                }
474            }
475            $stmt->order(\@new_order);
476
477            if ($stmt->distinct) {
478                $major_stmt = $driver->dbd->sql_class->distinct_stmt($stmt);
479            }
480        }
481
482        ## Join across the given column(s).
483        $j_col = [$j_col] unless ref $j_col;
484        my $tuple = $class->primary_key_tuple;
485        COLUMN: foreach my $i (0..$#$j_col) {
486            next unless defined $j_col->[$i];
487            my $t = $tuple->[$i];
488            my $c = $j_col->[$i];
489
490            my $where_col = $driver->_decorate_column_name($class, $t);
491            my $dec_j_col = $driver->_decorate_column_name($j_class, $c);
492            my $where_val = "= $dec_j_col";
493            $stmt->add_where($where_col, \$where_val);
494        }
495    }
496
497    if ($start_val) {
498        ## TODO: support complex primary keys
499        my $col = $args->{sort} || $class->primary_key;
500        if (ref $col eq 'ARRAY') {
501            if (ref $col->[0] eq 'HASH') {
502                # complex 'sort' array/hash structure
503                foreach (@$col) {
504                    $_->{column} = $driver->_decorate_column_name($class, $_->{column});
505                }
506            } else {
507                # primary key as array of column names
508                foreach (@$col) {
509                    $_ = $driver->_decorate_column_name($class, $_);
510                }
511            }
512        } else {
513            $col = $driver->_decorate_column_name($class, $col);
514        }
515        my $op = $args->{direction} eq 'descend' ? '<' : '>';
516        $stmt->add_where($col, { value => $start_val, op => $op });
517    }
518
519    ## Return with this reference, because we might have wrapped $stmt in
520    ## a subselect.
521    return $major_stmt;
522}
523
524sub sql {
525    my $driver = shift;
526    my ($sql) = @_;
527    my $dbh = $driver->rw_handle;
528    if (!ref $sql) {
529        $sql = [ $sql ];
530    }
531    foreach (@$sql) {
532        $dbh->do($_) or return $driver->last_error;
533    }
534    1;
535}   
536
5371;
538__END__
539
540=head1 NAME
541
542MT::ObjectDriver::Driver::DBI
543
544=head1 METHODS
545
546TODO
547
548=head1 AUTHOR & COPYRIGHT
549
550Please see L<MT/AUTHOR & COPYRIGHT>.
551
552=cut
Note: See TracBrowser for help on using the browser.