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

Revision 1873, 15.8 kB (checked in by bchoate, 20 months ago)

Applied patches from Ogawa-san to add an optimized 'exist' method for testing for existing rows. BugId:69661

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