root/branches/release-34/lib/MT/ObjectDriver/Driver/DBI.pm @ 1881

Revision 1881, 16.1 kB (checked in by fumiakiy, 20 months ago)

Added support to complex terms and order by clause to _do_group_by method.

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