blib/lib/DBIx/Struct.pm untested

filter: Statementstmt 0.0% 0 / 1160 Branchbran 0.0% 0 / 464 Conditioncond 0.0% 0 / 217 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 113 Podpod 0.0% 0 / 75 totaltotal 0.0% 0 / 2029 SCAR 108.8
CC
230
Cov
0%
_build_complex_query
3422.0
setup_row
1482.0
execute
870.0
CRAP 53130.0
1 package DBIx::Struct::JSON::Array;
2 use strict;
3 use warnings;
4  
5 sub TIEARRAY {
6 bless [$_[1], $_[2], $_[3]], $_[0];
7 }
8  
9 sub FETCHSIZE {
10 scalar @{$_[0][0]};
11 }
12  
13 sub STORESIZE {
14 $_[0][1]{$_[0][2]} = undef;
15 $#{$_[0][0]} = $_[1] - 1;
16 }
17  
18 sub STORE {
19 $_[0][1]{$_[0][2]} = undef;
20 $_[0][0][$_[1]] = $_[2];
21 }
22 sub FETCH {$_[0][0][$_[1]]}
23  
24 sub CLEAR {
25 $_[0][1]{$_[0][2]} = undef;
26 @{$_[0][0]} = ();
27 }
28  
29 sub POP {
30 $_[0][1]{$_[0][2]} = undef;
31 pop(@{$_[0][0]});
32 }
33  
34 sub PUSH {
35 my $o = shift;
36 $o->[1]{$o->[2]} = undef;
37 push(@{$o->[0]}, @_);
38 }
39  
40 sub SHIFT {
41 $_[0][1]{$_[0][2]} = undef;
42 shift(@{$_[0][0]});
43 }
44  
45 sub UNSHIFT {
46 my $o = shift;
47 $o->[1]{$o->[2]} = undef;
48 unshift(@$o, @_);
49 }
50 sub EXISTS {exists $_[0][0]->[$_[1]]}
51 sub DELETE {delete $_[0][0]->[$_[1]]}
52  
53 sub SPLICE {
54 my $ob = shift;
55 my $sz = $ob->FETCHSIZE;
56 my $off = @_ ? shift : 0;
57 $off += $sz if $off < 0;
58 my $len = @_ ? shift : $sz - $off;
59 $ob->[1]{$ob->[2]} = undef;
60 return splice(@{$ob->[0]}, $off, $len, @_);
61 }
62  
63 package DBIx::Struct::JSON::Hash;
64 use strict;
65 use warnings;
66  
67 sub TIEHASH {
68 bless [$_[1], $_[2], $_[3]], $_[0];
69 }
70  
71 sub STORE {
72 $_[0][1]{$_[0][2]} = undef;
73 $_[0][0]->{$_[1]} = $_[2];
74 }
75  
76 sub FETCH {
77 $_[0][0]->{$_[1]};
78 }
79  
80 sub FIRSTKEY {
81 my $a = scalar keys %{$_[0][0]};
82 each %{$_[0][0]};
83 }
84  
85 sub NEXTKEY {
86 each %{$_[0][0]};
87 }
88  
89 sub EXISTS {
90 exists $_[0][0]->{$_[1]};
91 }
92  
93 sub DELETE {
94 $_[0][1]{$_[0][2]} = undef;
95 delete $_[0][0]->{$_[1]};
96 }
97  
98 sub CLEAR {
99 $_[0][1]{$_[0][2]} = undef;
100 %{$_[0][0]} = ();
101 }
102  
103 sub SCALAR {
104 scalar %{$_[0][0]};
105 }
106  
107 package DBIx::Struct::JSON;
108  
109 use strict;
110 use warnings;
111 use JSON;
112  
113 sub factory {
114 my ($class, $value_ref, $update_hash, $hash_key) = @_;
115 my $self;
116 if (not ref $$value_ref) {
117 my $jv = from_json($$value_ref) if $$value_ref;
118 $$value_ref = $jv if $jv;
119 }
120 if (not defined $$value_ref) {
121 $self = [undef, undef];
122 } elsif ('HASH' eq ref $$value_ref) {
123 my %h;
124 tie %h, 'DBIx::Struct::JSON::Hash', $$value_ref, $update_hash, $hash_key;
125 $self = [\%h, $$value_ref];
126 } elsif ('ARRAY' eq ref $$value_ref) {
127 my @a;
128 tie @a, 'DBIx::Struct::JSON::Array', $$value_ref, $update_hash, $hash_key;
129 $self = [\@a, $$value_ref];
130 }
131 $$value_ref = bless $self, $class;
132 }
133  
134 sub revert {
135 $_[0] = defined($_[0][1]) ? to_json $_[0][1] : undef;
136 }
137  
138 sub data {
139 $_[0][1];
140 }
141  
142 sub accessor {
143 $_[0][0];
144 }
145  
146 package DBIx::Struct::Connector;
147 use strict;
148 use warnings;
149 use base 'DBIx::Connector';
150  
151 our $db_reconnect_timeout = 30;
152  
153 sub _connect {
154 my ($self, @args) = @_;
155 for my $try (1 .. $db_reconnect_timeout) {
156 my $dbh = eval {$self->SUPER::_connect(@args)};
157 return $dbh if $dbh;
158 sleep 1 if $try != $db_reconnect_timeout;
159 }
160 die $@ if $@;
161 die "DB connect error";
162 }
163  
164 package DBIx::Struct::Error::String;
165 use strict;
166 use warnings;
167 use Carp;
168  
169 sub error_message (+%) {
170 my $msg = $_[0];
171 delete $msg->{result};
172 my $message = delete $msg->{message};
173 croak join "; ", $message, map {"$_: $msg->{$_}"} keys %$msg;
174 }
175  
176 package DBIx::Struct::Error::Hash;
177 use strict;
178 use warnings;
179  
180 sub error_message (+%) {
181 die $_[0];
182 }
183  
184 package DBIx::Struct;
185 use strict;
186 use warnings;
187 use SQL::Abstract;
188 use Digest::MD5;
189 use Data::Dumper;
190 use Scalar::Util 'refaddr';
191 use base 'Exporter';
192 use v5.14;
193  
194 our $VERSION = '0.48';
195  
196 our @EXPORT = qw{
197 one_row
198 all_rows
199 for_rows
200 new_row
201 };
202  
203 our @EXPORT_OK = qw{
204 connector
205 hash_ref_slice
206 };
207  
208 sub ccmap ($) {
209 my $name = $_[0];
210 $name =~ s/([[:upper:]])/_\l$1/g;
211 $name =~ s/^_//;
212 return $name;
213 }
214  
215 our $camel_case_map = \&ccmap;
216 our $conn;
217 our $update_on_destroy = 1;
218 our $connector_module = 'DBIx::Struct::Connector';
219 our $connector_constructor = 'new';
220 our $connector_pool;
221 our $connector_pool_method = 'get_connector';
222 our $connector_args = [];
223 our $connector_driver;
224 our $user_schema_namespace;
225 our $table_classes_namespace = 'DBC';
226 our $query_classes_namespace = 'DBQ';
227 our $error_message_class = 'DBIx::Struct::Error::String';
228 our %driver_pk_insert;
229  
230 sub error_message (+%) {
231 goto &DBIx::Struct::Error::String::error_message;
232 }
233  
234 %driver_pk_insert = (
235 _returning => sub {
236 my ($table, $pk_row_data, $pk_returninig) = @_;
237 my $ret;
238 if ($pk_row_data) {
239 $ret = <<INS;
240 ($pk_row_data) =
241 \$_->selectrow_array(\$insert . " $pk_returninig", undef, \@bind)
242 INS
243 } else {
244 $ret = <<INS;
245 \$_->do(\$insert, undef, \@bind)
246 INS
247 }
248 $ret .= <<INS
249 or DBIx::Struct::error_message {
250 result => 'SQLERR',
251 message => 'error '.\$_->errstr.' inserting into table $table'
252 };
253 INS
254 },
255 _last_id_undef => sub {
256 my ($table, $pk_row_data) = @_;
257 my $ret;
258 $ret = <<INS;
259 \$_->do(\$insert, undef, \@bind)
260 or DBIx::Struct::error_message {
261 result => 'SQLERR',
262 message => 'error '.\$_->errstr.' inserting into table $table'
263 };
264 INS
265 if ($pk_row_data) {
266 $ret .= <<INS;
267 $pk_row_data = \$_->last_insert_id(undef, undef, undef, undef);
268 INS
269 }
270 },
271 _last_id_empty => sub {
272 my ($table, $pk_row_data) = @_;
273 my $ret;
274 $ret = <<INS;
275 \$_->do(\$insert, undef, \@bind)
276 or DBIx::Struct::error_message {
277 result => 'SQLERR',
278 message => 'error '.\$_->errstr.' inserting into table $table'
279 };
280 INS
281 if ($pk_row_data) {
282 $ret .= <<INS;
283 $pk_row_data = \$_->last_insert_id("", "", "", "");
284 INS
285 }
286 }
287 );
288  
289 $driver_pk_insert{Pg} = $driver_pk_insert{_returning};
290 $driver_pk_insert{mysql} = $driver_pk_insert{_last_id_undef};
291 $driver_pk_insert{SQLite} = $driver_pk_insert{_last_id_empty};
292  
293 sub hash_ref_slice($@) {
294 my ($hashref, @slice) = @_;
295 error_message {
296 message => "first parameter is not hash reference",
297 result => 'INTERR',
298 }
299 if 'HASH' ne ref $hashref;
300 map {$_ => $hashref->{$_}} @slice;
301 }
302  
303 my @already_exported_to;
304  
305 sub connector {
306 $conn;
307 }
308  
309 sub connector_from_pool {
310 $connector_pool->$connector_pool_method();
311 }
312  
313 sub set_connector_pool {
314 $connector_pool = $_[0];
315 if (\&connector != \&connector_from_pool) {
316 no warnings 'redefine';
317 no strict 'refs';
318 *connector = \&connector_from_pool;
319 for my $aep (@already_exported_to) {
320 *{"$aep\::connector"} = \&connector;
321 }
322 }
323 }
324  
325 sub set_user_schema_namespace {
326 $user_schema_namespace = $_[0];
327 }
328  
329 sub set_connector_pool_method {
330 $connector_pool_method = $_[0];
331 }
332  
333 sub set_connector_object {
334 *conn = \$_[0];
335 }
336  
337 sub set_camel_case_map {
338 error_message {
339 message => "CamelCaseMap must be code reference",
340 result => 'SQLERR',
341 } if 'CODE' ne ref $_[0];
342 $camel_case_map = $_[0];
343 }
344  
345 sub check_package_scalar {
346 my ($package, $scalar) = @_;
347 no strict 'refs';
348 my $pr = \%{$package . '::'};
349 my $er = $$pr{$scalar};
350 return unless $er;
351 defined *{$er}{'SCALAR'};
352 }
353  
354 sub import {
355 my ($class, @args) = @_;
356 my $defconn = 0;
357 my $_emc = 0;
358 my $_cp = 0;
359 my $_c = 0;
360 for (my $i = 0; $i < @args; ++$i) {
361 if ($args[$i] eq 'connector_module') {
362 (undef, $connector_module) = splice @args, $i, 2;
363 --$i;
364 if (not $defconn and check_package_scalar($connector_module, 'conn')) {
365 no strict 'refs';
366 set_connector_object(${$connector_module . '::conn'});
367 }
368 } elsif ($args[$i] eq 'connector_constructor') {
369 (undef, $connector_constructor) = splice @args, $i, 2;
370 --$i;
371 } elsif ($args[$i] eq 'camel_case_map' && 'CODE' eq ref $args[$i]) {
372 (undef, $camel_case_map) = splice @args, $i, 2;
373 --$i;
374 } elsif ($args[$i] eq 'user_schema_namespace') {
375 (undef, $user_schema_namespace) = splice @args, $i, 2;
376 --$i;
377 } elsif ($args[$i] eq 'table_classes_namespace') {
378 (undef, $table_classes_namespace) = splice @args, $i, 2;
379 --$i;
380 } elsif ($args[$i] eq 'query_classes_namespace') {
381 (undef, $query_classes_namespace) = splice @args, $i, 2;
382 --$i;
383 } elsif ($args[$i] eq 'connect_timeout') {
384 (undef, $db_reconnect_timeout) = splice @args, $i, 2;
385 --$i;
386 } elsif ($args[$i] eq 'error_class') {
387 my (undef, $emc) = splice @args, $i, 2;
388 $error_message_class = $emc;
389 $_emc = 1;
390 --$i;
391 } elsif ($args[$i] eq 'connector_pool') {
392 (undef, $connector_pool) = splice @args, $i, 2;
393 $_cp = 1;
394 --$i;
395 } elsif ($args[$i] eq 'connector_pool_method') {
396 (undef, $connector_pool_method) = splice @args, $i, 2;
397 --$i;
398 } elsif ($args[$i] eq 'connector_args') {
399 (undef, $connector_args) = splice @args, $i, 2;
400 --$i;
401 } elsif ($args[$i] eq 'connector') {
402 $_c = 1;
403 } elsif ($args[$i] eq 'connector_object') {
404 $defconn = 1;
405 set_connector_object($args[$i + 1]);
406 splice @args, $i, 2;
407 --$i;
408 }
409 }
410 if ($_emc) {
411 no warnings 'redefine';
412 no strict 'refs';
413 *error_message = \&{$error_message_class . "::error_message"};
414 }
415 if ($_cp) {
416 no warnings 'redefine';
417 no strict 'refs';
418 *connector = \&connector_from_pool;
419 for my $aep (@already_exported_to) {
420 *{"$aep\::connector"} = \&connector;
421 }
422 }
423 my $callpkg = caller;
424 push @already_exported_to, $callpkg if $_c;
425 my %imps = map {$_ => undef} @args, @EXPORT;
426 $class->export_to_level(1, $class, keys %imps);
427 }
428  
429 sub _not_yet_connected {
430 if (!$connector_pool && !$conn) {
431 my ($dsn, $user, $password) = @_;
432 if ($dsn && $dsn !~ /^dbi:/i) {
433 $dsn = "dbi:Pg:dbname=$dsn";
434 }
435 my $connect_attrs = {
436 AutoCommit => 1,
437 PrintError => 0,
438 AutoInactiveDestroy => 1,
439 RaiseError => 0,
440 };
441 if ($dsn) {
442 my ($driver) = $dsn =~ /^dbi:(\w*?)(?:\((.*?)\))?:/i;
443 if ($driver) {
444 if ($driver eq 'Pg') {
445 $connect_attrs->{pg_enable_utf8} = 1;
446 } elsif ($driver eq 'mysql') {
447 $connect_attrs->{mysql_enable_utf8} = 1;
448 } elsif ($driver eq 'SQLite') {
449 $connect_attrs->{sqlite_unicode} = 1;
450 }
451 }
452 }
453 if (!@$connector_args) {
454 @$connector_args = ($dsn, $user, $password, $connect_attrs);
455 }
456 $conn = $connector_module->$connector_constructor(@$connector_args)
457 or error_message {
458 message => "DB connect error",
459 result => 'SQLERR',
460 };
461 $conn->mode('fixup');
462 }
463 '' =~ /()/;
464 $connector_driver = connector->driver->{driver};
465 no warnings 'redefine';
466 *connect = \&connector;
467 populate();
468 connector;
469 }
470  
471 sub connect {
472 goto &_not_yet_connected;
473 }
474  
475 {
476 my $md5 = Digest::MD5->new;
477  
478 sub make_name {
479 my ($table) = @_;
480 my $simple_table = (index($table, " ") == -1);
481 my $ncn;
482 if ($simple_table) {
483 $ncn = $table_classes_namespace . "::" . join('', map {ucfirst($_)} split(/[^a-zA-Z0-9]/, $table));
484 } else {
485 $md5->add($table);
486 $ncn = $query_classes_namespace . "::" . "G" . $md5->hexdigest;
487 $md5->reset;
488 }
489 $ncn;
490 }
491 }
492  
493 sub populate {
494 my @tables;
495 DBIx::Struct::connect->run(
496 sub {
497 my $sth = $_->table_info('', '%', '%', "TABLE");
498 return if not $sth;
499 my $tables = $sth->fetchall_arrayref;
500 @tables = map {
501 (my $t = $_->[2]) =~ s/"//g;
502 $t;
503 } grep {
504 $_->[3] eq 'TABLE' and $_->[2] !~ /^sql_/
505 } @$tables;
506 }
507 );
508 for (@tables) {
509 my $ncn = setup_row($_);
510 if ($user_schema_namespace) {
511 (my $uncn = $ncn) =~ s/^.*:://;
512 eval "use ${user_schema_namespace}::${uncn}";
513 no strict 'refs';
514 eval {
515 if (
516 keys %{"${user_schema_namespace}::${uncn}::"}
517 and ( not ${"${user_schema_namespace}::${uncn}::"}{ISA}
518 or not "${user_schema_namespace}::${uncn}"->isa($ncn))
519 )
520 {
521 unshift @{"${user_schema_namespace}::${uncn}::ISA"}, $ncn;
522 }
523 };
524 }
525 }
526 }
527  
528 #<<<
529 my @uneq = (
530 qr/LessThanEqual$/, '<=',
531 qr/LessThan$/, '<',
532 qr/GreaterThanEqual$/, '>=',
533 qr/GreaterThan$/, '>',
534 qr/IsNull$/, sub {"'$_[0]' => {'=', undef}"},
535 qr/IsNotNull$/, sub {"'$_[0]' => {'!=', undef}"},
536 qr/IsNot$/, '!=',
537 qr/NotNull$/, sub {"'$_[0]' => {'!=', undef}"},
538 qr/NotEquals$/, '!=',
539 qr/NotIn$/, '-not_in',
540 qr/NotLike$/, '-not_like',
541 qr/IsEqualTo$/, '=',
542 qr/IsTrue$/, sub {"-bool => '$_[0]'"},
543 qr/IsFalse$/, sub {"-not_bool => '$_[0]'"},
544 qr/Equals$/, '=',
545 qr/True$/, sub {"-bool => '$_[0]'"},
546 qr/False$/, sub {"-not_bool => '$_[0]'"},
547 qr/Like$/, '-like',
548 qr/Is$/, '=',
549 qr/Not$/, '!=',
550 qr/In$/, '-in',
551 );
552 #>>>
553  
554 sub _parse_find_by {
555 my ($table, $find) = @_;
556 $find =~ s/^find(?<what>.*?)By(?![[:lower:]])// || $find =~ s/^find(?<what>.*)// or die "bad pattern: $find";
557 my $what = $+{what} || 'All';
558 $what =~ s/(?<distinct>Distinct)(?![[:lower:]])//;
559 my $distinct = $+{distinct} // 0;
560 $what =~ s/((?<type>(All|One|First))(?<limit>\d+)?)(?![[:lower:]])//;
561 my $type = $+{type} // 'All';
562 my $limit = $+{limit};
563 $what =~ s/(?<column>\w+)//;
564 my $column = $camel_case_map->($+{column} // '');
565 $find =~ s/OrderBy(?<order>.*?)(?<asc>Asc|Desc)(?=[[:upper:]]|$)// || $find =~ s/OrderBy(?<order>.*?)$//;
566 my $order = $+{order};
567 my $asc = $+{asc} || 'Asc';
568 my $where = $find;
569  
570 if ($type eq 'First' && !$limit) {
571 $limit = 1;
572 }
573 if ($limit && $limit == 1) {
574 $type = 'One';
575 }
576 my $pi = 1;
577 my $pp = sub {
578 my ($param) = @_;
579 my $found;
580 for (my $i = 0; $i < @uneq; $i += 2) {
581 if ($param =~ s/$uneq[$i]//) {
582 $found = $i + 1;
583 last;
584 }
585 }
586 $param = $camel_case_map->($param);
587 my $ret;
588 if ($found) {
589 if ('CODE' eq ref $uneq[$found]) {
590 $ret = $uneq[$found]->($param);
591 } else {
592 $ret = "'$param' => { '$uneq[$found]' => \$_[$pi]}";
593 ++$pi;
594 }
595 } else {
596 $ret = "'$param' => \$_[$pi]";
597 ++$pi;
598 }
599 $ret;
600 };
601 #<<<
602 my $conds = join(
603 ", ",
604 map {
605 /And(?![[:lower:]])/
606 ? '-and => [' . join(", ", map {$pp->($_)} split /And(?![[:lower:]])/x, $_) . ']'
607 : $pp->($_);
608 } split /Or(?![[:lower:]])/, $where
609 );
610 #>>>
611 my $obj = $type eq 'One' ? 'DBIx::Struct::one_row' : 'DBIx::Struct::all_rows';
612 my $flags = $column ? ", -column => '$column'" : '';
613 $flags = $distinct ? $flags ? ", -distinct => '$column'" : ", '-distinct'" : $flags;
614 $order =
615 $order
616 ? $asc eq 'Asc'
617 ? ", -order_by => '" . $camel_case_map->($order) . "'"
618 : ", -order_by => {-desc => '" . $camel_case_map->($order) . "'}"
619 : '';
620 $where = $conds ? ", -where => [$conds]" : '';
621 $limit = $limit && $limit > 1 && $type ne 'One' ? ", -limit => $limit" : '';
622 my $tspec = "'$table'" . $flags;
623 $tspec = "[$tspec]" if $column;
624 $tspec .= $where . $order . $limit;
625 return "sub { $obj($tspec) }";
626 }
627  
628 sub _row_data () {0}
629 sub _row_updates () {1}
630  
631 sub make_object_new {
632 my ($table, $required, $pk_row_data, $pk_returninig) = @_;
633 my $new = <<NEW;
634 sub new {
635 my \$class = \$_[0];
636 my \$self = [ [] ];
637 bless \$self, \$class;
638 if(CORE::defined(\$_[1]) && CORE::ref(\$_[1]) eq 'ARRAY') {
639 \$self->[@{[_row_data]}] = \$_[1];
640 }
641 NEW
642 if (not ref $table) {
643 $new .= <<NEW;
644 else {
645 my \%insert;
646 for(my \$i = 1; \$i < \@_; \$i += 2) {
647 if (CORE::exists \$fields{\$_[\$i]}) {
648 my \$f = \$_[\$i];
649 \$self->[@{[_row_data]}]->[\$fields{\$_[\$i]}] = \$_[\$i + 1];
650 \$insert{\$f} = \$_[\$i + 1];
651 } else {
652 DBIx::Struct::error_message {
653 result => 'SQLERR',
654 message => "unknown column \$_[\$i] inserting into table $table"
655 }
656 }
657 }
658 my (\@insert, \@values, \@bind);
659 \@insert =
660 CORE::map {
661 if(CORE::ref(\$insert{\$_}) eq 'ARRAY' and CORE::ref(\$insert{\$_}[0]) eq 'SCALAR') {
662 CORE::push \@bind, \@{\$insert{\$_}}[1..\$#{\$insert{\$_}}];
663 CORE::push \@values, \${\$insert{\$_}[0]};
664 DBIx::Struct::connect->dbh->quote_identifier(\$_);
665 } elsif(CORE::ref(\$insert{\$_}) eq 'REF' and CORE::ref(\${\$insert{\$_}}) eq 'ARRAY') {
666 if(CORE::defined \${\$insert{\$_}}->[0]) {
667 CORE::push \@bind, \@{\${\$insert{\$_}}}[1..\$#{\${\$insert{\$_}}}];
668 CORE::push \@values, \${\$insert{\$_}}->[0];
669 DBIx::Struct::connect->dbh->quote_identifier(\$_);
670 } else {
671 CORE::push \@values, "null";
672 DBIx::Struct::connect->dbh->quote_identifier(\$_)
673 }
674 } elsif(CORE::ref(\$insert{\$_}) eq 'SCALAR') {
675 CORE::push \@values, \${\$insert{\$_}};
676 DBIx::Struct::connect->dbh->quote_identifier(\$_);
677 } elsif(CORE::exists (\$json_fields{\$_})
678 && (CORE::ref(\$insert{\$_}) eq 'ARRAY' || CORE::ref(\$insert{\$_}) eq 'HASH')) {
679 CORE::push \@bind, JSON::to_json(\$insert{\$_});
680 CORE::push \@values, "?";
681 DBIx::Struct::connect->dbh->quote_identifier(\$_);
682 } else {
683 CORE::push \@bind, \$insert{\$_};
684 CORE::push \@values, "?";
685 DBIx::Struct::connect->dbh->quote_identifier(\$_);
686 }
687 } CORE::keys \%insert;
688 my \$insert;
689 if(\%insert){
690 \$insert = "insert into $table (" . CORE::join( ", ", \@insert) . ") values ("
691 . CORE::join( ", ", \@values) . ")";
692 } else {
693 \$insert = "insert into $table values (default)";
694 }
695 NEW
696 if ($required) {
697 $new .= <<NEW;
698 for my \$r ($required) {
699 DBIx::Struct::error_message {
700 result => 'SQLERR',
701 message => "required field \$r is absent for table $table"
702 } if not CORE::exists \$insert{\$r};
703 }
704 NEW
705 }
706 $new .= <<NEW;
707 DBIx::Struct::connect->run(
708 sub {
709 NEW
710 $new .= $driver_pk_insert{$connector_driver}->($table, $pk_row_data, $pk_returninig);
711 $new .= <<NEW;
712 });
713 }
714 NEW
715 }
716 $new .= <<NEW;
717 \$self;
718 }
719 NEW
720 $new;
721 }
722  
723 sub make_object_filter_timestamp {
724 my ($timestamps) = @_;
725 my $filter_timestamp = <<FTS;
726 sub filter_timestamp {
727 my \$self = \$_[0];
728 if(\@_ == 1) {
729 for my \$f ($timestamps) {
730 if(\$self->[@{[_row_data]}][\$fields{\$f}]) {
731 \$self->[@{[_row_data]}][\$fields{\$f}] =~ s/\\.\\d+(\$|\\+|\\-)/\$1/;
732 \$self->[@{[_row_data]}][\$fields{\$f}] =~ s/(\\+|\\-)(\\d{2})\$/\$1\${2}00/;
733 }
734 }
735 } else {
736 for my \$f (\@_[1..\$#_]) {
737 if(\$self->[@{[_row_data]}][\$fields{\$f}]) {
738 \$self->[@{[_row_data]}][\$fields{\$f}] =~ s/\\.\\d+(\$|\\+|\\-)/\$1/;
739 \$self->[@{[_row_data]}][\$fields{\$f}] =~ s/(\\+|\\-)(\\d{2})\$/\$1\${2}00/;
740 }
741 }
742 }
743 '' =~ /()/;
744 \$self;
745 }
746 FTS
747 $filter_timestamp;
748 }
749  
750 sub make_object_set {
751 my $table = $_[0];
752 my $set = <<SET;
753 sub set {
754 my \$self = \$_[0];
755 my \@unknown_columns;
756 if(CORE::defined(\$_[1])) {
757 if(CORE::ref(\$_[1]) eq 'ARRAY') {
758 \$self->[@{[_row_data]}] = \$_[1];
759 \$self->[@{[_row_updates]}] = {};
760 } elsif(CORE::ref(\$_[1]) eq 'HASH') {
761 for my \$f (CORE::keys \%{\$_[1]}) {
762 if (CORE::exists \$fields{\$f}) {
763 \$self->\$f(\$_[1]->{\$f});
764 } else {
765 CORE::push \@unknown_columns, \$f;
766 }
767 }
768 } elsif(not CORE::ref(\$_[1])) {
769 for(my \$i = 1; \$i < \@_; \$i += 2) {
770 if (CORE::exists \$fields{\$_[\$i]}) {
771 my \$f = \$_[\$i];
772 \$self->\$f(\$_[\$i + 1]);
773 } else {
774 CORE::push \@unknown_columns, \$_[\$i];
775 }
776 }
777 }
778 }
779 DBIx::Struct::error_message {
780 result => 'SQLERR',
781 message => 'unknown columns '.CORE::join(", ", \@unknown_columns).' for $table->data'
782 } if \@unknown_columns;
783 \$self;
784 }
785 SET
786 $set;
787 }
788  
789 sub make_object_data {
790 my $table = $_[0];
791 my $data = <<DATA;
792 sub data {
793 my \$self = \$_[0];
794 my \@ret_keys;
795 my \$ret;
796 if(CORE::defined(\$_[1])) {
797 if(CORE::ref(\$_[1]) eq 'ARRAY') {
798 if(!\@{\$_[1]}) {
799 \$ret = \$self->[@{[_row_data]}];
800 } else {
801 \$ret = [CORE::map {\$self->[@{[_row_data]}]->[\$fields{\$_}] } \@{\$_[1]}];
802 }
803 } else {
804 for my \$k (\@_[1..\$#_]) {
805 CORE::push \@ret_keys, \$k if CORE::exists \$fields{\$k};
806 }
807 }
808 } else {
809 \@ret_keys = keys \%fields;
810 }
811 my \@unknown_columns = CORE::grep {not CORE::exists \$fields{\$_}} \@ret_keys;
812 DBIx::Struct::error_message {
813 result => 'SQLERR',
814 message => 'unknown columns '.CORE::join(", ", \@unknown_columns).' for $table->data'
815 } if \@unknown_columns;
816 \$ret = {
817 CORE::map {\$_ => \$self->\$_} \@ret_keys
818 } if not CORE::defined \$ret;
819 \$ret;
820 }
821 DATA
822 $data;
823 }
824  
825 sub make_object_update {
826 my ($table, $pk_where, $pk_row_data) = @_;
827 my $update;
828 if (not ref $table) {
829  
830 # means this is just one simple table
831 $update = <<UPD;
832 sub update {
833 my \$self = \$_[0];
834 if(\@_ > 1 && CORE::ref(\$_[1]) eq 'HASH') {
835 my (\$set, \$where, \@bind, \@bind_where);
836 {
837 no strict 'vars';
838 local *set_hash = \$_[1];
839 my \@unknown_columns = CORE::grep {not CORE::exists \$fields{\$_}} CORE::keys %set_hash;
840 DBIx::Struct::error_message {
841 result => 'SQLERR',
842 message => 'unknown columns '.CORE::join(", ", \@unknown_columns).' updating table $table'
843 } if \@unknown_columns;
844 \$set =
845 CORE::join ", ",
846 CORE::map {
847 if(CORE::ref(\$set_hash{\$_}) eq 'ARRAY' and CORE::ref(\$set_hash{\$_}[0]) eq 'SCALAR') {
848 CORE::push \@bind, \@{\$set_hash{\$_}}[1..\$#{\$set_hash{\$_}}];
849 DBIx::Struct::connect->dbh->quote_identifier(\$_) . " = " . \${\$set_hash{\$_}[0]};
850 } elsif(CORE::ref(\$set_hash{\$_}) eq 'REF' and CORE::ref(\${\$set_hash{\$_}}) eq 'ARRAY') {
851 if(CORE::defined \${\$set_hash{\$_}}->[0]) {
852 CORE::push \@bind, \@{\${\$set_hash{\$_}}}[1..\$#{\${\$set_hash{\$_}}}];
853 DBIx::Struct::connect->dbh->quote_identifier(\$_) . " = " . \${\$set_hash{\$_}}->[0];
854 } else {
855 DBIx::Struct::connect->dbh->quote_identifier(\$_) . " = null"
856 }
857 } elsif(CORE::ref(\$set_hash{\$_}) eq 'SCALAR') {
858 DBIx::Struct::connect->dbh->quote_identifier(\$_) . " = " . \${\$set_hash{\$_}};
859 } elsif(CORE::exists(\$json_fields{\$_})
860 && (CORE::ref(\$set_hash{\$_}) eq 'ARRAY' || CORE::ref(\$set_hash{\$_}) eq 'HASH')) {
861 CORE::push \@bind, JSON::to_json(\$set_hash{\$_});
862 DBIx::Struct::connect->dbh->quote_identifier(\$_) . " = ?"
863 } else {
864 CORE::push \@bind, \$set_hash{\$_};
865 DBIx::Struct::connect->dbh->quote_identifier(\$_) . " = ?"
866 }
867 } CORE::keys \%set_hash;
868 }
869 if(\@_ > 2) {
870 my \$cond = \$_[2];
871 if(not CORE::ref(\$cond)) {
872 \$cond = {(selectKeys)[0] => \$_[2]};
873 }
874 (\$where, \@bind_where) = SQL::Abstract->new->where(\$cond);
875 }
876 return DBIx::Struct::connect->run(sub {
877 \$_->do(qq{update $table set \$set \$where}, undef, \@bind, \@bind_where)
878 or DBIx::Struct::error_message {
879 result => 'SQLERR',
880 message => 'error '.\$_->errstr.' updating table $table'
881 }
882 });
883 } elsif (CORE::ref(\$self) && \@\$self > 1 && \%{\$self->[@{[_row_updates]}]}) {
884 my (\$set, \@bind);
885 {
886 no strict 'vars';
887 \$set =
888 CORE::join ", ",
889 CORE::map {
890 local *column_value = \\\$self->[@{[_row_data]}][\$fields{\$_}];
891 if(CORE::ref(\$column_value) eq 'ARRAY' and CORE::ref(\$column_value->[0]) eq 'SCALAR') {
892 CORE::push \@bind, \@{\$column_value}[1..\$#\$column_value];
893 DBIx::Struct::connect->dbh->quote_identifier(\$_) . " = " . \${\$column_value->[0]};
894 } elsif(CORE::ref(\$column_value) eq 'REF' and CORE::ref(\${\$column_value}) eq 'ARRAY') {
895 if(CORE::defined \${\$column_value}->[0]) {
896 CORE::push \@bind, \@{\${\$column_value}}[1..\$#{\${\$column_value}}];
897 DBIx::Struct::connect->dbh->quote_identifier(\$_) . " = " . \${\$column_value}->[0];
898 } else {
899 DBIx::Struct::connect->dbh->quote_identifier(\$_) . " = null"
900 }
901 } elsif(CORE::ref(\$column_value) && CORE::ref(\$column_value) =~ /^DBIx::Struct::JSON/) {
902 \$column_value->revert;
903 CORE::push \@bind, \$column_value;
904 DBIx::Struct::connect->dbh->quote_identifier(\$_) . " = ?"
905 } elsif(CORE::ref(\$column_value) eq 'SCALAR') {
906 DBIx::Struct::connect->dbh->quote_identifier(\$_) . " = " . \$\$column_value;
907 } else {
908 CORE::push \@bind, \$column_value;
909 DBIx::Struct::connect->dbh->quote_identifier(\$_) . " = ?"
910 }
911 } CORE::keys \%{\$self->[@{[_row_updates]}]};
912 }
913 my \$update_query = qq{update $table set \$set where $pk_where};
914 DBIx::Struct::connect->run(
915 sub {
916 \$_->do(\$update_query, undef, \@bind, $pk_row_data)
917 or DBIx::Struct::error_message {
918 result => 'SQLERR',
919 message => 'error '.\$_->errstr.' updating table $table',
920 query => \$update_query,
921 bind => \\\@bind,
922 }
923 }
924 );
925 \$#\$self = @{[_row_data]};
926 }
927 \$self;
928 }
929 UPD
930 } else {
931 $update = <<UPD;
932 sub update {}
933 UPD
934 }
935 $update;
936 }
937  
938 sub make_object_delete {
939 my ($table, $pk_where, $pk_row_data) = @_;
940 my $delete;
941 if (not ref $table) {
942 $delete = <<DEL;
943 sub delete {
944 my \$self = \$_[0];
945 if(Scalar::Util::blessed \$self) {
946 DBIx::Struct::connect->run(
947 sub {
948 \$_->do(qq{delete from $table where $pk_where}, undef, $pk_row_data)
949 or DBIx::Struct::error_message {
950 result => 'SQLERR',
951 message => 'error '.\$_->errstr.' updating table $table'
952 }
953 });
954 return \$self;
955 }
956 my \$where = '';
957 my \@bind;
958 my \$cond = \$_[1] if \@_ > 1;
959 if(not CORE::ref(\$cond)) {
960 \$cond = {};
961 my \@keys = selectKeys();
962 for(my \$i = 1; \$i < \@_; ++\$i) {
963 DBIx::Struct::error_message {
964 result => 'SQLERR',
965 message => "Too many keys to delete for $table"
966 } if not CORE::defined \$keys[\$i-1];
967 \$cond->{\$keys[\$i-1]} = \$_[\$i];
968 }
969 }
970 my \@rpar = ();
971 if(\$cond) {
972 (\$where, \@bind) = SQL::Abstract->new->where(\$cond);
973 \@rpar = (undef, \@bind);
974 }
975 return DBIx::Struct::connect->run(sub {
976 \$_->do(qq{delete from $table \$where}, \@rpar)
977 or DBIx::Struct::error_message {
978 result => 'SQLERR',
979 message => 'error '.\$_->errstr.' updating table $table'
980 }
981 });
982 }
983 DEL
984 } else {
985 $delete = <<DEL
986 sub delete {}
987 DEL
988 }
989 $delete;
990 }
991  
992 sub make_object_autoload_find {
993 my ($table, $pk_where, $pk_row_data) = @_;
994 my $find = '';
995 if (not ref $table) {
996 $find = <<AUTOLOAD;
997 sub AUTOLOAD {
998 my \$self = \$_[0];
999 ( my \$method = \$AUTOLOAD ) =~ s{.*::}{};
1000
1001 if(Scalar::Util::blessed \$self) {
1002 \$self = CORE::ref \$self;
1003 }
1004 DBIx::Struct::error_message {
1005 result => 'SQLERR',
1006 message => "Unknown method \$method for $table"
1007 } if !\$self || !"\$self"->can("tableName") || \$method !~ /^find/;
1008 my \$func = DBIx::Struct::_parse_find_by('$table', \$method);
1009 my \$ncn = DBIx::Struct::make_name('$table');
1010 {
1011 no strict 'refs';
1012 *{\$ncn."::".\$method} = eval \$func;
1013 DBIx::Struct::error_message {
1014 result => 'SQLERR',
1015 message => "Error creating method \$method for $table: \$\@"
1016 } if \$\@;
1017 }
1018 goto &{\$ncn."::".\$method};
1019 }
1020 AUTOLOAD
1021 }
1022 $find;
1023 }
1024  
1025 sub make_object_fetch {
1026 my ($table, $pk_where, $pk_row_data) = @_;
1027 my $fetch;
1028 if (not ref $table) {
1029 $fetch = <<FETCH;
1030 sub fetch {
1031 my \$self = \$_[0];
1032 if(\@_ > 1) {
1033 my (\$where, \@bind);
1034 my \$cond = \$_[1];
1035 if(not CORE::ref(\$cond)) {
1036 \$cond = {(selectKeys)[0] => \$_[1]};
1037 }
1038 (\$where, \@bind) = SQL::Abstract->new->where(\$cond);
1039 DBIx::Struct::connect->run(sub {
1040 my \$rowref = \$_->selectrow_arrayref(qq{select * from $table \$where}, undef, \@bind)
1041 or DBIx::Struct::error_message {
1042 result => 'SQLERR',
1043 message => 'error '.\$_->errstr.' fetching table $table'
1044 };
1045 \$self->[@{[_row_data]}] = [\@\$rowref];
1046 });
1047 } else {
1048 DBIx::Struct::connect->run(
1049 sub {
1050 my \$rowref = \$_->selectrow_arrayref(qq{select * from $table where $pk_where}, undef, $pk_row_data)
1051 or DBIx::Struct::error_message {
1052 result => 'SQLERR',
1053 message => 'error '.\$_->errstr.' fetching table $table'
1054 };
1055 \$self->[@{[_row_data]}] = [\@\$rowref];
1056 });
1057 }
1058 \$self;
1059 }
1060 FETCH
1061 } else {
1062 $fetch = <<FETCH;
1063 sub fetch { \$_[0] }
1064 FETCH
1065 }
1066 $fetch;
1067 }
1068  
1069 sub _exists_row ($) {
1070 my $ncn = $_[0];
1071 no strict "refs";
1072 if (grep {!/::$/} keys %{"${ncn}::"}) {
1073 return 1;
1074 }
1075 return;
1076 }
1077  
1078 sub _parse_interface ($) {
1079 my $interface = $_[0];
1080 my %ret;
1081 $interface = [$interface] if not ref $interface;
1082 if ('ARRAY' eq ref $interface) {
1083 for my $i (@$interface) {
1084 my $dbc_name = make_name($i);
1085 error_message {
1086 result => 'SQLERR',
1087 message => "Unknown base interface table $i",
1088 }
1089 unless _exists_row $dbc_name;
1090 no strict 'refs';
1091 my $href = \%{"${dbc_name}::fkfuncs"};
1092 if ($href && %$href) {
1093 my @i = keys %$href;
1094 @ret{@i} = @{$href}{@i};
1095 }
1096 }
1097 } elsif ('HASH' eq ref $interface) {
1098 for my $i (keys %$interface) {
1099 my $dbc_name = make_name($i);
1100 error_message {
1101 result => 'SQLERR',
1102 message => "Unknown base interface table $i",
1103 }
1104 unless _exists_row $dbc_name;
1105 no strict 'refs';
1106 my $href = \%{"${dbc_name}::fkfuncs"};
1107 next if not $href or not %$href;
1108 my $fl = $interface->{$i};
1109 $fl = [$fl] if not ref $fl;
1110 if ('ARRAY' eq ref $fl) {
1111  
1112 for my $m (@$fl) {
1113 $ret{$m} = $href->{$m} if exists $href->{$m};
1114 }
1115 } else {
1116 error_message {
1117 result => 'SQLERR',
1118 message => "Usupported interface structure",
1119 };
1120 }
1121 }
1122 } else {
1123 error_message {
1124 result => 'SQLERR',
1125 message => "Unknown interface structure: " . ref($interface),
1126 };
1127 }
1128 \%ret;
1129 }
1130  
1131 sub make_object_to_json {
1132 my ($table, $field_types, $fields) = @_;
1133 my @to_types = map {[
1134 $_,
1135 qq|!defined(\$self->[@{[_row_data]}][$fields->{$_}])? undef: |
1136 . (
1137 $field_types->{$_} eq 'number' ? "0+\$self->[@{[_row_data]}][$fields->{$_}]"
1138 : $field_types->{$_} eq 'boolean' ? "\$self->[@{[_row_data]}][$fields->{$_}]? \\1: \\0"
1139 : $field_types->{$_} eq 'json'
1140 ? "CORE::ref(\$self->[@{[_row_data]}]->[$fields->{$_}])? \$self->[@{[_row_data]}][$fields->{$_}]->data"
1141 . ": JSON::from_json(\$self->[@{[_row_data]}][$fields->{$_}])"
1142 : "\"\$self->[@{[_row_data]}][$fields->{$_}]\""
1143 )
1144 ]
1145 } keys %$field_types;
1146 my $field_to_types = join ",\n\t\t\t\t ", map {qq|"$_->[0]" => $_->[1]|} @to_types;
1147 my $sub_to_types = '';
1148 for my $tt (@to_types) {
1149 my $k = $tt->[0];
1150 $k =~ s/[^\w\d]/_/g;
1151 $sub_to_types .= <<JSTT
1152 sub _to_json_$k { my \$self = \$_[0]; $tt->[1] }
1153 JSTT
1154 }
1155 my $to_json = <<TOJSON;
1156 sub TO_JSON {
1157 my \$self = shift;
1158 my \$ret;
1159 my \@columns = CORE::grep { not ref } \@_;
1160 my \@refs = CORE::grep { 'HASH' eq ref } \@_;
1161 if(\@columns) {
1162 \$ret = +{
1163 map {
1164 DBIx::Struct::error_message {
1165 result => 'SQLERR',
1166 message => "unknown column \$_ in table $table"
1167 } if not CORE::exists \$fields{\$_};
1168 my \$k = \$_;
1169 \$k =~ s/[^\\w\\d]/_/g;
1170 my \$m = "_to_json_\$k";
1171 \$_ => \$self->\$m
1172 } \@columns
1173 };
1174 } else {
1175 \$ret = +{
1176 $field_to_types
1177 };
1178 }
1179 if(\@refs) {
1180 \$ret = +{ %\$ret, map { %\$_ } \@refs };
1181 }
1182 return \$ret;
1183 }
1184 TOJSON
1185 return $sub_to_types . $to_json;
1186 }
1187  
1188 sub _field_type_from_name {
1189 my $type_name = $_[0];
1190 return 'string' if not defined $type_name;
1191 if ( $type_name =~ /int(\d+)?$/i
1192 || $type_name =~ /integer/i
1193 || $type_name =~ /bit$/
1194 || $type_name =~ /float|double|real|decimal|numeric/i)
1195 {
1196 return 'number';
1197 } elsif ($type_name =~ /json/i) {
1198 return 'json';
1199 } elsif ($type_name =~ /bool/i) {
1200 return 'boolean';
1201 } elsif ($type_name =~ /date/i && $type_name =~ /time/i) {
1202 return 'datetime';
1203 } elsif ($type_name =~ /date/i) {
1204 return 'date';
1205 } elsif ($type_name =~ /time/i) {
1206 return 'time';
1207 } else {
1208 return 'string';
1209 }
1210 }
1211  
1212 sub _schema_name {
1213 my $ncn = $_[0];
1214 if ($user_schema_namespace) {
1215 (my $uncn = $ncn) =~ s/^.*:://;
1216 no strict 'refs';
1217 eval {
1218 if (${"${user_schema_namespace}::${uncn}::"}{ISA}
1219 && "${user_schema_namespace}::${uncn}"->isa($ncn))
1220 {
1221 $ncn = "${user_schema_namespace}::${uncn}";
1222 }
1223 };
1224 }
1225 $ncn;
1226 }
1227  
1228 sub setup_row {
1229 my ($table, $ncn, $interface) = @_;
1230 error_message {
1231 result => 'SQLERR',
1232 message => "Unsupported driver $connector_driver",
1233 }
1234 unless exists $driver_pk_insert{$connector_driver};
1235 $ncn ||= make_name($table);
1236 return $ncn if _exists_row $ncn ;
1237 my %fields;
1238 my @fields;
1239 my @timestamp_fields;
1240 my @required;
1241 my @pkeys;
1242 my @fkeys;
1243 my @refkeys;
1244 my %json_fields;
1245 my $connector = DBIx::Struct::connect;
1246 my %field_types;
1247  
1248 if (not ref $table) {
1249 # means this is just one simple table
1250 $connector->run(
1251 sub {
1252 my $ssth = $_->prepare('select * from ' . $_->quote_identifier($table) . ' where 0 = 1');
1253 error_message {
1254 result => 'SQLERR',
1255 message => "Unknown table $table",
1256 }
1257 if not $ssth;
1258 $ssth->execute
1259 or error_message {
1260 result => 'SQLERR',
1261 message => "Probably unknown table $table: " . $_->errstr,
1262  
1263 };
1264 my $cih = $_->column_info(undef, undef, $table, undef);
1265 error_message {
1266 result => 'SQLERR',
1267 message => "Unknown table $table",
1268 }
1269 if not $cih;
1270 my $i = 0;
1271 while (my $chr = $cih->fetchrow_hashref) {
1272 $chr->{COLUMN_NAME} =~ s/"//g;
1273 $chr->{COLUMN_NAME} = lc $chr->{COLUMN_NAME};
1274 push @fields, $chr->{COLUMN_NAME};
1275 if ($chr->{TYPE_NAME} =~ /^time/i) {
1276 push @timestamp_fields, $chr->{COLUMN_NAME};
1277 }
1278 if ($chr->{TYPE_NAME} =~ /^json/i) {
1279 $json_fields{$chr->{COLUMN_NAME}} = undef;
1280 }
1281 $chr->{COLUMN_DEF} //= $chr->{mysql_is_auto_increment};
1282 if ($chr->{NULLABLE} == 0 && !defined($chr->{COLUMN_DEF})) {
1283 push @required, $chr->{COLUMN_NAME};
1284 }
1285 $fields{$chr->{COLUMN_NAME}} = $i++;
1286 $field_types{$chr->{COLUMN_NAME}} = _field_type_from_name($chr->{TYPE_NAME});
1287 }
1288 @pkeys = map {lc} $_->primary_key(undef, undef, $table);
1289 if (!@pkeys && @required) {
1290 my $ukh = $_->statistics_info(undef, undef, $table, 1, 1);
1291 my %req = map {$_ => undef} @required;
1292 my %pkeys;
1293 while (my $ukr = $ukh->fetchrow_hashref) {
1294 if (not exists $req{$ukr->{COLUMN_NAME}} or defined $ukr->{FILTER_CONDITION}) {
1295 $pkeys{lc $ukr->{INDEX_NAME}}{drop} = 1;
1296 } else {
1297 $pkeys{lc $ukr->{INDEX_NAME}}{fields}{lc $ukr->{COLUMN_NAME}} = undef;
1298 }
1299 }
1300 my @d = grep {exists $pkeys{$_}{drop}} keys %pkeys;
1301 delete $pkeys{$_} for @d;
1302 if (%pkeys) {
1303 my @spk = sort {scalar(keys %{$pkeys{$a}{fields}}) <=> scalar(keys %{$pkeys{$b}{fields}})}
1304 keys %pkeys;
1305 @pkeys = keys %{$pkeys{$spk[0]}{fields}};
1306 }
1307 }
1308 my $sth = $_->foreign_key_info(undef, undef, undef, undef, undef, $table);
1309 if ($sth) {
1310 @fkeys =
1311 grep {($_->{PKTABLE_NAME} || $_->{UK_TABLE_NAME}) && $_->{FK_COLUMN_NAME} !~ /[^a-z_0-9]/}
1312 map {
1313 $_->{FK_COLUMN_NAME} = $_->{FKCOLUMN_NAME}
1314 if $_->{FKCOLUMN_NAME};
1315 $_->{FK_TABLE_NAME} = $_->{FKTABLE_NAME} if $_->{FKTABLE_NAME};
1316 $_->{FK_TABLE_NAME} = lc $_->{FK_TABLE_NAME};
1317 $_->{FK_COLUMN_NAME} = lc $_->{FK_COLUMN_NAME};
1318 $_->{PKTABLE_NAME} ||= $_->{UK_TABLE_NAME};
1319 $_->{PKCOLUMN_NAME} ||= $_->{UK_COLUMN_NAME};
1320 $_->{PKTABLE_NAME} = lc $_->{PKTABLE_NAME} if $_->{PKTABLE_NAME};
1321 $_->{PKCOLUMN_NAME} = lc $_->{PKCOLUMN_NAME} if $_->{PKCOLUMN_NAME};
1322 $_
1323 } @{$sth->fetchall_arrayref({})};
1324 }
1325 $sth = $_->foreign_key_info(undef, undef, $table, undef, undef, undef);
1326 if ($sth) {
1327 @refkeys =
1328 grep {($_->{PKTABLE_NAME} || $_->{UK_TABLE_NAME}) && $_->{FK_COLUMN_NAME} !~ /[^a-z_0-9]/}
1329 map {
1330 $_->{FK_COLUMN_NAME} = $_->{FKCOLUMN_NAME}
1331 if $_->{FKCOLUMN_NAME};
1332 $_->{FK_TABLE_NAME} = $_->{FKTABLE_NAME} if $_->{FKTABLE_NAME};
1333 $_->{FK_TABLE_NAME} = lc $_->{FK_TABLE_NAME};
1334 $_->{FK_COLUMN_NAME} = lc $_->{FK_COLUMN_NAME};
1335 $_->{PKTABLE_NAME} = lc($_->{PKTABLE_NAME} || $_->{UK_TABLE_NAME});
1336 $_->{PKCOLUMN_NAME} = lc($_->{PKCOLUMN_NAME} || $_->{UK_COLUMN_NAME});
1337 $_
1338 } @{$sth->fetchall_arrayref({})};
1339 }
1340 }
1341 );
1342 } else {
1343  
1344 # means this is a query
1345 my %tnh = %{$table->{NAME_lc_hash}};
1346 for my $k (keys %tnh) {
1347 my $fk = $k;
1348 $fk =~ s/[^\w ].*$//;
1349 $fields{$fk} = $tnh{$k};
1350 }
1351 $connector->run(
1352 sub {
1353 for (my $cn = 0; $cn < @{$table->{NAME}}; ++$cn) {
1354 my $ti = $_->type_info($table->{TYPE}->[$cn]);
1355 my $field = lc $table->{NAME}->[$cn];
1356 $field =~ s/[^\w ].*$//;
1357 $field_types{$field} = _field_type_from_name($ti->{TYPE_NAME});
1358 push @timestamp_fields, $field
1359 if $ti->{TYPE_NAME} && $ti->{TYPE_NAME} =~ /^time/;
1360 $json_fields{$field} = undef
1361 if $ti->{TYPE_NAME} && $ti->{TYPE_NAME} =~ /^json/;
1362 }
1363 }
1364 );
1365 }
1366 my $field_types = join ", ", map {qq|"$_" => '$field_types{$_}'|} keys %field_types;
1367 my $fields = join ", ", map {qq|"$_" => $fields{$_}|} keys %fields;
1368 my $json_fields = join ", ", map {qq|"$_" => undef|} keys %json_fields;
1369 my $required = '';
1370 if (@required) {
1371 $required = join(", ", map {qq|"$_"|} @required);
1372 }
1373 my $timestamps = '';
1374 if (@timestamp_fields) {
1375 $timestamps = join(", ", map {qq|"$_"|} @timestamp_fields);
1376 } else {
1377 $timestamps = "()";
1378 }
1379 my %keywords = (
1380 new => undef,
1381 set => undef,
1382 data => undef,
1383 delete => undef,
1384 fetch => undef,
1385 update => undef,
1386 DESTROY => undef,
1387 filter_timestamp => undef,
1388 );
1389 my $pk_row_data = '';
1390 my $pk_returninig = '';
1391 my $pk_where = '';
1392 my $select_keys = '';
1393 my %pk_fields;
1394 if (@pkeys) {
1395 @pk_fields{@pkeys} = undef;
1396 $pk_row_data = join(", ", map {qq|\$self->[@{[_row_data]}]->[$fields{"$_"}]|} @pkeys);
1397 $pk_returninig = 'returning ' . join(", ", @pkeys);
1398 $pk_where = join(" and ", map {"$_ = ?"} @pkeys);
1399 my $sk_list = join(", ", map {qq|"$_"|} @pkeys);
1400 $select_keys = <<SK;
1401 sub selectKeys () {
1402 ($sk_list)
1403 }
1404 SK
1405 } else {
1406 if (@fields) {
1407 my $sk_list = join(", ", map {qq|"$_"|} @fields);
1408 $select_keys = <<SK;
1409 sub selectKeys () {
1410 ($sk_list)
1411 }
1412 SK
1413 } else {
1414 $select_keys = <<SK;
1415 sub selectKeys () { () }
1416 SK
1417 }
1418 }
1419 my $foreign_tables = '';
1420 my %foreign_tables;
1421 my %fkfuncs;
1422 for my $fk (@fkeys) {
1423 (my $pt = $fk->{PKTABLE_NAME} || $fk->{UK_TABLE_NAME}) =~ s/"//g;
1424 (my $pk = $fk->{PKCOLUMN_NAME} || $fk->{UK_COLUMN_NAME}) =~ s/"//g;
1425 my $fn = $pt;
1426 $fn =~ tr/_/-/;
1427 $fn =~ s/\b(\w)/\u$1/g;
1428 $fn =~ tr/-//d;
1429 $fk->{FK_COLUMN_NAME} =~ s/"//g;
1430 my $fn_suffix = $fk->{FK_COLUMN_NAME};
1431 $fn_suffix =~ s/^${pk}_*//i or $fn_suffix =~ s/_$pk(?=[^a-z]|$)//i or $fn_suffix =~ s/$pk(?=[^a-z]|$)//i;
1432 $fn_suffix =~ tr/_/-/;
1433 $fn_suffix =~ s/\b(\w)/\u$1/g;
1434 $fn_suffix =~ tr/-//d;
1435 $fn_suffix =~ s/$fn//;
1436 $fn .= $fn_suffix;
1437 $fkfuncs{$fn} = undef;
1438 $foreign_tables .= <<FKT;
1439 sub $fn {
1440 if(CORE::defined(\$_[0]->$fk->{FK_COLUMN_NAME})) {
1441 return DBIx::Struct::one_row("$pt", {$pk => \$_[0]->$fk->{FK_COLUMN_NAME}});
1442 } else {
1443 return
1444 }
1445 }
1446 FKT
1447 $foreign_tables{$pt} = [$fk->{FK_COLUMN_NAME} => $pk];
1448 }
1449 for my $ft (keys %foreign_tables) {
1450 my $ucft = ucfirst $ft;
1451 $fkfuncs{"foreignKey$ucft"} = undef;
1452 $foreign_tables .= <<FKT;
1453 sub foreignKey$ucft () {("$foreign_tables{$ft}[0]" => "$foreign_tables{$ft}[1]")}
1454 FKT
1455 }
1456 my $references_tables = '';
1457 for my $rk (@refkeys) {
1458 $rk->{FK_TABLE_NAME} =~ s/"//g;
1459 my $ft = $rk->{FK_TABLE_NAME};
1460 (my $fk = $rk->{FK_COLUMN_NAME}) =~ s/"//g;
1461 (my $pt = $rk->{PKTABLE_NAME} || $rk->{UK_TABLE_NAME}) =~ s/"//g;
1462 (my $pk = $rk->{PKCOLUMN_NAME} || $rk->{UK_COLUMN_NAME}) =~ s/"//g;
1463 if ($pk ne $fk) {
1464 my $fn = $fk;
1465 $fn =~ s/^${pk}_*//i or $fn =~ s/_$pk(?=[^a-z]|$)//i or $fn =~ s/$pk(?=[^a-z]|$)//i;
1466 $fn =~ s/$pt//i;
1467 $ft .= "_$fn" if $fn;
1468 }
1469 $ft =~ tr/_/-/;
1470 $ft =~ s/\b(\w)/\u$1/g;
1471 $ft =~ tr/-//d;
1472 $fkfuncs{"ref${ft}s"} = undef;
1473 $fkfuncs{"ref${ft}"} = undef;
1474 $references_tables .= <<RT;
1475 sub ref${ft}s {
1476 my (\$self, \@cond) = \@_;
1477 my \%cond;
1478 if(\@cond) {
1479 if(not CORE::ref \$cond[0]) {
1480 \%cond = \@cond;
1481 } else {
1482 \%cond = \%{\$cond[0]};
1483 }
1484 }
1485 \$cond{$fk} = \$self->$pk;
1486 return DBIx::Struct::all_rows("$rk->{FK_TABLE_NAME}", \\\%cond);
1487 }
1488 sub ref${ft} {
1489 my (\$self, \@cond) = \@_;
1490 my \%cond;
1491 if(\@cond) {
1492 if(not CORE::ref \$cond[0]) {
1493 \%cond = \@cond;
1494 } else {
1495 \%cond = \%{\$cond[0]};
1496 }
1497 }
1498 \$cond{$fk} = \$self->$pk;
1499 return DBIx::Struct::one_row("$rk->{FK_TABLE_NAME}", \\\%cond);
1500 }
1501 RT
1502 }
1503 my $accessors = <<ACC;
1504 sub markUpdated {
1505 \$_[0]->[@{[_row_updates]}]{\$_[1]} = undef if CORE::exists \$fields{\$_[1]};
1506 \$_[0];
1507 }
1508 ACC
1509 for my $k (keys %fields) {
1510 next if exists $keywords{$k};
1511 next if $k =~ /^\d/;
1512 $k =~ s/[^\w\d]/_/g;
1513 if (!exists $json_fields{$k}) {
1514 if (!exists($pk_fields{$k}) && (not ref $table)) {
1515 $accessors .= <<ACC;
1516 sub _$k {
1517 if(\@_ > 1) {
1518 \$_[0]->[@{[_row_data]}]->[$fields{$k}] = \$_[1];
1519 }
1520 \$_[0]->[@{[_row_data]}]->[$fields{$k}];
1521 }
1522 sub $k {
1523 if(\@_ > 1) {
1524 \$_[0]->[@{[_row_data]}]->[$fields{$k}] = \$_[1];
1525 \$_[0]->[@{[_row_updates]}]{"$k"} = undef;
1526 }
1527 \$_[0]->[@{[_row_data]}]->[$fields{$k}];
1528 }
1529 ACC
1530 } else {
1531 $accessors .= <<ACC;
1532 sub $k {
1533 \$_[0]->[@{[_row_data]}]->[$fields{$k}];
1534 }
1535 ACC
1536 }
1537 } else {
1538 if (!exists($pk_fields{$k}) && (not ref $table)) {
1539 $accessors .= <<ACC;
1540 sub _$k {
1541 if(\@_ > 1) {
1542 if(not CORE::ref \$_[1]) {
1543 \$_[0]->[@{[_row_data]}]->[$fields{$k}] = \$_[1];
1544 } else {
1545 \$_[0]->[@{[_row_data]}]->[$fields{$k}] = JSON::to_json(\$_[1]);
1546 }
1547 }
1548 if(not CORE::ref \$_[0]->[@{[_row_data]}]->[$fields{$k}]) {
1549 \$_[0]->[@{[_row_updates]}] = {} if not \$_[0]->[@{[_row_updates]}];
1550 \$_[0]->[@{[_row_data]}]->[$fields{$k}] =
1551 DBIx::Struct::JSON->factory(\\\$_[0]->[@{[_row_data]}]->[$fields{$k}], \$_[0]->[@{[_row_updates]}], "$k");
1552 }
1553 \$_[0]->[@{[_row_data]}]->[$fields{$k}]->accessor;
1554 }
1555 sub $k {
1556 if(\@_ > 1) {
1557 if(not CORE::ref \$_[1]) {
1558 \$_[0]->[@{[_row_data]}]->[$fields{$k}] = \$_[1];
1559 } else {
1560 \$_[0]->[@{[_row_data]}]->[$fields{$k}] = JSON::to_json(\$_[1]);
1561 }
1562 \$_[0]->[@{[_row_updates]}]{"$k"} = undef;
1563 }
1564 if(not CORE::ref \$_[0]->[@{[_row_data]}]->[$fields{$k}]) {
1565 \$_[0]->[@{[_row_updates]}] = {} if not \$_[0]->[@{[_row_updates]}];
1566 \$_[0]->[@{[_row_data]}]->[$fields{$k}] =
1567 DBIx::Struct::JSON->factory(\\\$_[0]->[@{[_row_data]}]->[$fields{$k}], \$_[0]->[@{[_row_updates]}], "$k");
1568 }
1569 \$_[0]->[@{[_row_data]}]->[$fields{$k}]->accessor;
1570 }
1571 ACC
1572 } else {
1573 $accessors .= <<ACC;
1574 sub $k {
1575 if(\$_[0]->[@{[_row_data]}]->[$fields{$k}] and not CORE::ref \$_[0]->[@{[_row_data]}]->[$fields{$k}]) {
1576 \$_[0]->[@{[_row_data]}]->[$fields{$k}] = JSON::from_json(\$_[0]->[@{[_row_data]}]->[$fields{$k}]);
1577 }
1578 \$_[0]->[@{[_row_data]}]->[$fields{$k}];
1579 }
1580 ACC
1581 }
1582 }
1583 }
1584 my $package_header = <<PHD;
1585 package ${ncn};
1586 use strict;
1587 use warnings;
1588 use Carp;
1589 use SQL::Abstract;
1590 use JSON;
1591 use Scalar::Util 'blessed';
1592 use vars qw(\$AUTOLOAD);
1593 our \%field_types = ($field_types);
1594 our \%fields = ($fields);
1595 our \%json_fields = ($json_fields);
1596 PHD
1597 if (not ref $table) {
1598 if (%fkfuncs) {
1599 my $fkfuncs = join ",", map {qq{"$_" => \\&${ncn}::$_}} keys %fkfuncs;
1600 $package_header .= <<PHD;
1601 our \%fkfuncs = ($fkfuncs);
1602 PHD
1603 } else {
1604 $package_header .= <<PHD;
1605 our \%fkfuncs = ();
1606 PHD
1607 }
1608 $package_header .= <<PHD;
1609 sub tableName () {"$table"}
1610 PHD
1611 } else {
1612 $package_header .= <<PHD;
1613 sub tableName () {"\\\$query\\\$$ncn"}
1614 PHD
1615 }
1616 my $new = make_object_new($table, $required, $pk_row_data, $pk_returninig);
1617 my $filter_timestamp = make_object_filter_timestamp($timestamps);
1618 my $set = make_object_set($table);
1619 my $data = make_object_data($table);
1620 my $update = make_object_update($table, $pk_where, $pk_row_data);
1621 my $delete = make_object_delete($table, $pk_where, $pk_row_data);
1622 my $fetch = make_object_fetch($table, $pk_where, $pk_row_data);
1623 my $autoload = make_object_autoload_find($table, $pk_where, $pk_row_data);
1624 my $to_json = make_object_to_json($table, \%field_types, \%fields);
1625 my $destroy;
1626  
1627 if (not ref $table) {
1628 $destroy = <<DESTROY;
1629 sub DESTROY {
1630 no warnings 'once';
1631 \$_[0]->update if \$DBIx::Struct::update_on_destroy;
1632 }
1633 DESTROY
1634 } else {
1635 $destroy = '';
1636 }
1637 my $eval_code = join "", $package_header, $select_keys, $new,
1638 $set, $data, $fetch, $autoload, $to_json, $filter_timestamp,
1639 $update, $delete, $destroy, $accessors, $foreign_tables, $references_tables;
1640  
1641 # print $eval_code;
1642 eval $eval_code;
1643 error_message {
1644 result => 'SQLERR',
1645 message => "Unknown error: $@",
1646 } if $@;
1647 if ($interface) {
1648 my $ifuncs = _parse_interface $interface;
1649 no strict 'refs';
1650 for my $f (keys %$ifuncs) {
1651 *{"${ncn}::$f"} = $ifuncs->{$f};
1652 }
1653 }
1654 '' =~ /()/;
1655 return $ncn;
1656 }
1657  
1658 my %cache_complex_query;
1659 my $json_canonical = JSON->new->canonical->convert_blessed;
1660  
1661 sub _cached_complex_query {
1662 my $key = $json_canonical->encode(\@_);
1663 my ($ret, $is_one_column);
1664 if (exists $cache_complex_query{$key}) {
1665 ($ret, $is_one_column) = @{$cache_complex_query{$key}};
1666 } else {
1667 ($ret, $is_one_column) = _build_complex_query(@_);
1668 $cache_complex_query{$key} = [($ret, $is_one_column)];
1669 }
1670 if (wantarray) {
1671 return ($ret, $is_one_column);
1672 } else {
1673 return $ret;
1674 }
1675 }
1676  
1677 sub _table_name() {0}
1678 sub _table_alias() {1}
1679 sub _table_join() {2}
1680 sub _table_join_on() {3}
1681  
1682 my $sql_abstract = SQL::Abstract->new;
1683 my $tblnum;
1684  
1685 sub _build_complex_query {
1686 my ($table, $query_bind, $where) = @_;
1687 return $table if not ref $table;
1688 my @from;
1689 my @columns;
1690 my @linked_list = (
1691 ref($table) eq 'ARRAY'
1692 ? @$table
1693 : error_message {
1694 result => 'SQLERR',
1695 message => "Unsupported type of query: " . ref($table)
1696 }
1697 );
1698 my ($conditions, $groupby, $having, $limit, $offset, $orderby);
1699 my $one_column = 0;
1700 my $distinct = 0;
1701 my $count = 0;
1702 my $all = 0;
1703  
1704 for (my $i = 0; $i < @linked_list; ++$i) {
1705 my $le = $linked_list[$i];
1706 if ('ARRAY' eq ref $le) {
1707 my $subfrom = _build_complex_query($le, $query_bind);
1708 my $ta = "t$tblnum";
1709 ++$tblnum;
1710 push @from, ["($subfrom)", $ta];
1711 next;
1712 }
1713 if (substr($le, 0, 1) ne '-') {
1714 my ($tn, $ta) = split ' ', $le;
1715 $ta = $tn if not $ta;
1716 my $ncn = make_name($tn);
1717 $ncn = _schema_name($ncn);
1718 error_message {
1719 result => 'SQLERR',
1720 message => "Unknown table $tn"
1721 }
1722 unless setup_row($tn, $ncn);
1723 push @from, [$tn, $ta];
1724 } else {
1725 my $cmd = substr($le, 1);
1726 if ($cmd eq 'left') {
1727 $from[-1][_table_join] = 'left join';
1728 } elsif ($cmd eq 'right') {
1729 $from[-1][_table_join] = 'right join';
1730 } elsif ($cmd eq 'join') {
1731 $from[-1][_table_join] = 'join';
1732 } elsif ($cmd eq 'on') {
1733 $from[-1][_table_join_on] = ["on", $linked_list[++$i]];
1734 } elsif ($cmd eq 'using') {
1735 $from[-1][_table_join_on] = ["using", $linked_list[++$i]];
1736 } elsif ($cmd eq 'as') {
1737 $from[-1][_table_alias] = $linked_list[++$i];
1738 } elsif ($cmd eq 'where') {
1739 $conditions = $linked_list[++$i];
1740 } elsif ($cmd eq 'group_by') {
1741 $groupby = $linked_list[++$i];
1742 } elsif ($cmd eq 'order_by') {
1743 $orderby = $linked_list[++$i];
1744 } elsif ($cmd eq 'having') {
1745 $having = $linked_list[++$i];
1746 } elsif ($cmd eq 'limit') {
1747 $limit = 0 + $linked_list[++$i];
1748 } elsif ($cmd eq 'offset') {
1749 $offset = 0 + $linked_list[++$i];
1750 } elsif ($cmd eq 'columns'
1751 || $cmd eq 'column'
1752 || $cmd eq 'distinct'
1753 || $cmd eq 'count'
1754 || $cmd eq 'all')
1755 {
1756 if ($cmd eq 'all') {
1757 $all = 1;
1758 }
1759 if ($cmd eq 'distinct') {
1760 $distinct = 1;
1761 }
1762 if ($cmd eq 'count') {
1763 $count = 1;
1764 }
1765 if ($i + 1 < @linked_list && substr($linked_list[$i + 1], 0, 1) ne '-') {
1766 my $cols = $linked_list[++$i];
1767 if ($cols && $cols !~ /^\d|^true$/) {
1768 if ('ARRAY' eq ref($cols)) {
1769 push @columns, @$cols;
1770 } else {
1771 push @columns, $cols;
1772 }
1773 } elsif (($cols =~ /^\d+$/ && $cols == 0) || $cols eq '') {
1774 $distinct = 0 if $cmd eq 'distinct';
1775 }
1776 }
1777 if ($cmd eq 'column') {
1778 ++$one_column;
1779 } else {
1780 $one_column += 2;
1781 }
1782  
1783 } else {
1784 error_message {
1785 result => 'SQLERR',
1786 message => "Unknown directive $le"
1787 };
1788 }
1789 }
1790 }
1791 error_message {
1792 result => 'SQLERR',
1793 message => "No table to build query on"
1794 } if !@from;
1795 for (my $idx = 1; $idx < @from; ++$idx) {
1796 next if $from[$idx][_table_join_on] or not $from[$idx - 1][_table_join];
1797 next if substr($from[$idx][_table_name], 0, 1) eq "(";
1798 my $cta = $from[$idx][_table_alias];
1799 my $cto = make_name($from[$idx][_table_name]);
1800 my $ucct = ucfirst $from[$idx][_table_name];
1801 my @join;
1802 for (my $i = $idx - 1; $i >= 0; --$i) {
1803 next if not $from[$i][_table_join];
1804 my $ptn = $from[$i][_table_name];
1805 next if substr($ptn, 0, 1) eq "(";
1806 my $ucfptn = ucfirst $ptn;
1807 if ($cto->can("foreignKey$ucfptn")) {
1808 my $fkfn = "foreignKey$ucfptn";
1809 my ($ctf, $ptk) = $cto->$fkfn;
1810 push @join, "$cta.$ctf = " . $from[$i][_table_alias] . ".$ptk";
1811 } else {
1812 my $ptno = make_name($ptn);
1813 if ($ptno->can("foreignKey$ucct")) {
1814 my $fkfn = "foreignKey$ucct";
1815 my ($ptf, $ctk) = $ptno->$fkfn;
1816 push @join, "$cta.$ctk = " . $from[$i][_table_alias] . ".$ptf";
1817 }
1818 }
1819 }
1820 $from[$idx][_table_join_on] = ["on", join(" and ", @join)];
1821 }
1822 my $from = '';
1823 @columns = ('*') if not @columns;
1824 @columns = map {('SCALAR' eq ref) ? DBIx::Struct::connect->dbh->quote_identifier($$_) : $_} @columns;
1825 my $joined = 0;
1826 for (my $idx = 0; $idx < @from; ++$idx) {
1827 if (not $joined) {
1828 $from .= " " . $from[$idx][_table_name];
1829 $from .= " " . $from[$idx][_table_alias] if $from[$idx][_table_alias] ne $from[$idx][_table_name];
1830 }
1831 if ($from[$idx][_table_join]) {
1832 my $nt = $from[$idx + 1];
1833 $from .= " " . $from[$idx][_table_join];
1834 $from .= " " . $nt->[_table_name];
1835 $from .= " " . $nt->[_table_alias] if $nt->[_table_alias] ne $nt->[_table_name];
1836 my $using_on = $nt->[_table_join_on][0];
1837 if ($using_on eq 'on' and ref $nt->[_table_join_on][1]) {
1838 my ($on_where, @on_bind) = $sql_abstract->where($nt->[_table_join_on][1]);
1839 $on_where =~ s/WHERE //;
1840 push @$query_bind, @on_bind;
1841 $from .= " $using_on(" . $on_where . ")";
1842 } else {
1843 $from .= " $using_on(" . $nt->[_table_join_on][1] . ")";
1844 }
1845 $joined = 1;
1846 } else {
1847 $from .= "," if $idx != $#from;
1848 $joined = 0;
1849 }
1850 }
1851 my $what = join(", ", @columns);
1852 if ($count) {
1853 $one_column = 1;
1854 if ($distinct) {
1855 $what = $from[0][_table_alias] . ".*" if $what eq '*';
1856 $what = "count(distinct $what)";
1857 } elsif ($all) {
1858 $what = $from[0][_table_alias] . ".*" if $what eq '*';
1859 $what = "count(all $what)";
1860 } else {
1861 $what = "count(*)";
1862 }
1863 } else {
1864 if ($distinct) {
1865 $what = "distinct $what";
1866 }
1867 }
1868 my $ret = "select $what from" . $from;
1869 if (not defined $where) {
1870 my $sql_grp = _parse_groupby($groupby);
1871 my $having_bind = [];
1872 if ($sql_grp && defined $having) {
1873 my $sql_having;
1874 ($sql_having, $having_bind) = _parse_having($having);
1875 $sql_grp .= " $sql_having";
1876 }
1877 if ($conditions) {
1878 my @where_bind;
1879 ($where, @where_bind) = $sql_abstract->where($conditions);
1880 push @$query_bind, @where_bind;
1881 } else {
1882 $where = '';
1883 }
1884 if (defined $sql_grp) {
1885 $where .= " $sql_grp";
1886 push @$query_bind, @$having_bind;
1887 }
1888 $where .= " limit $limit" if defined $limit;
1889 $where .= " offset $offset" if $offset;
1890 }
1891 $ret .= " $where" if $where;
1892 if (wantarray) {
1893 return ($ret, $one_column == 1);
1894 } else {
1895 return $ret;
1896 }
1897 }
1898  
1899 sub _parse_groupby {
1900 my $groupby = $_[0];
1901 my $sql_grp;
1902 if (defined $groupby) {
1903 $sql_grp = "GROUP BY ";
1904 my @groupby =
1905 map {/^\d+$/ ? $_ : /^[a-z][\w ]*$/i ? "\"$_\"" : "$_"} (ref($groupby) ? @$groupby : ($groupby));
1906 $sql_grp .= join(", ", @groupby);
1907 }
1908 $sql_grp;
1909 }
1910  
1911 sub _parse_having {
1912 my $having = $_[0];
1913 my $sql_having;
1914 my @having_bind;
1915 if (defined $having) {
1916 ($sql_having, @having_bind) = $sql_abstract->where($having);
1917 $sql_having =~ s/\bWHERE\b/HAVING/;
1918 }
1919 ($sql_having, \@having_bind);
1920 }
1921  
1922 sub execute {
1923 my ($groupby, $having, $up_conditions, $up_order, $up_limit, $up_offset, $up_interface, $sql, $dry_run);
1924 my $distinct = '';
1925 for (my $i = 2; $i < @_; ++$i) {
1926 next unless defined $_[$i] and not ref $_[$i];
1927 if ($_[$i] eq '-group_by') {
1928 (undef, $groupby) = splice @_, $i, 2;
1929 --$i;
1930 } elsif ($_[$i] eq '-distinct') {
1931 $distinct = ' distinct';
1932 splice @_, $i, 1;
1933 --$i;
1934 } elsif ($_[$i] eq '-having') {
1935 (undef, $having) = splice @_, $i, 2;
1936 --$i;
1937 } elsif ($_[$i] eq '-order_by') {
1938 (undef, $up_order) = splice @_, $i, 2;
1939 --$i;
1940 } elsif ($_[$i] eq '-where') {
1941 (undef, $up_conditions) = splice @_, $i, 2;
1942 --$i;
1943 } elsif ($_[$i] eq '-limit') {
1944 (undef, $up_limit) = splice @_, $i, 2;
1945 --$i;
1946 } elsif ($_[$i] eq '-interface') {
1947 (undef, $up_interface) = splice @_, $i, 2;
1948 --$i;
1949 } elsif ($_[$i] eq '-offset') {
1950 (undef, $up_offset) = splice @_, $i, 2;
1951 --$i;
1952 } elsif ($_[$i] eq '-sql') {
1953 (undef, $sql) = splice @_, $i, 2;
1954 --$i;
1955 } elsif ($_[$i] eq '-dry_run') {
1956 (undef, $dry_run) = splice @_, $i, 2;
1957 --$i;
1958 } elsif (substr($_[$i], 0, 1) eq '-') {
1959 error_message {
1960 result => 'SQLERR',
1961 message => "Unknown directive $_[$i]"
1962 };
1963 }
1964 }
1965 $tblnum = 1;
1966 my $sql_grp = _parse_groupby($groupby);
1967 my $having_bind = [];
1968 if ($sql_grp && defined $having) {
1969 my $sql_having;
1970 ($sql_having, $having_bind) = _parse_having($having);
1971 $sql_grp .= " $sql_having";
1972 }
1973 my ($code, $table, $conditions, $order, $limit, $offset) = @_;
1974 my $have_conditions = @_ > 2;
1975 $conditions //= $up_conditions;
1976 $order //= $up_order;
1977 $limit //= $up_limit;
1978 $offset //= $up_offset;
1979 my $where;
1980 my $need_where = 0;
1981 my @where_bind;
1982 my $simple_table = (not ref $table and index($table, " ") == -1);
1983 my $ncn;
1984  
1985 if ($simple_table) {
1986 $ncn = make_name($table);
1987 $ncn = _schema_name($ncn);
1988 setup_row($table, $ncn);
1989 if ($have_conditions and not ref $conditions) {
1990 my $id = ($ncn->selectKeys())[0]
1991 or error_message {
1992 result => 'SQLERR',
1993 message => "unknown primary key",
1994 query => "select * from $table",
1995 };
1996 if (defined $conditions) {
1997 $where = "where $id = ?";
1998 @where_bind = ($conditions);
1999 } else {
2000 $where = "where $id is null";
2001 }
2002 } else {
2003 $need_where = 1;
2004 }
2005 } else {
2006 $need_where = 1;
2007 }
2008 if ($need_where) {
2009 ($where, @where_bind) = $sql_abstract->where($conditions);
2010 }
2011 if (defined $sql_grp) {
2012 $where .= " $sql_grp";
2013 push @where_bind, @$having_bind;
2014 }
2015 if ($order) {
2016 my ($order_sql, @order_bind) = $sql_abstract->where(undef, $order);
2017 $where .= " $order_sql";
2018 push @where_bind, @order_bind;
2019 }
2020 if (defined($limit)) {
2021 $limit += 0;
2022 $where .= " limit $limit";
2023 }
2024 if (defined($offset)) {
2025 $offset += 0;
2026 $where .= " offset $offset" if $offset;
2027 }
2028 my $query;
2029 my @query_bind;
2030 my $one_column = 0;
2031 if ($simple_table) {
2032 $query = qq{select$distinct * from $table $where};
2033 } else {
2034 if (not ref $table) {
2035 $query = "$table $where";
2036 } else {
2037 ($query, $one_column) = _cached_complex_query($table, \@query_bind, $where);
2038 }
2039 $ncn = make_name($query);
2040 }
2041 if ($sql) {
2042 if ('CODE' eq ref $sql) {
2043 $sql->($query, \@where_bind);
2044 } elsif ('SCALAR' eq ref $sql) {
2045 $$sql = $query;
2046 }
2047 }
2048 return if $dry_run;
2049 '' =~ /()/;
2050 my $sth;
2051 return DBIx::Struct::connect->run(
2052 sub {
2053 $sth = $_->prepare($query)
2054 or error_message {
2055 result => 'SQLERR',
2056 message => $_->errstr,
2057 query => $query,
2058 };
2059 $sth->execute(@query_bind, @where_bind)
2060 or error_message {
2061 result => 'SQLERR',
2062 message => $_->errstr,
2063 query => $query,
2064 where_bind => Dumper(\@where_bind),
2065 query_bind => Dumper(\@query_bind),
2066 conditions => Dumper($conditions),
2067 };
2068 setup_row($sth, $ncn, $up_interface);
2069 return $code->($sth, $ncn, $one_column);
2070 }
2071 );
2072 }
2073  
2074 sub one_row {
2075 return execute(
2076 sub {
2077 my ($sth, $ncn, $one_column) = @_;
2078 my $data = $sth->fetchrow_arrayref;
2079 $sth->finish;
2080 return if not $data;
2081 if ($one_column) {
2082 #<<<
2083 # json type is not working yet here
2084 # no strict 'refs';
2085 # my @f = %{$ncn . "::field_types"};
2086 # if ($f[1] eq 'json') {
2087 # return (defined($data->[0]) ? from_json($data->[0]) : undef);
2088 # } else {
2089 return $data->[0];
2090 #>>> }
2091 }
2092 return $ncn->new([@$data]);
2093 },
2094 @_
2095 );
2096 }
2097  
2098 sub all_rows {
2099 my $mapfunc;
2100 for (my $i = 0; $i < @_; ++$i) {
2101 if (ref($_[$i]) eq 'CODE') {
2102 $mapfunc = splice @_, $i, 1;
2103 last;
2104 }
2105 }
2106 return execute(
2107 sub {
2108 my ($sth, $ncn, $one_column) = @_;
2109 my @rows;
2110 my $row;
2111 if ($mapfunc) {
2112 while ($row = $sth->fetch) {
2113 local $_ = $ncn->new([@$row]);
2114 push @rows, $mapfunc->();
2115 }
2116 } else {
2117 if ($one_column) {
2118 #<<<
2119 # json type is not working yet here
2120 # no strict 'refs';
2121 # my @f = %{$ncn . "::field_types"};
2122 # if ($f[1] eq 'json') {
2123 # push @rows, (defined($row->[0]) ? from_json($row->[0]) : undef) while ($row = $sth->fetch);
2124 # } else {
2125 push @rows, $row->[0] while ($row = $sth->fetch);
2126 # }
2127 #>>>
2128 } else {
2129 push @rows, $ncn->new([@$row]) while ($row = $sth->fetch);
2130 }
2131 }
2132 return \@rows;
2133 },
2134 @_
2135 );
2136 }
2137  
2138 sub for_rows {
2139 my $itemfunc;
2140 for (my $i = 0; $i < @_; ++$i) {
2141 if (ref($_[$i]) eq 'CODE') {
2142 $itemfunc = splice @_, $i, 1;
2143 last;
2144 }
2145 }
2146 error_message {
2147 result => 'SQLERR',
2148 message => "Item function is required",
2149 query => "(not parsed)",
2150 where_bind => "(not parsed)",
2151 query_bind => "(not parsed)",
2152 conditions => "(not parsed)",
2153 }
2154 if not $itemfunc;
2155 return execute(
2156 sub {
2157 my ($sth, $ncn) = @_;
2158 my $rows = 0;
2159 my $row;
2160 my $dbh = $_;
2161 local $dbh->{mysql_use_result} = 1 if $connector_driver eq 'mysql';
2162 local $_;
2163 while ($row = $sth->fetch) {
2164 ++$rows;
2165 $_ = $ncn->new([@$row]);
2166 last if not $itemfunc->();
2167 }
2168 return $rows;
2169 },
2170 @_
2171 );
2172 }
2173  
2174 sub new_row {
2175 my ($table, @data) = @_;
2176 my $simple_table = (index($table, " ") == -1);
2177 error_message {
2178 result => 'SQLERR',
2179 message => "insert row can't work for queries"
2180 }
2181 unless $simple_table;
2182 my $ncn = make_name($table);
2183 $ncn = _schema_name($ncn);
2184 $ncn = setup_row($table, $ncn);
2185 return $ncn->new(@data);
2186 }
2187  
2188 1;