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

Revision 2459, 16.4 kB (checked in by bchoate, 18 months ago)

Adding support for a max_group_by method. BugId:79914

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