QBit/Application/Model/DB/Query.pm untested

filter: Statementstmt 0.0% 0 / 422 Branchbran 0.0% 0 / 236 Conditioncond 0.0% 0 / 143 MC/DCmcdc 0.0% 0 / 84 Subroutinesub 0.0% 0 / 36 Podpod 0.0% 0 / 32 totaltotal 0.0% 0 / 953 CC 119 SCAR 64.7
CC
119
Cov
0%
_field_to_sql
1722.0
get_sql_with_data_for_select
756.0
get_sql_with_data_for_update
342.0
CRAP 644.6
1 package Exception::DB::NoFieldsAvailable;
2 $Exception::DB::NoFieldsAvailable::VERSION = '0.030';
3 use base qw(Exception::DB);
4  
5 =head1 Name
6  
7 QBit::Application::Model::DB::Query
8  
9 =head1 Description
10  
11 Base class for DB queries.
12  
13 =cut
14  
15 package QBit::Application::Model::DB::Query;
16 $QBit::Application::Model::DB::Query::VERSION = '0.030';
17 use qbit;
18  
19 use base qw(QBit::Application::Model::DB::Class);
20  
21 use QBit::Application::Model::DB::VirtualTable;
22  
23 =head1 Abstract methods
24  
25 =over
26  
27 =item
28  
29 B<_found_rows>
30  
31 =back
32  
33 =cut
34  
35 __PACKAGE__->abstract_methods(qw(_found_rows));
36  
37 =head1 Package methods
38  
39 =head2 init
40  
41 B<No arguments.>
42  
43 Method called from L</new> before return object.
44  
45 =cut
46  
47 sub init {
48 my ($self) = @_;
49  
50 $self->SUPER::init();
51  
52 delete($self->{$_}) foreach grep {/__.+__/} keys(%$self);
53 }
54  
55 =head2 select
56  
57 B<Arguments:>
58  
59 =over
60  
61 =item *
62  
63 B<%opts> - options with keys
64  
65 =over
66  
67 =item *
68  
69 B<table> - object
70  
71 =item *
72  
73 B<fields> (optional, default: all fields)
74  
75 =item *
76  
77 B<filter> (optional)
78  
79 =back
80  
81 =back
82  
83 B<Return values:>
84  
85 =over
86  
87 =item *
88  
89 B<$query> - object
90  
91 =back
92  
93 B<Example:>
94  
95 my $query = $app->db->query->select(
96 table => $app->db->users,
97 fields => [qw(id login)],
98 filter => {id => 3},
99 );
100  
101 =cut
102  
103 sub select {
104 my ($self, %opts) = @_;
105  
106 $self->{'__TABLES__'} = [];
107 $self->{'__TYPE__'} = 'select';
108  
109 return $self->_add_table(%opts);
110 }
111  
112 =head2 join
113  
114 B<Arguments:>
115  
116 =over
117  
118 =item *
119  
120 B<%opts> - options with keys
121  
122 =over
123  
124 =item *
125  
126 B<table> - object
127  
128 =item *
129  
130 B<alias> (optional)
131  
132 =item *
133  
134 B<fields> (optional, default: all fields)
135  
136 =item *
137  
138 B<filter> (optional)
139  
140 =item *
141  
142 B<join_type> (optional, default: 'INNER JOIN')
143  
144 =item *
145  
146 B<join_on> (optional, default: use foreign keys)
147  
148 =back
149  
150 =back
151  
152 B<Return values:>
153  
154 =over
155  
156 =item *
157  
158 B<$query> - object
159  
160 =back
161  
162 B<Example:>
163  
164 my $join_query = $query->join(
165 table => $app->db->fio,
166 fields => [qw(name surname)],
167 filter => ['name' => 'LIKE' => \'Max'],
168 join_type => 'INNER JOIN',
169 join_on => ['user_id' => '=' => {'id' => $app->db->users}],
170 );
171  
172 =cut
173  
174 sub join {
175 my ($self, %opts) = @_;
176  
177 $opts{'join_type'} = $opts{'join_type'} ? uc($opts{'join_type'}) : 'INNER JOIN';
178  
179 my $dont_check_join_on;
180  
181 # Проверяем, что в query есть таблица из FK
182 unless (exists($opts{'join_on'})) {
183 foreach (@{$opts{'table'}->{'foreign_keys'} || []}) {
184 my $table = $_->[1];
185 my $foreign_table;
186 try {
187 $foreign_table = $self->_get_table($self->db->$table);
188 }
189 catch {
190 undef($foreign_table);
191 };
192 if (defined($foreign_table)) {
193 my $fkey = $_;
194 $dont_check_join_on = $opts{'join_on'} = [];
195 push(@{$opts{'join_on'}}, [$fkey->[0][$_] => '=' => {$fkey->[2][$_] => $foreign_table->{'table'}}])
196 for 0 .. @{$fkey->[0]} - 1;
197 last;
198 }
199 }
200 $opts{'join_on'} = [AND => $opts{'join_on'}] if exists($opts{'join_on'});
201 }
202  
203 # Проверяем, что в query есть таблица, в FK которой есть текущая таблица
204 unless (exists($opts{'join_on'})) {
205 foreach my $qtable (map {$_->{'table'}} @{$self->{'__TABLES__'} || []}) {
206 foreach (@{$qtable->{'foreign_keys'} || []}) {
207 if ($opts{'table'}->name eq $_->[1]) {
208 my $fkey = $_;
209 $dont_check_join_on = $opts{'join_on'} = [];
210 push(@{$opts{'join_on'}}, [$fkey->[2][$_] => '=' => {$fkey->[0][$_] => $qtable}])
211 for 0 .. @{$fkey->[0]} - 1;
212 last;
213 }
214 }
215 }
216 $opts{'join_on'} = [AND => $opts{'join_on'}] if exists($opts{'join_on'});
217 }
218  
219 unless ($dont_check_join_on) {
220 throw gettext('join_on is required')
221 unless exists($opts{'join_on'});
222  
223 }
224  
225 return $self->_add_table(%opts);
226 }
227  
228 =head2 left_join
229  
230 join_type => 'LEFT JOIN'
231  
232 =cut
233  
234 sub left_join {
235 my ($self, %opts) = @_;
236  
237 return $self->join(%opts, join_type => 'LEFT JOIN');
238 }
239  
240 =head2 right_join
241  
242 join_type => 'RIGHT JOIN'
243  
244 =cut
245  
246 sub right_join {
247 my ($self, %opts) = @_;
248  
249 return $self->join(%opts, join_type => 'RIGHT JOIN');
250 }
251  
252 =head2 group_by
253  
254 B<Arguments:>
255  
256 =over
257  
258 =item *
259  
260 B<@fields>
261  
262 =back
263  
264 B<Return values:>
265  
266 =over
267  
268 =item *
269  
270 B<$query> - object
271  
272 =back
273  
274 B<Example:>
275  
276 my $group_query = $query->group_by(qw(name surname));
277  
278 =cut
279  
280 sub group_by {
281 my ($self, @group_by) = @_;
282  
283 my %group_by = map {$_ => TRUE} @group_by;
284 my %fields = map {%{$_->{'fields'}}} @{$self->{'__TABLES__'}};
285 my @not_grouping_fields = grep {!$fields{$_} && !$group_by{$_}} keys(%fields);
286  
287 throw Exception::BadArguments gettext("You've forgotten grouping function for query field(s) '%s'.",
288 CORE::join(', ', @not_grouping_fields))
289 if @not_grouping_fields;
290  
291 $self->{'__GROUP_BY__'} = \@group_by;
292  
293 return $self;
294 }
295  
296 =head2 having
297  
298 B<Arguments:>
299  
300 =over
301  
302 =item *
303  
304 B<$expression>
305  
306 =back
307  
308 B<Return values:>
309  
310 =over
311  
312 =item *
313  
314 B<$query> - object
315  
316 =back
317  
318 B<Example:>
319  
320 my $query_with_having = $query->having([cnt => '>=' => \100]);
321  
322 =cut
323  
324 sub having {
325 my ($self, $expression) = @_;
326  
327 $self->{'__HAVING__'} = $expression;
328  
329 return $self;
330 }
331  
332 =head2 order_by
333  
334 B<Arguments:>
335  
336 =over
337  
338 =item *
339  
340 B<@fields> - fields or reference to array
341  
342 =back
343  
344 B<Return values:>
345  
346 =over
347  
348 =item *
349  
350 B<$query> - object
351  
352 =back
353  
354 B<Example:>
355  
356 my $order_query = $query->order_by('id', ['login', 1]);
357  
358 =cut
359  
360 sub order_by {
361 my ($self, @order_by) = @_;
362  
363 $self->{'__ORDER_BY__'} = [map {ref($_) eq 'ARRAY' ? $_ : [$_]} @order_by];
364  
365 return $self;
366 }
367  
368 =head2 limit
369  
370 B<Arguments:>
371  
372 =over
373  
374 =item *
375  
376 B<@limit>
377  
378 =back
379  
380 B<Return values:>
381  
382 =over
383  
384 =item *
385  
386 B<$query> - object
387  
388 =back
389  
390 B<Example:>
391  
392 my $limit_query = $query->limit(100, 200);
393  
394 =cut
395  
396 sub limit {
397 my ($self, @params) = @_;
398  
399 $self->{'__LIMIT__'} = [splice(@params, 0, 2)];
400  
401 return $self;
402 }
403  
404 =head2 distinct
405  
406 B<No arguments.>
407  
408 B<Return values:>
409  
410 =over
411  
412 =item *
413  
414 B<$query> - object
415  
416 =back
417  
418 B<Example:>
419  
420 my $distinct_query = $query->distinct();
421  
422 =cut
423  
424 sub distinct {
425 my ($self) = @_;
426  
427 $self->{'__DISTINCT__'} = TRUE;
428  
429 return $self;
430 }
431  
432 =head2 union
433  
434 B<Arguments:>
435  
436 =over
437  
438 =item *
439  
440 B<$query> - object
441  
442 =item *
443  
444 B<%opts> - options with keys
445  
446 =over
447  
448 =item *
449  
450 B<all> - boolean (optional, default: FALSE)
451  
452 =back
453  
454 =back
455  
456 B<Return values:>
457  
458 =over
459  
460 =item *
461  
462 B<$query> - object
463  
464 =back
465  
466 B<Example:>
467  
468 my $union_query = $query->union(
469 $app->db->query->select(
470 table => $app->db->people,
471 fields => [qw(id login name surname)]
472 ),
473 all => FALSE,
474 );
475  
476 =cut
477  
478 sub union {
479 my ($self, $query, %opts) = @_;
480  
481 throw Exception::BadArguments gettext('"query" must be QBit::Application::Model::DB::Query descendant')
482 unless defined($query) && blessed($query) && $query->isa('QBit::Application::Model::DB::Query');
483  
484 $self->{'__UNION__'} ||= [];
485 push(@{$self->{'__UNION__'}}, {query => $query, %opts});
486  
487 return $self;
488 }
489  
490 =head2 union_all
491  
492 all => TRUE
493  
494 =cut
495  
496 sub union_all {
497 my ($self, @params) = @_;
498  
499 return $self->union(@params, all => TRUE);
500 }
501  
502 =head2 calc_rows
503  
504 B<Arguments:>
505  
506 =over
507  
508 =item *
509  
510 B<$flag> - boolean
511  
512 =back
513  
514 B<Return values:>
515  
516 =over
517  
518 =item *
519  
520 B<$query> - object
521  
522 =back
523  
524 B<Example:>
525  
526 my $calc_rows_query = $query->calc_rows(TRUE);
527  
528 =cut
529  
530 sub calc_rows {
531 my ($self, $flag) = @_;
532  
533 $self->{'__CALC_ROWS__'} = !!$flag;
534  
535 return $self;
536 }
537  
538 =head2 all_langs
539  
540 B<Arguments:>
541  
542 =over
543  
544 =item *
545  
546 B<$flag> - boolean
547  
548 =back
549  
550 B<Return values:>
551  
552 =over
553  
554 =item *
555  
556 B<$query> - object
557  
558 =back
559  
560 B<Example:>
561  
562 my $all_langs_query = $query->all_langs(TRUE);
563  
564 =cut
565  
566 sub all_langs {
567 my ($self, $flag) = @_;
568  
569 $self->{'__ALL_LANGS__'} = !!$flag;
570  
571 return $self;
572 }
573  
574 =head2 for_update
575  
576 B<No arguments.>
577  
578 B<Return values:>
579  
580 =over
581  
582 =item *
583  
584 B<$query> - object
585  
586 =back
587  
588 B<Example:>
589  
590 my $for_update_query = $query->for_update();
591  
592 =cut
593  
594 sub for_update {
595 my ($self) = @_;
596  
597 $self->{'__FOR_UPDATE__'} = 1;
598  
599 return $self;
600 }
601  
602 =head2 filter
603  
604 =cut
605  
606 sub filter {shift->db->filter(@_)}
607  
608 =head2 get_sql_with_data
609  
610 B<Arguments:>
611  
612 =over
613  
614 =item *
615  
616 B<%opts> - options with keys
617  
618 =over
619  
620 =item *
621  
622 B<offset> - number (optional, default: 0)
623  
624 =back
625  
626 =back
627  
628 B<Return values:>
629  
630 =over
631  
632 =item *
633  
634 B<$sql> - string
635  
636 =back
637  
638 B<Example:>
639  
640 my $sql = $query->get_sql_with_data();
641  
642 =cut
643  
644 sub get_sql_with_data_for_select {
645 my ($self, %opts) = @_;
646  
647 my @sql_data = ();
648 my $sql = '';
649  
650 $opts{'offset'} ||= 0;
651 my ($orig_offset, $offset);
652 $orig_offset = $offset = ' ' x $opts{'offset'};
653  
654 if (@{$self->{'__UNION__'} || []}) {
655 $opts{'offset'} += 4;
656 $offset .= ' ';
657 $sql .= "(\n$offset";
658 }
659  
660 $sql .= $self->_comment() . "\n$offset" if $self->{'comment'};
661  
662 $sql .= 'SELECT';
663  
664 $sql .= ' DISTINCT' if $self->{'__DISTINCT__'};
665  
666 $sql .= $self->_after_select(\@sql_data);
667  
668 my %all_fields = ();
669 foreach my $table (@{$self->{'__TABLES__'}}) {
670 throw Exception::BadArguments gettext('Fields must be hash ref') if ref($table->{'fields'}) ne 'HASH';
671 foreach my $field (keys(%{$table->{'fields'}})) {
672 throw Exception::BadArguments gettext('Duplicate field name "%s", table "%s"', $field,
673 $table->{'table'}->name)
674 if exists($all_fields{$field});
675 $all_fields{$field} = [$self->_field_to_sql($field, $table->{'fields'}{$field}, $table, %opts)];
676 }
677 }
678  
679 unless (%all_fields) {
680 throw Exception::DB::NoFieldsAvailable gettext('No fields available');
681 }
682  
683 $sql .= "\n$offset " . CORE::join(",\n$offset ", map {@{$all_fields{$_}}} sort keys(%all_fields));
684 my ($select_query_table, @join_query_tables) = @{$self->{'__TABLES__'}};
685 $sql .= "\n${offset}FROM";
686  
687 if ($select_query_table->{'table'}->isa('QBit::Application::Model::DB::VirtualTable')) {
688 my ($vt_sql, @vt_data) =
689 $select_query_table->{'table'}->get_sql_with_data(%opts, offset => $opts{'offset'} + 4);
690  
691 $sql .= " (\n${offset} $vt_sql\n${offset}) " . $self->quote_identifier($select_query_table->{'table'}->name);
692 push(@sql_data, @vt_data);
693 } else {
694 $sql .=
695 ' '
696 . $self->quote_identifier($select_query_table->{'table'}->name)
697 . (
698 exists($select_query_table->{'alias'})
699 ? ' AS ' . $self->quote_identifier($select_query_table->{'alias'})
700 : ''
701 );
702 }
703  
704 foreach my $table (@join_query_tables) {
705 $sql .= "\n${offset}" . $table->{'join_type'};
706  
707 if ($table->{'table'}->isa('QBit::Application::Model::DB::VirtualTable')) {
708 my ($vt_sql, @vt_data) = $table->{'table'}->get_sql_with_data(%opts, offset => $opts{'offset'} + 4);
709  
710 $sql .= " (\n${offset} $vt_sql\n${offset}) " . $self->quote_identifier($table->{'table'}->name);
711 push(@sql_data, @vt_data);
712 } else {
713 $sql .=
714 ' '
715 . $self->quote_identifier($table->{'table'}->name)
716 . (
717 exists($table->{'alias'})
718 ? ' AS ' . $self->quote_identifier($table->{'alias'})
719 : ''
720 );
721 }
722  
723 next unless exists($table->{'join_on'});
724 my $filter_expr = $self->filter($table->{'join_on'})->expression();
725 next unless defined($filter_expr);
726 my ($filter_sql) = $self->_field_to_sql(undef, $filter_expr, $table, %opts, offset => $opts{'offset'});
727 $sql .= " ON " . $filter_sql if $filter_sql;
728 }
729  
730 my $where_sql = '';
731 foreach my $table (@{$self->{'__TABLES__'}}) {
732 next unless defined($table->{'filter'});
733 my $filter_expr = $self->filter($table->{'filter'})->expression();
734 next unless defined($filter_expr);
735 my ($filter_sql) = $self->_field_to_sql(undef, $filter_expr, $table, %opts, offset => $opts{'offset'});
736 $where_sql .= "\n${offset}" . ($where_sql ? 'AND ' : 'WHERE ') . $filter_sql if $filter_sql;
737 }
738 $sql .= $where_sql;
739  
740 $sql .= "\n${offset}GROUP BY " . CORE::join(', ', map {$self->quote_identifier($_)} @{$self->{'__GROUP_BY__'}})
741 if exists($self->{'__GROUP_BY__'});
742  
743 $sql .= $self->_after_group_by();
744  
745 if (exists($self->{'__HAVING__'})) {
746 local $self->{'without_check_fields'} = {};
747 local $self->{'without_table_alias'} = TRUE;
748  
749 my ($having, @having_data) = $self->_field_to_sql(undef, $self->{'__HAVING__'}, $select_query_table, %opts);
750  
751 $sql .= "\n${offset}HAVING $having";
752 push(@sql_data, @having_data) if @having_data;
753 }
754  
755 $sql .=
756 "\n${offset}ORDER BY "
757 . CORE::join(', ', map {$self->quote_identifier($_->[0]) . ($_->[1] ? ' DESC' : '')} @{$self->{'__ORDER_BY__'}})
758 if exists($self->{'__ORDER_BY__'});
759  
760 $sql .= "\n${offset}LIMIT " . CORE::join(', ', map {int($_ || 0)} @{$self->{'__LIMIT__'}})
761 if exists($self->{'__LIMIT__'});
762  
763 $sql .= "\n${offset}FOR UPDATE" if $self->{'__FOR_UPDATE__'};
764  
765 $sql .= "\n$orig_offset)" if @{$self->{'__UNION__'} || []};
766 foreach my $union_query (@{$self->{'__UNION__'} || []}) {
767 $sql .= "\n${orig_offset}UNION";
768 $sql .= ' ALL' if $union_query->{'all'};
769 $sql .= "\n${orig_offset}(\n$offset";
770  
771 my ($usql, @udata) = $union_query->{'query'}->get_sql_with_data(%opts, offset => $opts{'offset'});
772 $sql .= $usql;
773 push(@sql_data, @udata);
774 $sql .= "\n${orig_offset})";
775 }
776  
777 return ($sql, @sql_data);
778 }
779  
780 sub _comment {"/* $_[0]->{'comment'} */"}
781  
782 =head2 get_all
783  
784 B<No arguments.>
785  
786 B<Return values:>
787  
788 =over
789  
790 =item *
791  
792 B<$data> - reference to array
793  
794 =back
795  
796 B<Example:>
797  
798 my $data = $query->get_all();
799  
800 =cut
801  
802 sub get_all {
803 my ($self) = @_;
804  
805 return []
806 unless exists($self->{'__TABLES__'}) && @{$self->{'__TABLES__'}};
807  
808 my $res = $self->db->_get_all($self->get_sql_with_data());
809  
810 $self->{'__FOUND_ROWS__'} = $self->{'__CALC_ROWS__'} ? $self->_found_rows() : undef;
811  
812 return $res;
813 }
814  
815 =head2 update
816  
817 B<Arguments:>
818  
819 =over
820  
821 =item *
822  
823 B<%opts> - options with keys
824  
825 =over
826  
827 =item *
828  
829 B<table> - object
830  
831 =item *
832  
833 B<alias> - alias for table (type: string)
834  
835 =item *
836  
837 B<data> - data for update (type: reference to hash)
838  
839 =item *
840  
841 B<filter> (optional)
842  
843 =back
844  
845 =back
846  
847 B<Return values:>
848  
849 =over
850  
851 =item *
852  
853 B<$query> - object
854  
855 =back
856  
857 B<Example:>
858  
859 my $query = $app->db->query->update(
860 table => $app->db->users,
861 alias => 'u',
862 data => {
863 login => 'ChuckNorris',
864 date => {NOW => []},
865 },
866 filter => {id => 3},
867 );
868  
869 =cut
870  
871 sub update {
872 my ($self, %opts) = @_;
873  
874 throw '"table" is not defined' unless defined $opts{'table'};
875  
876 throw '"table" must be QBit::Application::Model::DB::Table'
877 unless blessed($opts{'table'}) && $opts{'table'}->isa('QBit::Application::Model::DB::Table');
878  
879 throw '"data" must be defined and be a reference to the hash'
880 unless defined($opts{'data'}) && ref($opts{'data'}) eq 'HASH' && %{$opts{'data'}};
881  
882 $self->{'__TABLES__'} = [];
883 $self->{'__TYPE__'} = 'update';
884  
885 my %table_info =
886 map {exists($opts{$_}) ? ($_ => $opts{$_}) : ()} qw(table alias data filter);
887  
888 push(@{$self->{'__TABLES__'}}, \%table_info);
889  
890 return $self;
891 }
892  
893 =head2 do
894  
895 Execute query and returns results
896  
897 B<No arguments>
898  
899 B<Return values:>
900  
901 =over
902  
903 =item *
904  
905 B<$res> - count of a affected rows or -1
906  
907 =back
908  
909 B<Example:>
910  
911 my $res = $query->do();
912  
913 =cut
914  
915 sub do {
916 my ($self) = @_;
917  
918 return -1
919 unless exists($self->{'__TABLES__'}) && @{$self->{'__TABLES__'}};
920  
921 return $self->db->_do($self->get_sql_with_data());
922 }
923  
924 sub get_sql_with_data_for_update {
925 my ($self, %opts) = @_;
926  
927 my $sql = '';
928 my @sql_data = ();
929  
930 $opts{'offset'} ||= 0;
931 my $offset = ' ' x $opts{'offset'};
932 my $offset_params = $offset . (' ' x 4);
933  
934 $sql .= $self->_comment() . "\n$offset" if $self->{'comment'};
935  
936 my ($update_table, @join_query_tables) = @{$self->{'__TABLES__'}};
937 my ($table, $data, $filter) = @$update_table{qw(table data filter)};
938  
939 $sql .=
940 "UPDATE\n$offset_params"
941 . $self->quote_identifier($table->name)
942 . (
943 exists($update_table->{'alias'})
944 ? ' AS ' . $self->quote_identifier($update_table->{'alias'})
945 : ''
946 );
947  
948 foreach my $qtable (@join_query_tables) {
949 $sql .= "\n${offset}" . $qtable->{'join_type'};
950  
951 if ($qtable->{'table'}->isa('QBit::Application::Model::DB::VirtualTable')) {
952 my ($vt_sql, @vt_data) = $qtable->{'table'}->get_sql_with_data(%opts, offset => $opts{'offset'} + 4);
953  
954 $sql .= " (\n${offset} $vt_sql\n${offset}) " . $self->quote_identifier($qtable->{'table'}->name);
955 push(@sql_data, @vt_data);
956 } else {
957 $sql .=
958 ' '
959 . $self->quote_identifier($qtable->{'table'}->name)
960 . (
961 exists($qtable->{'alias'})
962 ? ' AS ' . $self->quote_identifier($qtable->{'alias'})
963 : ''
964 );
965 }
966  
967 next unless exists($qtable->{'join_on'});
968 my $filter_expr = $self->filter($qtable->{'join_on'})->expression();
969 next unless defined($filter_expr);
970 my ($filter_sql) = $self->_field_to_sql(undef, $filter_expr, $qtable, %opts, offset => $opts{'offset'});
971 $sql .= " ON " . $filter_sql if $filter_sql;
972 }
973  
974 $sql .= "\n${offset}SET\n";
975  
976 my $fields = $table->_fields_hs();
977  
978 my @locales = sort keys(%{$self->db->get_option('locales', {})});
979  
980 my $sql_params = '';
981 foreach my $name (sort keys(%$data)) {
982 if ($fields->{$name}{'i18n'} && @locales) {
983 foreach my $locale (@locales) {
984 $sql_params .= ",\n" if $sql_params;
985  
986 my $field_data = ref($data->{$name}) eq 'HASH' ? $data->{$name}{$locale} : $data->{$name};
987  
988 my ($sql_field, @field_data) = $self->_field_to_sql(
989 undef,
990 ref($field_data) ? $field_data : \$field_data,
991 $self->_get_table($table),
992 %opts,
993 offset => $opts{'offset'},
994 locale => $locale,
995 );
996  
997 $sql_params .= $offset_params . $self->quote_identifier("${name}_${locale}") . " = $sql_field";
998 push(@sql_data, @field_data);
999 }
1000 } else {
1001 $sql_params .= ",\n" if $sql_params;
1002  
1003 my ($sql_field, @field_data) = $self->_field_to_sql(
1004 undef,
1005 ref($data->{$name}) ? $data->{$name} : \$data->{$name},
1006 $self->_get_table($table),
1007 %opts, offset => $opts{'offset'},
1008 );
1009  
1010 $sql_params .= $offset_params . $self->quote_identifier($name) . " = $sql_field";
1011 push(@sql_data, @field_data);
1012 }
1013 }
1014 $sql .= $sql_params;
1015  
1016 my $where_sql = '';
1017 foreach my $table (@{$self->{'__TABLES__'}}) {
1018 next unless defined($table->{'filter'});
1019  
1020 my $filter_expr = $self->filter($table->{'filter'})->expression();
1021 next unless defined($filter_expr);
1022  
1023 my ($filter_sql, @filter_data) =
1024 $self->_field_to_sql(undef, $filter_expr, $table, %opts, offset => $opts{'offset'});
1025  
1026 if ($filter_sql) {
1027 $where_sql .= "\n${offset}" . ($where_sql ? 'AND ' : 'WHERE ') . $filter_sql;
1028 push(@sql_data, @filter_data);
1029 }
1030 }
1031 $sql .= $where_sql;
1032  
1033 return ($sql, @sql_data);
1034 }
1035  
1036 sub get_sql_with_data {
1037 my ($self, %opts) = @_;
1038  
1039 my $method = 'get_sql_with_data_for_' . $self->{'__TYPE__'};
1040  
1041 return $self->$method(%opts);
1042 }
1043  
1044 =head2 found_rows
1045  
1046 B<No arguments.>
1047  
1048 B<Return values:>
1049  
1050 =over
1051  
1052 =item *
1053  
1054 B<$bool>
1055  
1056 =back
1057  
1058 B<Example:>
1059  
1060 my $bool = $query->found_rows();
1061  
1062 =cut
1063  
1064 sub found_rows {
1065 my ($self) = @_;
1066  
1067 return $self->{'__FOUND_ROWS__'};
1068 }
1069  
1070 sub _add_table {
1071 my ($self, %opts) = @_;
1072  
1073 throw '"table" is not defined' unless defined $opts{'table'};
1074  
1075 throw '"table" must be QBit::Application::Model::DB::Table or QBit::Application::Model::DB::Query descendant'
1076 unless $opts{'table'}
1077 && $opts{'table'}
1078 && ( $opts{'table'}->isa('QBit::Application::Model::DB::Table')
1079 || $opts{'table'}->isa('QBit::Application::Model::DB::Query'));
1080  
1081 $opts{'table'} = QBit::Application::Model::DB::VirtualTable->new(
1082 db => $self->db,
1083 query => $opts{'table'},
1084 name => $opts{'alias'}
1085 ) if $opts{'table'}->isa('QBit::Application::Model::DB::Query');
1086  
1087 my %table_info =
1088 map {exists($opts{$_}) ? ($_ => $opts{$_}) : ()} qw(table alias fields join_type join_on filter);
1089 $table_info{'fields'} = [keys(%{$opts{'table'}->_fields_hs()})] unless exists($opts{'fields'});
1090  
1091 $table_info{'fields'} = {map {$_ => ''} @{$table_info{'fields'}}}
1092 if $table_info{'fields'} && ref($table_info{'fields'}) eq 'ARRAY';
1093  
1094 push(@{$self->{'__TABLES__'}}, \%table_info);
1095  
1096 return $self;
1097 }
1098  
1099 sub _get_table {
1100 my ($self, $tbl_or_alias) = @_;
1101  
1102 if (blessed($tbl_or_alias)
1103 && $tbl_or_alias->isa('QBit::Application::Model::DB::Table'))
1104 { # Передали указатель на объект-таблицу
1105 foreach (@{$self->{'__TABLES__'}}) {
1106 return $_ if $_->{'table'}->name eq $tbl_or_alias->name;
1107 }
1108 throw gettext('Cannot find table "%s" in query', $tbl_or_alias->name);
1109 } elsif (!ref($tbl_or_alias)) { # Передали alias таблицы
1110 foreach (@{$self->{'__TABLES__'}}) {
1111 return $_ if ($_->{'alias'} || '') eq $tbl_or_alias;
1112 }
1113 throw gettext('Cannot find table alias "%s" in query', $tbl_or_alias);
1114 } else { # Передали что-то непонятное
1115 throw Exception::BadArguments gettext('Bad arguments');
1116 }
1117 }
1118  
1119 sub _table_alias {
1120 my ($self, $query_table) = @_;
1121  
1122 return exists($query_table->{'alias'}) ? $query_table->{'alias'} : $query_table->{'table'}->name;
1123 }
1124  
1125 sub _get_locale_suffixes {
1126 my ($self, $locale) = @_;
1127  
1128 return "_$locale" if defined($locale);
1129  
1130 my @locales =
1131 $self->{'__ALL_LANGS__'}
1132 ? (sort keys(%{$self->db->get_option('locales', {})}))
1133 : ($self->db->get_option('locale'));
1134 @locales = (undef) unless @locales;
1135  
1136 return (map {defined($_) ? "_$_" : ''} @locales);
1137 }
1138  
1139 sub _after_select {''}
1140  
1141 sub _after_group_by {''}
1142  
1143 sub _field_to_sql {
1144 my ($self, $alias, $expr, $cur_query_table, %opts) = @_;
1145  
1146 throw Exception::BadArguments gettext('Table field aliase must be SCALAR') if ref($alias);
1147  
1148 $opts{'offset'} ||= 0;
1149  
1150 if (ref($expr) eq 'SCALAR') {
1151 # {name => \'string or number or undef'}
1152 return ($self->quote($$expr) . (defined($alias) ? ' AS ' . $self->quote_identifier($alias) : ''));
1153  
1154 } elsif (!ref($expr) && $expr eq '') {
1155 # {field_name => ''}
1156 my $field =
1157 $cur_query_table->{'table'}->_fields_hs()->{$alias}
1158 || $self->{'without_check_fields'}
1159 || throw Exception::BadArguments gettext('Table "%s" has not field "%s"', $cur_query_table->{'table'}->name,
1160 $alias);
1161  
1162 return (
1163 map {
1164 $self->_get_table_alias($cur_query_table)
1165 . $self->quote_identifier($alias . $_) . ' AS '
1166 . $self->quote_identifier($alias . ($field->{'i18n'} && $self->{'__ALL_LANGS__'} ? $_ : ''))
1167 } $field->{'i18n'} ? $self->_get_locale_suffixes($opts{'locale'}) : ('')
1168 );
1169  
1170 } elsif (!ref($expr)) {
1171 # {new_field_name => 'field_name'}
1172 my $field =
1173 $cur_query_table->{'table'}->_fields_hs()->{$expr}
1174 || $self->{'without_check_fields'}
1175 || throw Exception::BadArguments gettext('Table "%s" has not field "%s"', $cur_query_table->{'table'}->name,
1176 $expr);
1177  
1178 return (
1179 map {
1180 $self->_get_table_alias($cur_query_table)
1181 . $self->quote_identifier($expr . $_)
1182 . (
1183 defined($alias)
1184 ? ' AS '
1185 . $self->quote_identifier($alias . ($field->{'i18n'} && $self->{'__ALL_LANGS__'} ? $_ : ''))
1186 : ''
1187 )
1188 } $field->{'i18n'} ? $self->_get_locale_suffixes($opts{'locale'}) : ('')
1189 );
1190  
1191 } elsif (
1192 ref($expr) eq 'HASH'
1193 && (!ref([%$expr]->[1])
1194 || (blessed([%$expr]->[1]) && [%$expr]->[1]->isa('QBit::Application::Model::DB::Table')))
1195 )
1196 {
1197 # {alias => {field_name => 'tbl_alias'}} {alias => {field_name => $...db->tbl}}
1198 my $query_table = $self->_get_table([%$expr]->[1]);
1199 my $field =
1200 $query_table->{'table'}->_fields_hs()->{[%$expr]->[0]}
1201 || $self->{'without_check_fields'}
1202 || throw Exception::BadArguments gettext('Table "%s" has not field "%s"', $query_table->{'table'}->name,
1203 [%$expr]->[0]);
1204  
1205 return (
1206 map {
1207 $self->_get_table_alias($query_table)
1208 . $self->quote_identifier([%$expr]->[0] . $_)
1209 . (
1210 defined($alias)
1211 ? ' AS '
1212 . $self->quote_identifier($alias . ($field->{'i18n'} && $self->{'__ALL_LANGS__'} ? $_ : ''))
1213 : ''
1214 )
1215 } $field->{'i18n'} ? $self->_get_locale_suffixes($opts{'locale'}) : ('')
1216 );
1217  
1218 } elsif (ref($expr) eq 'HASH' && ref([%$expr]->[1]) eq 'ARRAY') {
1219 # Function: {field => [SUM => {'f1', \5, ['-' => ['f2', 'f3']]}]}
1220 my @res = ();
1221 my $func_name = [%$expr]->[0];
1222 $func_name =~ s/^\s+|\s+$//g;
1223 my @arg_sets =
1224 map {[$self->_field_to_sql(undef, $_, $cur_query_table, %opts, offset => $opts{'offset'} + 4)]}
1225 @{[%$expr]->[1]};
1226 my @locale_suffixes =
1227 $self->{'__ALL_LANGS__'} && (grep {@$_ > 1} @arg_sets) ? $self->_get_locale_suffixes($opts{'locale'}) : ('');
1228  
1229 for my $i (0 .. @locale_suffixes - 1) {
1230 my @args = map {@$_ > 1 ? $_->[$i] : $_->[0]} @arg_sets;
1231 push(@res,
1232 "$func_name("
1233 . CORE::join(', ', @args) . ')'
1234 . (defined($alias) ? ' AS ' . $self->quote_identifier($alias . $locale_suffixes[$i]) : ''));
1235 }
1236 return @res;
1237  
1238 } elsif (ref($expr) eq 'ARRAY' && @$expr == 2 && ref($expr->[1]) eq 'ARRAY') {
1239 # Expression: {field => ['+' => ['f1', 'f2', [f3 => '/' => \5]]]}
1240 my $offset = ' ' x $opts{'offset'};
1241 my @res = ();
1242 my $operator = $expr->[0];
1243 $operator =~ s/^\s+|\s+$//g;
1244 my @operand_sets =
1245 map {[$self->_field_to_sql(undef, $_, $cur_query_table, %opts, offset => $opts{'offset'} + 4)]} @{$expr->[1]};
1246  
1247 my @locale_suffixes = $self->{'__ALL_LANGS__'}
1248 && (grep {@$_ > 1} @operand_sets) ? $self->_get_locale_suffixes($opts{'locale'}) : ('');
1249  
1250 for my $i (0 .. @locale_suffixes - 1) {
1251 my @operands = map {@$_ > 1 ? $_->[$i] : $_->[0]} @operand_sets;
1252 if (grep {$operator eq $_} qw(AND OR)) {
1253 push(@res,
1254 "(\n$offset "
1255 . CORE::join("\n$offset $operator ", @operands)
1256 . "\n$offset)"
1257 . (defined($alias) ? ' AS ' . $self->quote_identifier($alias . $locale_suffixes[$i]) : ''));
1258 } else {
1259 push(@res,
1260 '('
1261 . CORE::join(" $operator ", @operands) . ')'
1262 . (defined($alias) ? ' AS ' . $self->quote_identifier($alias . $locale_suffixes[$i]) : ''));
1263 }
1264 }
1265  
1266 return @res;
1267  
1268 } elsif (ref($expr) eq 'ARRAY' && @$expr == 3) {
1269 # Comparison: [field => '=' => \5], [field => '=' => \[5, 10, 15]]
1270 my $offset = ' ' x $opts{'offset'};
1271 my @res = ();
1272 my ($cmp1, $operator, $cmp2) = @$expr;
1273  
1274 # Fix operator
1275 $operator =~ s/^\s+|\s+$//g;
1276 $operator = uc($operator);
1277 $operator =~ s/!=/<>/;
1278 $operator =~ s/==/=/;
1279  
1280 if ($operator eq '=') {
1281 if (ref($cmp2) eq 'SCALAR' && !defined($$cmp2)) {
1282 $operator = 'IS';
1283 } elsif (ref($cmp2) eq 'REF' && ref($$cmp2) eq 'ARRAY') {
1284 $operator = 'IN';
1285 }
1286 } elsif ($operator eq '<>') {
1287 if (ref($cmp2) eq 'SCALAR' && !defined($$cmp2)) {
1288 $operator = 'IS NOT';
1289 } elsif (ref($cmp2) eq 'REF' && ref($$cmp2) eq 'ARRAY') {
1290 $operator = 'NOT IN';
1291 }
1292 }
1293  
1294 $cmp1 = [$self->_field_to_sql(undef, $cmp1, $cur_query_table, %opts, offset => $opts{'offset'} + 4)];
1295  
1296 if (ref($cmp2) eq 'REF' && ref($$cmp2) eq 'ARRAY') {
1297 unless (@{$$cmp2}) {
1298 #['field', 'NOT IN', \[]] to sql: '1'
1299 #['field', 'IN', \[]] to sql: 'NULL'
1300  
1301 return (
1302 $self->_field_to_sql(
1303 undef, $operator =~ /^NOT/ ? \1 : \undef,
1304 $cur_query_table, %opts, offset => $opts{'offset'} + 4
1305 )
1306 );
1307 }
1308  
1309 $cmp2 = ['(' . CORE::join(', ', map {$self->quote($_)} @{$$cmp2}) . ')'];
1310 } elsif (blessed($cmp2) && $cmp2->isa(__PACKAGE__)) {
1311 ($cmp2) = $cmp2->get_sql_with_data(%opts, offset => $opts{'offset'} + 4);
1312 $cmp2 = ["(\n$offset $cmp2\n$offset)"];
1313 } else {
1314 $cmp2 = [$self->_field_to_sql(undef, $cmp2, $cur_query_table, %opts, offset => $opts{'offset'} + 4)];
1315 }
1316  
1317 my @locale_suffixes =
1318 $self->{'__ALL_LANGS__'} && @$cmp1 + @$cmp2 > 2 ? $self->_get_locale_suffixes($opts{'locale'}) : ('');
1319  
1320 for my $i (0 .. @locale_suffixes - 1) {
1321 push(@res,
1322 (exists($cmp1->[$i]) ? $cmp1->[$i] : $cmp1->[0])
1323 . " $operator "
1324 . (exists($cmp2->[$i]) ? $cmp2->[$i] : $cmp2->[0]));
1325 }
1326  
1327 return (
1328 (@res > 1 ? '(' . CORE::join(' OR ', @res) . ')' : $res[0])
1329 . (
1330 defined($alias)
1331 ? ' AS ' . $self->quote_identifier($alias)
1332 : ''
1333 )
1334 );
1335 } else {
1336 local $Data::Dumper::Terse = 1;
1337 local $Data::Dumper::Indent = 2;
1338 throw Exception::BadArguments gettext("Bad expression:\n%s", Dumper($expr));
1339 }
1340 }
1341  
1342 sub _get_table_alias {
1343 my ($self, $table) = @_;
1344  
1345 return $self->{'without_table_alias'} ? '' : $self->quote_identifier($self->_table_alias($table)) . '.';
1346 }
1347  
1348 TRUE;
1349  
1350 =pod
1351  
1352 For more information see code and test.
1353  
1354 =cut