root/branches/release-40/lib/MT/ObjectDriver/Driver/DBI.pm @ 2625

Revision 2625, 16.9 kB (checked in by fumiakiy, 17 months ago)

Removed hard-coded SQL statement and pass select list to SQL class. This is mainly for enterprise database drivers to generate SQL statements correctly. BugId:79817

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