root/branches/release-37/lib/MT/ObjectDriver/Driver/DBI.pm @ 2202

Revision 2202, 16.0 kB (checked in by fumiakiy, 19 months ago)

Removed the reference to a private method in MT::Object from MT::OD::DBI. Use the trigger instead, just like other methods in it are doing. BugId:79569

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