DO/FS/Glue.pm untested

filter: Statementstmt 0.0% 0 / 992 Branchbran 0.0% 0 / 396 Conditioncond 0.0% 0 / 492 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 66 Podpod 0.0% 0 / 59 totaltotal 0.0% 0 / 2005 SCAR 105.9
CC
199
Cov
0%
_build_search_query
2756.0
_build_search_clause
380.0
_list_search
342.0
CRAP 39800.0
1 =head1 NAME
2  
3 XAO::DO::FS::Glue - glue that connects database with classes in XAO::FS
4  
5 =head1 SYNOPSIS
6  
7 my $odb=XAO::Objects->new(objname => 'FS::Glue',
8 dbh => $dbh);
9 my $global=$odb->fetch('/');
10  
11 =head1 DESCRIPTION
12  
13 A reference to the Glue object is what holds together all List and Hash
14 objects in your objects database. This is the only place in API where
15 you pass database handler.
16  
17 It is quite possible that if XAO::OS would ever be implemented on
18 top of some non-relational database layer the syntax of Glue's new()
19 methow would change too.
20  
21 In current implementation Glue also serves as a base class for both List
22 and Hash classes and it provides some common methods. You should avoid
23 calling them on Glue object (think of them as pure virtual methods in OO
24 sense) and in fact you should avoid using glue object for anything but
25 connecting to a database and retrieveing root node reference.
26  
27 For XAO::Web case initialization of Glue and retrieveing of Global
28 object is hidden from developer.
29  
30 In theory Glue object should be split into ListGlue and HashGlue because
31 now it mixes methods that know data structure inside List and Glue and
32 this is not a Right Thing. But on the other side it is easier to keep
33 everything that knows about SQL in just one place instead of spreading
34 it over a couple of classes. So, do not ever rely on the fact that let's
35 say _list_store_object is in Glue - it might move to some class of its
36 own later.
37  
38 =head1 PUBLIC METHODS
39  
40 =over
41  
42 =cut
43  
44 ###############################################################################
45 package XAO::DO::FS::Glue;
46 use strict;
47 use Encode;
48 use XAO::Utils;
49 use XAO::Objects;
50  
51 use base XAO::Objects->load(objname => 'Atom');
52  
53 use vars qw($VERSION);
54 $VERSION=(0+sprintf('%u.%03u',(q$Id: Glue.pm,v 2.21 2008/12/10 05:05:17 am Exp $ =~ /\s(\d+)\.(\d+)\s/))) || die "Bad VERSION";
55  
56 ###############################################################################
57  
58 =item new ($%)
59  
60 Creates new Glue object and connects it to a database. There should be
61 exactly one Glue object per process/per database.
62  
63 It is highly recommended that you create a Glue object once somewhere
64 at the top of your script, then retrieve root node object from it and
65 keep reference for the lifetime of your script. The same applies for web
66 scripts, especially under mod_perl - it is recommended to keep root node
67 reference between sessions.
68  
69 The only required argument is B<dsn> (database source name). It has
70 special format - first part is `OS', then driver name, then database
71 name and optionally port number, hostname and so on. It is recommended
72 to pass user name and password too. Example:
73  
74 my $odb=XAO::Objects->new(
75 objname => 'FS::Glue',
76 dsn => 'OS:MySQL_DBI:ostest;dbi_driver=MariaDB;hostname=dbserver'
77 user => 'user',
78 password => 'pAsSwOrD',
79 );
80  
81 Most database options are passed to the implementation driver as is
82 (e.g. hostname, etc), but some are special:
83  
84 * dbi_driver - mysql (for DBD::mysql) or MariaDB (for DBD::MariaDB)
85 * table_type - MyISAM or InnoDB
86  
87 In order to get objects connected to that database you should call new
88 on $odb with the following syntax:
89  
90 my $neworder=$odb->new(objname => 'Data::Order');
91  
92 =cut
93  
94 sub new ($%) {
95 my $proto=shift;
96 my $args=get_args(\@_);
97 my $class=ref($proto) || $proto;
98  
99 ##
100 # If we've got Glue reference in $proto then pass that to
101 # XAO::Objects to load.
102 #
103 if(ref($proto) &&
104 $proto->isa('XAO::DO::FS::Glue') &&
105 $$proto->{'objname'} eq 'FS::Glue') {
106 my %a=%{$args};
107 $a{'glue'}=$proto;
108 return XAO::Objects->new(\%a);
109 }
110  
111 ##
112 # Our object
113 #
114 my $hash={ class => $class };
115 my $self=bless \$hash, $class;
116  
117 ##
118 # We must always have objname
119 #
120 my $objname=$args->{'objname'};
121 $objname || $self->throw("new - must be loaded by XAO::Objects");
122 $$self->{'objname'}=$objname;
123  
124 ##
125 # When new object is created by get()'ing it we will have 'uri'
126 # parameter passed.
127 #
128 $$self->{'uri'}=$args->{'uri'};
129  
130 ##
131 # Checking if this is System::Glue or something else that is based
132 # on it.
133 #
134 if($objname eq 'FS::Glue') {
135  
136 my $user=$args->{'user'};
137 my $password=$args->{'password'};
138  
139 my $dsn=$args->{'dsn'};
140 $dsn || $self->throw("new - required parameter missed 'dsn'");
141 $dsn=~/^OS:(\w+):\w+(;.*)?$/ || $self->throw("new - bad format of 'dsn' ($dsn)");
142 my $drvname='FS::Glue::' . $1;
143  
144 my $driver=XAO::Objects->new(
145 objname => $drvname,
146 dsn => $dsn,
147 user => $user,
148 password => $password,
149 );
150 $$self->{'driver'}=$driver;
151  
152 # Checking if this is a request to trash everything and produce a
153 # squeky clean new database.
154 #
155 my $empty_database;
156 if($args->{'empty_database'}) {
157 $args->{'empty_database'} eq 'confirm' ||
158 throw $self "new - request for 'empty_database' is not 'confirm'ed";
159  
160 $driver->initialize_database;
161 $empty_database=1;
162 }
163  
164 # Loading data layout. From 1.07 onward by default it does not
165 # check table consistency as this is a slow operation that can
166 # also be dangerous if multiple requests were to be made at the
167 # same time and fixes/upgrades were run in parallel.
168 #
169 # 'check_consistency' argument is needed to get checks done.
170 # If the database is just created 'check_consistency' is
171 # assumed, to help in test cases
172 #
173 $driver->consistency_check_set(
174 $empty_database ||
175 $args->{'check_consistency'} || $args->{'consistency_check'}
176 );
177 $$self->{'classes'}=$driver->load_structure;
178 }
179  
180 else {
181  
182 # We must have glue object somewhere - either explicitly given
183 # or from an object being cloned..
184 #
185 my $glue=ref($proto) ? $proto : $args->{'glue'};
186 $glue || throw $self "new - required parameter missed 'glue'";
187 $$self->{'glue'}=$glue;
188 }
189  
190 ##
191 # Returning resulting object
192 #
193 $self;
194 }
195  
196 ###############################################################################
197  
198 sub DESTROY () {
199 my $self=shift;
200  
201 if($$self->{'driver'}) {
202 if($self->transact_active) {
203 eprint "Rolling back uncommitted transaction";
204 $self->transact_rollback;
205 }
206  
207 $self->disconnect();
208 }
209 }
210  
211 ###############################################################################
212  
213 =item collection (%)
214  
215 Creates a collection object based on parameters given. Collection is
216 similar to List object -- it contains a list of objects having something
217 in common. Collection is a read-only object, you can use it only to
218 retrieve objects, not to store objects in it.
219  
220 Currently the only type of collection supported is the list of all
221 objects of the same class. This can be very useful for searching and
222 analyzing tasks.
223  
224 Example:
225  
226 my $orders=$odb->collection(class => 'Data::Order');
227  
228 my $sr=$orders->search('date_placed', ge, 12345678);
229  
230 my $sum=0;
231 foreach my $id (@$sr) {
232 $sum+=$orders->get($id)->get('order_total');
233 }
234  
235 =cut
236  
237 sub collection ($%) {
238 my $self=shift;
239 my $args=merge_refs(get_args(\@_), {
240 objname => 'FS::Collection',
241 glue => $self,
242 });
243 XAO::Objects->new($args);
244 }
245  
246 ###############################################################################
247  
248 =item container_key ()
249  
250 Works for Hash'es and List's -- returns the name of current object in
251 upper level container.
252  
253 =cut
254  
255 sub container_key ($) {
256 my $self=shift;
257 $$self->{'key_value'};
258 }
259  
260 ###############################################################################
261  
262 =item contents ()
263  
264 Alias for values() method.
265  
266 =cut
267  
268 sub contents ($) {
269 shift->values();
270 }
271  
272 ###############################################################################
273  
274 =item destroy ()
275  
276 Rough equivalent of:
277  
278 foreach my $key ($object->keys()) {
279 $object->delete($key);
280 }
281  
282 =cut
283  
284 sub destroy ($;$) {
285 my ($self,$lists_only)=@_;
286 foreach my $key ($self->keys) {
287 my $type=$self->describe($key)->{'type'};
288 next if $type eq 'key';
289 next if $lists_only && $type ne 'list';
290 $self->delete($key);
291 }
292 }
293  
294 ###############################################################################
295  
296 =item disconnect ()
297  
298 If you need to explicitly disconnect from the database and you do not want to
299 trust perl's garbage collector to do that call this method.
300  
301 After you call disconnect() nearly all methods on $odb handler will throw
302 errors and there is currently no way to re-connect existing handler to the
303 database.
304  
305 =cut
306  
307 sub disconnect () {
308 my $self=shift;
309 $$self->{'glue'} &&
310 throw $self "disconnect - only makes sense on database handler (did you mean 'detach'?)";
311 if($$self->{'driver'}) {
312 $$self->{'driver'}->disconnect();
313 delete $$self->{'driver'};
314 }
315 }
316  
317 ###############################################################################
318  
319 =item fetch ($)
320  
321 Returns an object or a property referred to by the given URI. A URI must
322 always start from / currently, relative URIs are not supported.
323  
324 This method is in fact the only way to get a reference to the root
325 object (formerly /Global):
326  
327 my $global=$odb->fetch('/');
328  
329 B<Experimental extension>: The following full forms can also be used:
330  
331 xaofs://uri/Pages/P123/Hits/H234/name
332 xaofs://collection/class/Data::Page/5678/Hits/H234/name
333  
334 Both should yield the same result providing that 5678 is a Collection
335 (see L<XAO::DS::FS::Collection>) code for P123.
336  
337 =cut
338  
339 sub fetch ($$) {
340 my $self=shift;
341 my $path=shift;
342  
343 $path =~ /^(xaofs:\/\/(.*?))?(\/.*)$/;
344 my $type;
345 my $full_path;
346 if($1) {
347 $type=$2;
348 $full_path=$path;
349 $path=$3;
350 }
351  
352 if(!defined $type || $type eq 'uri') {
353  
354 ##
355 # Normalizing and checking path
356 #
357 $path=$self->normalize_path($path);
358 substr($path,0,1) eq '/' || throw $self "fetch - bad path ($path)";
359  
360 ##
361 # Going through the path and retrieving every element. Could be a
362 # little bit more optimal, but not much..
363 #
364 my $node=XAO::Objects->new(objname => 'FS::Global',
365 glue => $self,
366 uri => '/');
367 foreach my $nodename (split(/\/+/,$path)) {
368 next unless length($nodename);
369 if(ref($node)) {
370 $node=$node->get($nodename);
371 } else {
372 return undef;
373 }
374 }
375  
376 return $node;
377 }
378 elsif($type eq 'collection') {
379 $path =~ qr|^/class/(\w+(::\w+)*)(/.*)?$| ||
380 throw $self "fetch - wrong collection uri ($full_path)";
381  
382 my $class=$1;
383 $path=$3;
384  
385 my $node=$self->collection(class => $class);
386 if($path && $path ne '/') {
387 foreach my $nodename (split(/\/+/,$path)) {
388 next unless length($nodename);
389 if(ref($node)) {
390 $node=$node->get($nodename);
391 } else {
392 return undef;
393 }
394 }
395 }
396  
397 return $node;
398 }
399 }
400  
401 ###############################################################################
402  
403 =item glue ()
404  
405 Returns reference to the Glue object the current object is received from.
406  
407 =cut
408  
409 sub glue ($) {
410 my $self=shift;
411 return $self->_glue;
412 }
413  
414 ###############################################################################
415  
416 =item objname ()
417  
418 Returns relative object name that XAO::Objects would accept.
419  
420 =cut
421  
422 sub objname ($) {
423 my $self=shift;
424 $$self->{'objname'} || throw $self "objname - must have an objname";
425 }
426  
427 ###############################################################################
428  
429 =item objtype ()
430  
431 Always returns 'Glue' string for object database handler object.
432  
433 =cut
434  
435 sub objtype ($) {
436 'Glue';
437 }
438  
439 ###############################################################################
440  
441 =item reset ()
442  
443 Useful to bring glue to a usable state after some unknown software used
444 it. If the connection went down it is reconnected. If there is an active
445 transaction -- it will be rolled back, if there are locked tables --
446 they will be unlocked.
447  
448 =cut
449  
450 sub reset ($) {
451 my $self=shift;
452  
453 $self->_driver->reset;
454  
455 if($self->transact_active) {
456 $self->transact_rollback;
457 }
458 }
459  
460 ###############################################################################
461  
462 =item scan (@)
463  
464 A wrapper for search() method that makes it easier to search in large
465 collections of data.
466  
467 See L<XAO::DO::FS::List> for details.
468  
469 =cut
470  
471 sub scan ($@) {
472 my $self=shift;
473 my $args=get_args(\@_);
474  
475 my $block_size=$args->{'block_size'} || throw $self "- no block_size";
476  
477 $args->{'search_options'} || throw $self "- no search_options";
478  
479 my $options=merge_refs($args->{'search_options'});
480  
481 $options->{'orderby'} || throw $self "- must have an orderby in search_options";
482  
483 my $offset_global=$args->{'offset'} || $args->{'search_options'}->{'offset'} || 0;
484 my $limit_global=$args->{'limit'} || $args->{'search_options'}->{'limit'} || 0;
485  
486 $args->{'call_before'} &&
487 $args->{'call_before'}->($self,$args);
488  
489 my $offset=$offset_global;
490 while(1) {
491 $options->{'offset'}=$offset;
492 $options->{'limit'}=(!$limit_global || $offset-$offset_global+$block_size < $limit_global)
493 ? $block_size
494 : $limit_global-($offset-$offset_global);
495  
496 my $sr=$self->search(
497 $args->{'search_query'} || [ ],
498 $options,
499 );
500  
501 last unless @$sr;
502  
503 ### dprint Dumper($sr);
504 ### dprint Dumper($options);
505  
506 my $margs=merge_refs($args,{
507 search_options => $options,
508 });
509  
510 if($args->{'call_block'}) {
511 $args->{'call_block'}->(
512 $self,
513 $margs,
514 $sr,
515 $options->{'offset'},
516 $options->{'limit'},
517 );
518 }
519  
520 if($args->{'call_row'}) {
521 for(my $i=0; $i<@$sr; ++$i) {
522 $args->{'call_row'}->(
523 $self,
524 $margs,
525 $sr->[$i],
526 $i+$options->{'offset'},
527 );
528 }
529 }
530  
531 last if scalar(@$sr)<$options->{'limit'};
532  
533 last if $limit_global && $options->{'offset'}+scalar(@$sr) >= $limit_global;
534  
535 $offset+=scalar(@$sr);
536 }
537  
538 $args->{'call_after'} &&
539 $args->{'call_after'}->($self,$args);
540 }
541  
542 ###############################################################################
543  
544 =item transact_active ()
545  
546 Checks if a there is an active transaction at the moment. Can be used to
547 avoid starting another one as transactions can't be nested.
548  
549 Example:
550  
551 $odb->transact_begin unless $odb->transact_active;
552  
553 =cut
554  
555 sub transact_active ($) {
556 my $self=shift;
557 return $self->_driver->tr_ext_active;
558 }
559  
560 ###############################################################################
561  
562 =item transact_begin ()
563  
564 Begins new transaction. If transactions are not supported by the
565 underlying driver it does nothing, see transact_can() method.
566  
567 If there is already an active transaction an error will be thrown and no
568 new transaction will be started. Transactions can't be nested and
569 each transact_begin() must be matched by a transact_commit() or
570 transact_rollback().
571  
572 Automatic transact_rollback() is performed on destroying Glue or
573 disconnecting. It is not done automatically on thrown errors, but if an
574 error is never caught the transaction will be rolled back automatically
575 at the program termination stage when Glue is destroyed. Beware of
576 global error catching blocks and do proper cleanup if you use them.
577  
578 Example:
579  
580 $odb->transact_begin;
581 try {
582 $order->put(order_total => 123.45);
583 $order->get('Products')->put($product_obj);
584 $odb->transact_commit;
585 }
586 otherwise {
587 my $e=shift;
588 $odb->transact_rollback;
589 $e->throw;
590 };
591  
592 =cut
593  
594 sub transact_begin ($) {
595 my $self=shift;
596 return $self->_driver->tr_ext_begin;
597 }
598  
599 ###############################################################################
600  
601 =item transact_can ()
602  
603 Returns boolean true if underlying driver supports transactions of false
604 otherwise.
605  
606 Example:
607  
608 $odb->transact_can ||
609 throw XAO::E::Sample "Transactions are not supported";
610  
611 =cut
612  
613 sub transact_can ($) {
614 my $self=shift;
615 return $self->_driver->tr_ext_can;
616 }
617  
618 ###############################################################################
619  
620 =item transact_commit ()
621  
622 Commits changes made during the current transaction. If there is no
623 current transaction it will throw an error assuming that there was an
624 out-of-sync transact_commit() or transact_rollback() somewhere before.
625  
626 If transactions are not supported the method will do nothing.
627  
628 =cut
629  
630 sub transact_commit ($) {
631 my $self=shift;
632 return $self->_driver->tr_ext_commit;
633 }
634  
635 ###############################################################################
636  
637 =item transact_rollback ()
638  
639 Rolls back (cancels) changes made during the current transaction. If
640 there is no current transaction it will throw an error assuming that
641 there was an out-of-sync transact_commit() or transact_rollback()
642 somewhere before.
643  
644 If transactions are not supported the method will do nothing.
645  
646 =cut
647  
648 sub transact_rollback ($) {
649 my $self=shift;
650 return $self->_driver->tr_ext_rollback;
651 }
652  
653 ###############################################################################
654  
655 =item unlink ($)
656  
657 Alias to delete(), which is defined in derived classes - List and Hash.
658  
659 =cut
660  
661 sub unlink ($$) {
662 my $self=shift;
663 $self->delete(shift);
664 }
665  
666 ###############################################################################
667  
668 =item upper_class ($)
669  
670 Returns the upper class name for the given class or undef for
671 FS::Global. Will skip lists and return class name of hashes only.
672  
673 Will throw an error if there is no description for the given class name.
674  
675 Example:
676  
677 my $base=$odb->upper_class('Data::Order');
678  
679 =cut
680  
681 sub upper_class ($$) {
682 my $self=shift;
683 my $class_name=shift || 'FS::Global';
684  
685 return undef if $class_name eq 'FS::Global';
686  
687 my $cdesc=$$self->{'classes'}->{$class_name} ||
688 $self->throw("upper_class - nothing known about '$class_name'");
689  
690 foreach my $fd (values %{$cdesc->{'fields'}}) {
691 return $fd->{'refers'} if $fd->{'type'} eq 'connector';
692 }
693 return 'FS::Global';
694 }
695  
696 ###############################################################################
697  
698 =item values ()
699  
700 Returns list of values for either Hash or List.
701  
702 =cut
703  
704 sub values ($) {
705 my $self=shift;
706 my @k=$self->keys;
707 my $num=scalar(@k);
708 eprint ref($self)."::values - more then 100 keys ($num), consider scanning instead"
709 if $num > 100 && $self->objtype eq 'List';
710 return $self->get(@k);
711 }
712  
713 ###############################################################################
714  
715 =item uri ()
716  
717 Returns complete URI to either the object itself (if no argument is
718 given) or to a property with the given name.
719  
720 That URI can then be used to retrieve a property or object using
721 $odb->fetch($uri). Be aware, that fetch() is relatively slow method and
722 should not be abused.
723  
724 Works for both List and Hash objects. For just created object will
725 return `undef'.
726  
727 =cut
728  
729 sub uri ($;$) {
730 my $self=shift;
731 my $name=shift;
732  
733 my $uri=$$self->{'uri'};
734 return undef unless $uri;
735  
736 return $uri unless defined($name);
737  
738 return $uri eq '/' ? $uri . $name : $uri . '/' . $name;
739 }
740  
741 ###############################################################################
742  
743 =back
744  
745 =head1
746  
747 Most of the methods of Glue would be considered "protected" in more
748 restrictive OO languages. Perl does not impose such limitations and it
749 is up to a developer's conscience to avoid using them.
750  
751 The following list is here only for reference. Names, arguments and
752 functions performed may change from version to version. You should
753 B<never use the following methods in your applications>.
754  
755 =over
756  
757 =cut
758  
759 ###############################################################################
760  
761 =item _maxlength_change (%)
762  
763 Upgrades 'maxlength' information for the given text fields both in
764 memory structures AND in the database tables.
765  
766 =cut
767  
768 sub _maxlength_change ($%) {
769 my $self=shift;
770  
771 my $flist=get_args(\@_);
772  
773 my $desc=$self->_class_description;
774 my $table=$desc->{'table'};
775  
776 my $driver=$self->_driver;
777 my $csh=$driver->maxlength_change_prepare($table);
778  
779 foreach my $name (keys %$flist) {
780 my $fdesc=$desc->{'fields'}->{$name} || throw $self "- something went wrong";
781  
782 my $maxlength_new=$flist->{$name};
783 my $maxlength_old=$fdesc->{'maxlength'} || throw $self "- no existing maxlength on field '$name'";
784 dprint "...field $name, changing maxlength from '$maxlength_old' to '$maxlength_new'";
785  
786 $driver->maxlength_change_field($csh,$name,$maxlength_new,$fdesc);
787  
788 $fdesc->{'maxlength'}=$maxlength_new;
789 }
790  
791 dprint "....preparing to execute, LAST CHANCE TO ABORT";
792 sleep 3;
793 dprint ".....executing";
794 $driver->maxlength_change_execute($csh);
795  
796 foreach my $name (keys %$flist) {
797 my $fdesc=$self->describe($name) || throw $self "- something went wrong";
798  
799 my $uid=$driver->unique_id('Global_Fields','field_name',$name,'table_name',$table);
800 $driver->update_fields('Global_Fields',$uid,{ maxlength => $fdesc->{'maxlength'} });
801 }
802  
803 dprint "...done";
804 }
805  
806 ###############################################################################
807  
808 =item _charset_change (%)
809  
810 Upgrades charset information for the given text fields both in memory
811 structures AND in the database tables.
812  
813 =cut
814  
815 sub _charset_change ($%) {
816 my $self=shift;
817  
818 my $flist=get_args(\@_);
819  
820 my $desc=$self->_class_description;
821 my $table=$desc->{'table'};
822  
823 my $driver=$self->_driver;
824 my $csh=$driver->charset_change_prepare($table);
825  
826 foreach my $name (keys %$flist) {
827 my $fdesc=$desc->{'fields'}->{$name} || throw $self "- something went wrong";
828  
829 my $charset_new=$flist->{$name};
830 my $charset_old=$fdesc->{'charset'} || throw $self "- no existing charset on field '$name'";
831 dprint "...field $name, changing charset from '$charset_old' to '$charset_new'";
832  
833 $driver->charset_change_field($csh,$name,$charset_new,$fdesc->{'maxlength'},$fdesc->{'default'});
834  
835 $fdesc->{'charset'}=$charset_new;
836 }
837  
838 dprint "....preparing to execute, LAST CHANCE TO ABORT";
839 sleep 3;
840 dprint ".....executing";
841 $driver->charset_change_execute($csh);
842  
843 foreach my $name (keys %$flist) {
844 my $fdesc=$self->describe($name) || throw $self "- something went wrong";
845  
846 my $uid=$driver->unique_id('Global_Fields','field_name',$name,'table_name',$table);
847 $driver->update_fields('Global_Fields',$uid,{ charset => $fdesc->{'charset'} });
848 }
849  
850 dprint "...done";
851 }
852  
853 ###############################################################################
854  
855 =item _scale_change (%)
856  
857 Changes 'scale' on 'real' type fields. Can go from unscaled REAL to a
858 scaled DECIMAL.
859  
860 =cut
861  
862 sub _scale_change ($%) {
863 my $self=shift;
864  
865 my $flist=get_args(\@_);
866  
867 my $desc=$self->_class_description;
868 my $table=$desc->{'table'};
869  
870 my $driver=$self->_driver;
871 my $csh=$driver->scale_change_prepare($table);
872  
873 foreach my $name (keys %$flist) {
874 my $fdesc=$desc->{'fields'}->{$name} || throw $self "- something went wrong";
875  
876 my $scale_new=$flist->{$name};
877 my $scale_old=$fdesc->{'maxlength'};
878  
879 dprint "...field $name, changing scale from ",$scale_old," to ",$scale_new;
880  
881 $driver->scale_change_field($csh,$name,$scale_new,$fdesc->{'minvalue'},$fdesc->{'maxvalue'},$fdesc->{'default'});
882  
883 $fdesc->{'maxlength'}=$scale_new;
884 }
885  
886 dprint "....preparing to execute, LAST CHANCE TO ABORT";
887 sleep 3;
888 dprint ".....executing";
889  
890 $driver->scale_change_execute($csh);
891  
892 foreach my $name (keys %$flist) {
893 my $fdesc=$self->describe($name) || throw $self "- something went wrong";
894  
895 my $uid=$driver->unique_id('Global_Fields','field_name',$name,'table_name',$table);
896 $driver->update_fields('Global_Fields',$uid,{ maxlength => $fdesc->{'maxlength'} });
897 }
898  
899 dprint "...done";
900 }
901  
902 ###############################################################################
903  
904 =item _default_change (%)
905  
906 Changes default values for fields.
907  
908 =cut
909  
910 sub _default_change ($%) {
911 my $self=shift;
912 my $flist=get_args(\@_);
913  
914 my $desc=$self->_class_description;
915 my $table=$desc->{'table'};
916  
917 my $driver=$self->_driver;
918  
919 foreach my $name (keys %$flist) {
920 my $fdesc=$self->describe($name) || throw $self "- something went wrong";
921  
922 my $uid=$driver->unique_id('Global_Fields','field_name',$name,'table_name',$table);
923 dprint "...$table:$uid $name -> '$flist->{$name}'";
924 $driver->update_fields('Global_Fields',$uid,{ default => $flist->{$name} });
925 }
926  
927 dprint "...done";
928 }
929  
930 ###############################################################################
931  
932 =item _class_description ()
933  
934 Returns hash reference describing fields of the class name given.
935  
936 =cut
937  
938 sub _class_description ($) {
939 my $self=shift;
940 my $class_name=shift;
941  
942 if($class_name) {
943 return ${$self->_glue}->{'classes'}->{$class_name} ||
944 $self->throw("_class_description - no description for class $class_name");
945 }
946 else {
947 return $$self->{'description'} if $$self->{'description'};
948  
949 my $objname=$$self->{'objname'};
950 my $desc=${$self->_glue}->{'classes'}->{$objname} ||
951 $self->throw("_class_description - object ($objname) is not configured in the database");
952 $$self->{'description'}=$desc;
953  
954 return $desc;
955 }
956 }
957  
958 ###############################################################################
959  
960 # Checks if a collection contains an object with the given collection key (unique id)
961 #
962 sub _collection_exists ($$) {
963 my ($self,$key)=@_;
964  
965 my $desc=$$self->{'class_description'};
966  
967 return $self->_driver->unique_id($desc->{'table'},'unique_id',$key,undef,undef,1);
968 }
969  
970 ###############################################################################
971  
972 # Returns a reference to an array containing complete set of keys for
973 # the given list.
974 #
975 sub _collection_keys ($) {
976 my $self=shift;
977 my $desc=$$self->{'class_description'};
978 $self->_driver->list_keys($desc->{'table'},'unique_id');
979 }
980  
981 ###############################################################################
982  
983 =item _collection_setup ()
984  
985 Sets up collection - base class name, key name and class_description.
986  
987 =cut
988  
989 sub _collection_setup ($) {
990 my $self=shift;
991  
992 my $glue=$self->_glue;
993 $glue || $self->throw("- meaningless on Glue object");
994  
995 my $class_name=$$self->{'class_name'} || $self->throw("_collection_setup - no class name given");
996 $$self->{'class_description'}=$self->_class_description($class_name);
997  
998 my $base_name=$$self->{'base_name'};
999 if(!$base_name) {
1000 $base_name=$$self->{'base_name'}=$glue->upper_class($class_name) ||
1001 $self->throw("- $class_name does not belong to the database");
1002 }
1003  
1004 $$self->{'key_name'}=$glue->_list_key_name($class_name,$base_name);
1005 $$self->{'class_description'}=$self->_class_description($class_name);
1006 }
1007  
1008 ###############################################################################
1009  
1010 =item _driver ()
1011  
1012 Returns a reference to the driver for both Glue and derived objects.
1013  
1014 =cut
1015  
1016 sub _driver ($) {
1017 my $self=shift;
1018 ($$self->{'glue'} ? ${$$self->{'glue'}}->{'driver'} : $$self->{'driver'}) ||
1019 $self->throw("_driver - no low level driver found");
1020 }
1021  
1022 ###############################################################################
1023  
1024 =item _field_description ($)
1025  
1026 Returns the description of the given field.
1027  
1028 =cut
1029  
1030 sub _field_description ($$) {
1031 my $self=shift;
1032 my $field=shift;
1033 $self->_class_description->{'fields'}->{$field};
1034 }
1035  
1036 ###############################################################################
1037  
1038 =item _field_default ($;$) {
1039  
1040 Returns default value for the given field for a hash object. Also sets
1041 'default' in class description if it is not there -- this might happen
1042 when old database is used with new FS.
1043  
1044 Optional second argument is for optimization. It should hold field
1045 description hash reference if it is available in calling context.
1046  
1047 =cut
1048  
1049 sub _field_default ($$) {
1050 my ($self,$field,$desc,$check)=@_;
1051  
1052 $desc//=$self->_field_description($field);
1053  
1054 my $default=$desc->{'default'};
1055 if(defined $default) {
1056 return $default unless $check;
1057  
1058 my $type=$desc->{'type'};
1059 if($type eq 'text' || $type eq 'blob') {
1060 !defined $desc->{'minlength'} || length $default >= $desc->{'minlength'} ||
1061 throw $self "- default '$default' is shorter than minlength $desc->{'minlength'} for $field";
1062 !defined $desc->{'maxlength'} || length $default <= $desc->{'maxlength'} ||
1063 throw $self "- default '$default' is longer than maxlength $desc->{'maxlength'} for $field";
1064 }
1065 elsif($type eq 'integer' || $type eq 'real') {
1066 if($type eq 'integer') {
1067 $default=~/^-?\d+$/ ||
1068 throw $self "- default '$default' is not an integer for $field";
1069 }
1070 elsif($type eq 'real') {
1071 $default=~/^-?\d+(?:\.\d+)?$/ || $default=~/^-?\.\d+$/ ||
1072 throw $self "- default '$default' is not a number for $field";
1073 }
1074 !defined $desc->{'minvalue'} || $default >= $desc->{'minvalue'} ||
1075 throw $self "- default $default is below minvalue $desc->{'minvalue'} for $field";
1076 !defined $desc->{'maxvalue'} || $default <= $desc->{'maxvalue'} ||
1077 throw $self "- default $default is above maxvalue $desc->{'maxvalue'} for $field";
1078 }
1079  
1080 return $default;
1081 }
1082  
1083 # Undefined, calculating a default default.
1084 #
1085 my $type=$desc->{'type'};
1086 if($type eq 'text' || $type eq 'blob') {
1087 $default='';
1088 }
1089 elsif($type eq 'integer' || $type eq 'real') {
1090 my $minvalue=$desc->{'minvalue'};
1091 my $maxvalue=$desc->{'maxvalue'};
1092 if(!defined $minvalue) {
1093 $default=!defined $maxvalue || $maxvalue>=0 ? 0 : $maxvalue;
1094 }
1095 elsif(!defined $maxvalue) {
1096 $default=$minvalue<0 ? 0 : $minvalue;
1097 }
1098 else {
1099 $default=$minvalue;
1100 }
1101 }
1102 else {
1103 throw $self "- wrong type for trying to get default (name=$field, type=$type)";
1104 }
1105  
1106 $desc->{'default'}=$default;
1107  
1108 return $default;
1109 }
1110  
1111 ###############################################################################
1112  
1113 =item _glue ()
1114  
1115 Returns glue object reference. Makes sense only in derived objects!
1116 For GLue object itself would throw an error, this is expected
1117 behavior!
1118  
1119 =cut
1120  
1121 sub _glue ($) {
1122 my $self=shift;
1123 $$self->{'glue'} || $self->throw("_glue - meaningless on Glue object");
1124 }
1125  
1126 ###############################################################################
1127  
1128 =item _hash_list_base_id ()
1129  
1130 Returns unique_id of the hash that contains the list that contains the
1131 current hash. Used in container_object() method of Hash.
1132  
1133 =cut
1134  
1135 sub _hash_list_base_id () {
1136 my $self=shift;
1137  
1138 ##
1139 # Most of the time that will work fine, except for objects retrieved
1140 # from a Collection of some sort.
1141 #
1142 return $$self->{'list_base_id'} if $$self->{'list_base_id'};
1143  
1144 ##
1145 # Global is a special case
1146 #
1147 my $base_name=$$self->{'list_base_name'};
1148 return $$self->{'list_base_id'}=1 if $base_name eq 'FS::Global';
1149  
1150 ##
1151 # Collection skips over hierarchy and we have to be more elaborate.
1152 #
1153 my $connector=$self->_glue->_connector_name($self->objname,$base_name);
1154 $$self->{'list_base_id'}=$self->_retrieve_data_fields($connector);
1155 }
1156  
1157 ###############################################################################
1158  
1159 =item _hash_list_key_value ()
1160  
1161 Returns what would be returned by container_key() of upper level
1162 List. Used in container_object().
1163  
1164 =cut
1165  
1166 sub _hash_list_key_value () {
1167 my $self=shift;
1168  
1169 ##
1170 # Returning cached value if available
1171 #
1172 return $$self->{'list_key_value'} if $$self->{'list_key_value'};
1173  
1174 ##
1175 # Finding that out.
1176 #
1177 my $cdesc=${$self->_glue}->{'classes'}->{$$self->{'list_base_name'}} ||
1178 $self->throw("_hash_list_key_value - no 'list_base_name' available");
1179 my $class_name=$self->objname;
1180 foreach my $fn (keys %{$cdesc->{'fields'}}) {
1181 my $fd=$cdesc->{'fields'}->{$fn};
1182 next unless $fd->{'type'} eq 'list' && $fd->{'class'} eq $class_name;
1183 return $$self->{'list_key_value'}=$fn;
1184 }
1185  
1186 $self->throw("_hash_list_key_value - no reference to the list in upper class, weird");
1187 }
1188  
1189 ###############################################################################
1190  
1191 ##
1192 # Retrieves content of arbitrary number of data fields. Works only for
1193 # Hash object.
1194 #
1195 sub _retrieve_data_fields ($@) {
1196 my $self=shift;
1197  
1198 @_ || $self->throw("_retrieve_data_field - at least one name must present");
1199  
1200 my $desc=$self->_class_description();
1201  
1202 my $data=$self->_driver->retrieve_fields($desc->{'table'},
1203 $$self->{'unique_id'},
1204 @_);
1205  
1206 $data ? (@_ == 1 ? $data->[0] : @$data)
1207 : (@_ == 1 ? undef : ());
1208 }
1209  
1210 ###############################################################################
1211  
1212 ##
1213 # Stores multiple pre-checked for validity key/value pairs into hash
1214 # object. Works only on Hash objects.
1215 #
1216 sub _store_data_fields ($$) {
1217 my ($self,$data)=@_;
1218 my $table=$self->_class_description->{'table'};
1219 $self->_driver->update_fields($table,$$self->{'unique_id'},$data);
1220 }
1221  
1222 ###############################################################################
1223  
1224 ##
1225 # Returns and caches connector name between two given classes. Works
1226 # only for Glue object.
1227 #
1228 sub _connector_name ($$$) {
1229 my $self=shift;
1230 my $class_name=shift;
1231 my $base_name=shift;
1232 if(exists($$self->{'connectors_cache'}->{$class_name}->{$base_name})) {
1233 return $$self->{'connectors_cache'}->{$class_name}->{$base_name};
1234 }
1235 my $class_desc=$$self->{'classes'}->{$class_name};
1236 $class_desc || $self->throw("_connector_name - no data for class $class_name (called on derived object?)");
1237 foreach my $field (keys %{$class_desc->{'fields'}}) {
1238 my $fdesc=$class_desc->{'fields'}->{$field};
1239 next unless $fdesc->{'type'} eq 'connector' && $fdesc->{'refers'} eq $base_name;
1240 $$self->{'connectors_cache'}->{$class_name}->{$base_name}=$field;
1241 return $field;
1242 }
1243 undef;
1244 }
1245  
1246 ###############################################################################
1247  
1248 # Checks if list contains an object with the given name
1249 #
1250 sub _list_exists ($$) {
1251 my $self=shift;
1252 my $name=shift;
1253 $self->_find_unique_id($name) ? 1 : 0;
1254 }
1255  
1256 ###############################################################################
1257  
1258 ##
1259 # Returns list key name that uniquely identify specific list objects
1260 # along that list.
1261 #
1262 sub _list_key_name ($$$) {
1263 my $self=shift;
1264 my $class_name=shift;
1265 my $base_name=shift || '';
1266 if(exists($$self->{'list_keys_cache'}->{$class_name}->{$base_name})) {
1267 return $$self->{'list_keys_cache'}->{$class_name}->{$base_name};
1268 }
1269 my $class_desc=$$self->{'classes'}->{$class_name};
1270 $class_desc || $self->throw("_list_key_name - no data for class $class_name (called on derived object?)");
1271 foreach my $field (keys %{$class_desc->{'fields'}}) {
1272 my $fdesc=$class_desc->{'fields'}->{$field};
1273 next unless $fdesc->{'type'} eq 'key' && $fdesc->{'refers'} eq $base_name;
1274 $$self->{'list_keys_cache'}->{$class_name}->{$base_name}=$field;
1275 return $field;
1276 }
1277 $self->throw("_list_key_name - no key defines $class_name in $base_name");
1278 }
1279  
1280 ###############################################################################
1281  
1282 ##
1283 # Returns a reference to an array containing complete set of keys for
1284 # the given list.
1285 #
1286 sub _list_keys ($) {
1287 my $self=shift;
1288 my $desc=$$self->{'class_description'};
1289 $self->_driver->list_keys($desc->{'table'},
1290 $$self->{'key_name'},
1291 $$self->{'connector_name'},
1292 $$self->{'base_id'});
1293 }
1294  
1295 ###############################################################################
1296  
1297 =item _list_search (%)
1298  
1299 Searches for elements in the list and returns a reference to the array
1300 with object IDs. See search() method in
1301 L<XAO::DO::FS::List> for more details.
1302  
1303 Works on Collections too.
1304  
1305 =cut
1306  
1307 sub _list_search ($%) {
1308 my $self=shift;
1309  
1310 my $options;
1311 $options=pop(@_) if ref($_[$#_]) eq 'HASH';
1312  
1313 my $conditions;
1314 if(scalar(@_) == 3) {
1315 $conditions=[ @_ ];
1316 }
1317 elsif(scalar(@_) == 1 && ref($_[0]) eq 'ARRAY') {
1318 $conditions=$_[0];
1319 $conditions=undef unless @$conditions;
1320 }
1321 elsif(! @_) {
1322 $conditions=undef;
1323 }
1324 else {
1325 $self->throw('_list_search - bad arguments');
1326 }
1327  
1328 if($$self->{'connector_name'} && $$self->{'base_id'}) {
1329 my $special=[ $$self->{'connector_name'}, 'eq', $$self->{'base_id'} ];
1330 if($conditions) {
1331 $conditions=[ $special, 'and', $conditions ];
1332 }
1333 else {
1334 $conditions=$special;
1335 }
1336 }
1337  
1338 my $key;
1339 if($self->objname eq 'FS::Collection') {
1340 $key='unique_id';
1341 }
1342 else {
1343 $key=$$self->{'key_name'};
1344 }
1345  
1346 my $query=$self->_build_search_query(
1347 options => $options,
1348 conditions => $conditions,
1349 key => $key,
1350 );
1351  
1352 ##
1353 # Performing the search
1354 #
1355 my $list=$self->_driver->search($query);
1356  
1357 ##
1358 # Post-processing results if required. The only way to get here
1359 # currently is if database driver does not support regex'es and
1360 # ws/wq search was performed.
1361 #
1362 if($query->{'post_process'}) {
1363 $self->throw('TODO; post-processing not supported yet, mail am@ejelta.com');
1364 }
1365  
1366 ##
1367 # Done.
1368 #
1369 if($options->{'result'}) {
1370  
1371 ##
1372 # Checking if we need to manipulate the results before returning them
1373 #
1374 my $result_descs=$query->{'result_descs'} || throw $self "_list_search - internal error";
1375 my @dmap;
1376 my $need_mapping;
1377 for(my $i=0; $i<@$result_descs; ++$i) {
1378 my $d=$result_descs->[$i];
1379 if($d->{'type'} && $d->{'type'} eq 'text' && $d->{'charset'} ne 'binary') {
1380 $need_mapping=1;
1381 $dmap[$i]=$d->{'charset'};
1382 }
1383 elsif($d->{'type'} && $d->{'type'} eq 'key' && $d->{'key_charset'} ne 'binary') {
1384 $need_mapping=1;
1385 $dmap[$i]=$d->{'key_charset'};
1386 }
1387 }
1388  
1389 if($need_mapping) {
1390 my $i;
1391 return [ map {
1392 $i=-1;
1393 [ map {
1394 ++$i;
1395 $dmap[$i] ? Encode::decode($dmap[$i],$_) : $_;
1396 } @$_ ];
1397 } @{$query->{'fields_list'}}==1 ? (map { [ $_ ] } @$list) : @$list ];
1398 }
1399 elsif(@{$query->{'fields_list'}}==1) {
1400 return [ map { [ $_ ] } @$list ];
1401 }
1402 else {
1403 return $list;
1404 }
1405 }
1406 elsif(@{$query->{'fields_list'}} > 1) {
1407 return [ map { $_->[0] } @$list ];
1408 }
1409 else {
1410 return $list;
1411 }
1412 }
1413  
1414 ###############################################################################
1415  
1416 =item _build_search_query (%)
1417  
1418 Builds SQL search query according to search parameters given. See
1419 List manpage for description. Returns a reference to a hash of the
1420 following structure, not a string:
1421  
1422 sql => complete SQL statement
1423 values => array of values to be substituted into the SQL query
1424 classes => hash with all classes and their aliases
1425 fields_list => list of all fiels names
1426 fields_map => hash with the map of 'condition field name' => 'sql name'
1427 distinct => list of fields to be unique
1428 order_by => list of fields to sort on
1429 post_process => is non-zero if there could be extra rows in the search
1430 results because of some condition that could not be
1431 expressed adequately in SQL.
1432 options => original options from the FS query
1433  
1434 =cut
1435  
1436 sub _build_search_query ($%) {
1437 my $self=shift;
1438 my $args=get_args(\@_);
1439  
1440 ##
1441 # Building the list of classes used and WHERE clause for the
1442 # conditions list.
1443 #
1444 # In case where we do not have conditions we just put current class
1445 # name into classes.
1446 #
1447 my $condition=$args->{'conditions'};
1448 ### use Data::Dumper;
1449 ### dprint "CONDITION: ",Dumper($condition);
1450 my %classes;
1451 my @values;
1452 my %fields_map;
1453 my $post_process=0;
1454 my $clause;
1455 if($condition && (ref($condition) ne 'ARRAY' || @$condition)) {
1456 $clause=$self->_build_search_clause(\%classes,
1457 \@values,
1458 \%fields_map,
1459 \$post_process,
1460 $condition);
1461 }
1462 else {
1463 $clause='';
1464 my $class_name=$$self->{'class_name'} ||
1465 $self->throw("_build_search_query - no 'class_name', not a List or Collection?");
1466 $self->_build_search_field_class(\%classes,$class_name,1,"",1);
1467 }
1468  
1469 ##
1470 # Adding key name into fields we need.
1471 #
1472 my $key=$args->{'key'} ||
1473 $self->throw("_build_search_query - no 'key' given");
1474 my ($key_field,$key_fdesc)=$self->_build_search_field(\%classes,$key);
1475  
1476 ##
1477 # Analyzing options
1478 #
1479 my %return_fields;
1480 my @distinct;
1481 my @orderby;
1482 my $debug;
1483 my $options=$args->{'options'};
1484 my @result_fields;
1485 my @result_descs;
1486 my $groupby_pos;
1487 my $no_distinct;
1488 if($options) {
1489 foreach my $option (keys %$options) {
1490 if(lc($option) eq 'distinct') {
1491 my $list=$options->{$option};
1492 $list=[ $list ] unless ref($list);
1493 foreach my $fn (@$list) {
1494 my ($sqlfn,$fdesc)=$self->_build_search_field(\%classes,$fn);
1495 $fdesc->{'type'} eq 'list' &&
1496 $self->throw("_build_search_query - can't use 'list' fields in DISTINCT");
1497 $return_fields{$sqlfn}=1;
1498 push(@distinct,$sqlfn);
1499 }
1500 }
1501 elsif(lc($option) eq 'no_distinct') {
1502 $no_distinct=1;
1503 }
1504 elsif(lc($option) eq 'result') {
1505 my $list=$options->{$option};
1506 $list=[ $list ] unless ref $list;
1507  
1508 @$list ||
1509 throw $self "_build_search_query - list of fields in 'result' option can't be empty";
1510  
1511 foreach my $fn (@$list) {
1512 my ($sqlfn,$fdesc);
1513 if($fn eq '#id') {
1514 $sqlfn=$key_field;
1515 $fdesc=$key_fdesc;
1516 $groupby_pos=@result_fields;
1517 }
1518 elsif($fn eq '#connector') {
1519 my $conn=$self->_glue->_connector_name($$self->{'class_name'},$$self->{'base_name'}) ||
1520 throw $self "- no #connector on the top level list";
1521 ($sqlfn,$fdesc)=$self->_build_search_field(\%classes,$conn);
1522 }
1523 elsif($fn eq '#container_key') {
1524 if($self->objname eq 'FS::Collection') {
1525 ($sqlfn,$fdesc)=$self->_build_search_field(\%classes,$$self->{'key_name'});
1526 }
1527 else {
1528 $sqlfn=$key_field;
1529 $fdesc=$key_fdesc;
1530 }
1531 }
1532 elsif($fn eq '#collection_key') {
1533 if($self->objname eq 'FS::Collection') {
1534 $sqlfn=$key_field;
1535 $fdesc=$key_fdesc;
1536 }
1537 else {
1538 ($sqlfn,$fdesc)=$self->_build_search_field(\%classes,'unique_id');
1539 }
1540 $groupby_pos=@result_fields;
1541 }
1542 else {
1543 ($sqlfn,$fdesc)=$self->_build_search_field(\%classes,$fn);
1544 $fdesc->{'type'} eq 'list' &&
1545 $self->throw("_build_search_query - can't use 'list' fields in 'result' option");
1546 }
1547 if(!defined $groupby_pos && $sqlfn eq $key_field) {
1548 $groupby_pos=@result_fields;
1549 }
1550 $return_fields{$sqlfn}=1;
1551 push(@result_fields,$sqlfn);
1552 push(@result_descs,$fdesc);
1553 }
1554  
1555 ### dprint Dumper(\%return_fields);
1556 ### dprint Dumper(\@result_descs);
1557 }
1558 elsif(lc($option) eq 'orderby') {
1559 my $list=$options->{$option};
1560  
1561 if(ref($list)) {
1562 ref($list) eq 'ARRAY' ||
1563 $self->throw("_list_search - 'orderby' argument must be an array reference");
1564 }
1565 elsif(substr($list,0,1) eq '-') {
1566 $list=[ descend => substr($list,1) ];
1567 }
1568 else {
1569 $list=[ ascend => $list ];
1570 }
1571  
1572 scalar(@$list)%2 &&
1573 $self->throw("_list_search - odd number of values in 'orderby' list");
1574  
1575 for(my $i=0; $i<@$list; $i+=2) {
1576 my $fn=$list->[$i+1];
1577 my ($sqlfn,$fdesc)=$self->_build_search_field(\%classes,$fn);
1578  
1579 $fdesc->{'type'} eq 'list' &&
1580 $self->throw("_build_search_query - can't use 'list' fields in ORDERBY");
1581  
1582 my $o=lc($list->[$i]);
1583 $o='ascend' if $o eq 'asc';
1584 $o='descend' if $o eq 'desc';
1585  
1586 push(@orderby,$o,$sqlfn);
1587 }
1588 }
1589 elsif(lc($option) eq 'limit' || lc($option) eq 'offset') {
1590 # pass through, handled in the driver
1591 }
1592 elsif(lc($option) eq 'index') {
1593 my $fn=$options->{$option};
1594 my ($sqlfn,$fdesc,$class_name,$class_tag)=
1595 $self->_build_search_field(\%classes,$fn);
1596 $classes{'center_class'}=$class_name;
1597 $classes{'center_tag'}=$class_tag;
1598 $classes{'center_weight'}=1000;
1599 }
1600 elsif(lc($option) eq 'debug') {
1601 $debug=$options->{$option};
1602 }
1603 else {
1604 $self->throw("_build_search_query - unknown option '$option'");
1605 }
1606 }
1607 }
1608 $no_distinct=undef if @distinct;
1609  
1610 ##
1611 # If post processing is required then adding everything to the list
1612 # of fields to return.
1613 #
1614 if($post_process) {
1615 @return_fields{CORE::values %fields_map}=CORE::values %fields_map;
1616 }
1617  
1618 ##
1619 # Removing unused top of the tree
1620 #
1621 my $top_class=$classes{'top_class'};
1622 my $top_tag=$classes{'top_tag'};
1623 my $up=$classes{'up'};
1624 while(1) {
1625 last if $up->{$top_class}->{$top_tag}->{'name'};
1626 my $count=0;
1627 my $ntc;
1628 my $ntt;
1629 foreach my $cin (keys %$up) {
1630 foreach my $tin (keys %{$up->{$cin}}) {
1631 if($up->{$cin}->{$tin}->{'class'} eq $top_class) {
1632 if(!$count) {
1633 $ntc=$cin;
1634 $ntt=$tin;
1635 }
1636 $count++;
1637 }
1638 }
1639 last if $count>1;
1640 }
1641 last if $count>1;
1642 delete $up->{$top_class};
1643 $top_class=$classes{'top_class'}=$ntc;
1644 $top_tag=$classes{'top_tag'}=$ntt;
1645 $up->{$top_class}->{$top_tag}->{'class'}='';
1646 }
1647  
1648 ##
1649 # Adding names to tables that are left in the tree but are not
1650 # referred by any fields and therefore did not yet get their names.
1651 #
1652 foreach my $cin (keys %$up) {
1653 foreach my $tin (keys %{$up->{$cin}}) {
1654 if(!$up->{$cin}->{$tin}->{'name'}) {
1655 my $ci=$classes{'index'}++;
1656 $up->{$cin}->{$tin}->{'name'}=$ci;
1657 $classes{'names'}->{$ci}={
1658 class => $cin,
1659 tag => $tin,
1660 weight => 0,
1661 table => $self->_class_description($cin)->{'table'},
1662 };
1663 }
1664 }
1665 }
1666  
1667 ##
1668 # Translating classes into table names and adding glue to join
1669 # tables together into the clause.
1670 #
1671 # We link up tables that are above our center point and then link
1672 # down the rest. This takes care of all tables in correct order. SQL
1673 # engine can of course reverse or alter the order, but generally
1674 # this should be pretty optimal way of joining.
1675 #
1676 my ($cc,$ct)=@classes{'center_class','center_tag'};
1677 my $wrapped=$clause && substr($clause,0,1) eq '(';
1678 my $glue=$self->_glue;
1679 while(1) {
1680 my ($uc,$ut,$cn)=@{$up->{$cc}->{$ct}}{'class','tag','name'};
1681 last unless $uc;
1682 if(!$wrapped) {
1683 $clause="($clause)" if $clause;
1684 $wrapped=1;
1685 }
1686 my $conn=$glue->_connector_name($cc,$uc);
1687 if($conn) {
1688 $conn=$self->_driver->mangle_field_name($conn);
1689 my $un=$up->{$uc}->{$ut}->{'name'};
1690 $clause.=" AND " if $clause;
1691 $clause.="$un.unique_id=$cn.$conn";
1692 }
1693 $up->{$cc}->{$ct}->{'done'}=1;
1694 $cc=$uc;
1695 $ct=$ut;
1696 }
1697 foreach my $cc (keys %$up) {
1698 foreach my $ct (keys %{$up->{$cc}}) {
1699 my ($uc,$ut,$cn,$d)=@{$up->{$cc}->{$ct}}{'class','tag','name','done'};
1700 next unless $uc && !$d;
1701 if(!$wrapped) {
1702 $clause="($clause)" if $clause;
1703 $wrapped=1;
1704 }
1705  
1706 my $conn=$glue->_connector_name($cc,$uc);
1707 if($conn) {
1708 $conn=$self->_driver->mangle_field_name($conn);
1709 my $un=$up->{$uc}->{$ut}->{'name'};
1710 $clause.=" AND " if $clause;
1711 $clause.="$cn.$conn=$un.unique_id";
1712 }
1713 }
1714 }
1715  
1716 ##
1717 # Unless we were asked for a specific set of fields, moving key to
1718 # the first position in the list of fields. Otherwise making sure
1719 # the fields we were asked for are the first in the given order.
1720 #
1721 my @fields_list;
1722 if(@result_fields) {
1723 delete @return_fields{@result_fields};
1724 if(@distinct || defined $groupby_pos) {
1725 @fields_list=(@result_fields,keys %return_fields);
1726 }
1727 else {
1728 delete $return_fields{$key_field};
1729 @fields_list=(@result_fields,$key_field,keys %return_fields);
1730 $groupby_pos=@result_fields;
1731 }
1732 }
1733 else {
1734 delete $return_fields{$key_field};
1735 @fields_list=($key_field, keys %return_fields);
1736 $groupby_pos=0;
1737 }
1738 undef %return_fields;
1739 undef @result_fields;
1740  
1741 ##
1742 # Composing SQL query out of data we have.
1743 #
1744 my $c_names=$classes{'names'};
1745 my $sql='SELECT ';
1746 $sql.=join(',',@fields_list) .
1747 ' FROM ' .
1748 join(',',map { $c_names->{$_}->{'table'} . ' AS ' . $_ } keys %{$c_names});
1749 $sql.=' WHERE ' . $clause if $clause;
1750  
1751 ##
1752 # If we're asked to produce distinct on something then we only group
1753 # on that, because if we include key into group by we will not
1754 # eliminate rows that have non-unique values in the parameter.
1755 #
1756 # The drawback of that is that if we were asked to have distinct
1757 # values in some inner class then we can have repeating keys.
1758 #
1759 my $have_group_by;
1760 if(@distinct) {
1761 $sql.=' GROUP BY ' . join(',',@distinct);
1762 $have_group_by=1;
1763 }
1764 elsif($no_distinct) {
1765 #
1766 }
1767 elsif(scalar(keys %$c_names)>1) {
1768 $sql.=' GROUP BY ' . $fields_list[$groupby_pos];
1769 $have_group_by=1;
1770 }
1771  
1772 # Ordering goes after GROUP BY
1773 #
1774 if(@orderby) {
1775 $sql.=' ORDER BY ';
1776 for(my $i=0; $i<@orderby; $i+=2) {
1777 $sql.=$orderby[$i+1];
1778 $sql.=' DESC' if $orderby[$i] eq 'descend';
1779 $sql.=',' unless $i+2 == @orderby;
1780 }
1781 }
1782  
1783 # MySQL suggests to add "ORDER BY NULL" if the query has "GROUP BY",
1784 # but sorting order is not important. The default MySQL behavior is
1785 # to assume there is an ORDER BY on the same columns as GROUP BY.
1786 #
1787 if($have_group_by && !@orderby) {
1788 $sql.=' ORDER BY NULL';
1789 }
1790  
1791 # To aid in debugging..
1792 #
1793 print STDERR "SEARCH SQL: $sql\n" if $debug;
1794  
1795 # Returning resulting hash
1796 #
1797 return {
1798 sql => $sql,
1799 where => $clause,
1800 values => \@values,
1801 classes => \%classes,
1802 fields_list => \@fields_list,
1803 fields_map => \%fields_map,
1804 result_descs => \@result_descs,
1805 distinct => \@distinct,
1806 order_by => \@orderby,
1807 post_process => $post_process,
1808 options => $options,
1809 };
1810 }
1811  
1812 ###############################################################################
1813  
1814 =item _build_search_field ($$)
1815  
1816 Builds SQL field name including table alias from field path like
1817 'Specification/value'.
1818  
1819 XXX - Returns array consisting of translated field name, final class name,
1820 class description and field description.
1821  
1822 =cut
1823  
1824 sub _build_search_field ($$$) {
1825 my $self=shift;
1826 my $classes=shift;
1827 my $lha=shift;
1828 my $glue=$self->_glue;
1829  
1830 my $up=$classes->{'up'};
1831 $up=$classes->{'up'}={} unless $up;
1832  
1833 # Optimizing stupid things like 'D/../E' into 'E'
1834 #
1835 while($lha=~/^(.*\/)?\w.*?\/\.\.\/(.*)$/) {
1836 $lha=(defined($1) ? $1 : '') . $2;
1837 }
1838  
1839 # Splitting field name into parts if it looks like path either
1840 # absolute or relative. Real field name is the last element, popping
1841 # it back into $lha.
1842 #
1843 my @path=split(/\/+/,$lha);
1844 $lha=pop @path;
1845  
1846 my $class_name;
1847 my $class_tag=1;
1848 if(@path && $path[0] eq '') {
1849 $class_name='FS::Global';
1850 shift @path;
1851 }
1852 else {
1853 $class_name=$$self->{'class_name'} ||
1854 $self->throw("_build_search_field - no 'class_name', not a List or Collection?");
1855 while(@path && $path[0] eq '..') {
1856 $class_name=$glue->upper_class($class_name) ||
1857 throw $self "_build_search_field - no upper class for $class_name";
1858 shift @path;
1859 }
1860 }
1861  
1862 $self->_build_search_field_class($classes,$class_name,$class_tag,"",1);
1863  
1864 my $class_desc=$self->_class_description($class_name);
1865  
1866 for(my $i=0; $i!=@path; $i++) {
1867 my $n=$path[$i];
1868  
1869 my $fd=$class_desc->{'fields'}->{$n} ||
1870 $self->throw("_build_search_field - unknown field '$n' in $lha");
1871 $fd->{'type'} eq 'list' ||
1872 $self->throw("_build_search_field - '$n' is not a list in $lha");
1873 my $n_class=$fd->{'class'};
1874  
1875 my $n_tag=$i+1==@path ? '' : $path[$i+1];
1876 if($n_tag eq '*') {
1877 $i++;
1878 $classes->{'tag_index'}||='ta';
1879 $n_tag=$classes->{'tag_index'}++;
1880 }
1881 elsif($n_tag=~/^\d+$/) {
1882 $i++;
1883 }
1884 else {
1885 $n_tag=1;
1886 }
1887  
1888 $self->_build_search_field_class($classes,$n_class,$n_tag,
1889 $class_name,$class_tag);
1890 $class_name=$n_class;
1891 $class_tag=$n_tag;
1892 $class_desc=$self->_class_description($class_name);
1893 }
1894  
1895 my $class_index=$up->{$class_name}->{$class_tag}->{'name'};
1896 if(!$class_index) {
1897 $classes->{'index'}||='a';
1898 $class_index=$classes->{'index'}++;
1899 $up->{$class_name}->{$class_tag}->{'name'}=$class_index;
1900 $classes->{'names'}->{$class_index}={
1901 class => $class_name,
1902 tag => $class_tag,
1903 weight => 0,
1904 table => $class_desc->{'table'},
1905 };
1906 }
1907  
1908 # Special condition for 'unique_id' field names.
1909 #
1910 my $field_desc=$lha eq 'unique_id' ? { type => 'unique_id' } : $class_desc->{'fields'}->{$lha};
1911 $field_desc || $self->throw("_build_search_field - unknown field '$lha' ($class_name)");
1912  
1913 # Counting number of fields using that table, index have more weight
1914 # and unique index even more. If not overriden in options that is
1915 # going to be our center table.
1916 #
1917 my $inc=$field_desc->{'unique'} ? 20 : ($field_desc->{'index'} ? 10 : 1);
1918 my $weight=$classes->{'names'}->{$class_index}->{'weight'}+=$inc;
1919 if(!$classes->{'center_weight'} || $classes->{'center_weight'}<$weight) {
1920 $classes->{'center_weight'}=$weight;
1921 $classes->{'center_class'}=$class_name;
1922 $classes->{'center_tag'}=$class_tag;
1923 }
1924  
1925 # We don't need to mangle field name if it's a unique_id field
1926 #
1927 if($lha eq 'unique_id') {
1928 $lha=$class_index . '.' . $lha;
1929 }
1930 else {
1931 $lha=$class_index . '.' . $self->_driver->mangle_field_name($lha);
1932 }
1933  
1934 return ($lha,$field_desc,$class_name,$class_tag);
1935 }
1936  
1937 ###############################################################################
1938  
1939 sub _build_search_field_class ($$$$$$) {
1940 my ($self,$classes,$n_class,$n_tag,$p_class,$p_tag)=@_;
1941  
1942 my $up=$classes->{'up'};
1943  
1944 if(!$p_class && (!$up->{$n_class} || !$up->{$n_class}->{$n_tag})) {
1945 if(!$classes->{'top_class'}) {
1946 $classes->{'top_class'}=$n_class;
1947 $classes->{'top_tag'}=$n_tag;
1948 }
1949 elsif($classes->{'top_class'} ne $n_class) {
1950 my $uc=$classes->{'top_class'};
1951 while($uc ne $n_class) {
1952 $uc=$self->_glue->upper_class($uc);
1953 last unless $uc;
1954 $up->{$uc}->{1}={
1955 class => '',
1956 tag => 1,
1957 };
1958 my ($ctc,$ctt)=@{$classes}{'top_class','top_tag'};
1959 @{$up->{$ctc}->{$ctt}}{'class','tag'}=($uc,1);
1960 @{$classes}{'top_class','top_tag'}=($uc,$uc eq $n_class ? $n_tag : 1);
1961 }
1962 if(!$uc) {
1963 $uc=$n_class;
1964 my $ut=$n_tag;
1965 while(1) {
1966 if(!$up->{$uc} || !$up->{$uc}->{$ut}) {
1967 $up->{$uc}->{$ut}={
1968 class => $self->_glue->upper_class($uc),
1969 tag => 1,
1970 };
1971 $uc=$up->{$uc}->{$ut}->{'class'};
1972 $ut=1;
1973 }
1974 last if $up->{$uc}->{$ut};
1975 }
1976 }
1977 }
1978 elsif($classes->{'top_tag'} ne $n_tag) {
1979 my $uc=$classes->{'top_class'};
1980 $uc=$self->_glue->upper_class($uc) ||
1981 throw $self "_build_search_field_class - no upper class for $uc";
1982 $up->{$uc}->{1}={
1983 class => '',
1984 tag => 1,
1985 };
1986 }
1987 }
1988  
1989 return if $up->{$n_class} && $up->{$n_class}->{$n_tag};
1990  
1991 $up->{$n_class}->{$n_tag}={
1992 class => $p_class,
1993 tag => $p_tag,
1994 };
1995 }
1996  
1997 ###############################################################################
1998  
1999 =item _build_search_clause ($$$$$)
2000  
2001 Builds a list of classes used and WHERE clause for the given search
2002 conditions.
2003  
2004 =cut
2005  
2006 sub _build_search_clause ($$$$$$) {
2007 my ($self,$classes,$values,$fields_map,$post_process,$condition)=@_;
2008  
2009 ##
2010 # Checking if the condition has exactly three elements
2011 #
2012 ref($condition) eq 'ARRAY' && @$condition == 3 ||
2013 $self->throw("_build_search_query - bad syntax of 'conditions'");
2014 my ($lha,$op,$rha)=@$condition;
2015 $op=lc($op);
2016  
2017 ##
2018 # Handling search('comment', 'wq', [ 'big', 'ugly' ]);
2019 #
2020 # Translated to search([ 'comment', 'wq', 'big' ],
2021 # 'or',
2022 # [ 'comment', 'wq', 'ugly' ]);
2023 #
2024 if(!ref($lha) && ref($rha) eq 'ARRAY') {
2025 @$rha ||
2026 throw $self "_build_search_query - shortcut array cannot be empty ('$lha','$op',[])";
2027  
2028 my @args=($lha,$op,$rha->[0]);
2029 for(my $i=1; $i!=@$rha; $i++) {
2030 @args=( [ @args ], 'or', [ $lha, $op, $rha->[$i] ] );
2031 }
2032 ($lha,$op,$rha)=@args;
2033 }
2034  
2035 ##
2036 # First checking if we have OR/AND stuff
2037 #
2038 if(ref($lha)) {
2039 ref($rha) eq 'ARRAY' ||
2040 $self->throw("_build_search_clause - expected an array reference in RHA '$rha'");
2041  
2042 # The recursion is expected here, silencing the warning.
2043 #
2044 no warnings 'recursion';
2045  
2046 my $lhv=$self->_build_search_clause($classes,
2047 $values,
2048 $fields_map,
2049 $post_process,
2050 $lha);
2051  
2052 my $rhv=$self->_build_search_clause($classes,
2053 $values,
2054 $fields_map,
2055 $post_process,
2056 $rha);
2057  
2058 my $clause;
2059 if($op eq 'or' || $op eq '||') {
2060 $clause="($lhv OR $rhv)";
2061 }
2062 elsif($op eq 'and' || $op eq '&&') {
2063 $clause="($lhv AND $rhv)";
2064 }
2065 else {
2066 $self->throw("_build_search_clause - unknown operation '$op'");
2067 }
2068  
2069 return $clause;
2070 }
2071  
2072 ##
2073 # Now building SQL field name and class aliases to support it.
2074 #
2075 my ($field,$field_desc)=$self->_build_search_field($classes,$lha);
2076 $fields_map->{$lha}=$field;
2077  
2078 ##
2079 # And finally making the part of clause we were asked for
2080 #
2081 ($field_desc->{'type'} && $field_desc->{'type'} eq 'list') &&
2082 throw $self "_build_search_clause - can't search on 'list' field '$lha'";
2083 ref($rha) &&
2084 throw $self "_build_search_clause - expected constant right hand side argument ['$lha', '$op', $rha]";
2085 defined $rha ||
2086 throw $self "_build_search_clause - undefined right hand side for '$lha'";
2087  
2088 my $rha_escaped=$rha;
2089 $rha_escaped=~s/([%_\\'"])/\\$1/g;
2090  
2091 my $clause;
2092 if($op eq 'eq') {
2093 $clause="$field=?";
2094 push(@$values,$rha);
2095 }
2096 elsif($op eq 'ne') {
2097 $clause="$field<>?";
2098 push(@$values,$rha);
2099 }
2100 elsif($op eq 'lt') {
2101 $clause="$field<?";
2102 push(@$values,$rha);
2103 }
2104 elsif($op eq 'le') {
2105 $clause="$field<=?";
2106 push(@$values,$rha);
2107 }
2108 elsif($op eq 'gt') {
2109 $clause="$field>?";
2110 push(@$values,$rha);
2111 }
2112 elsif($op eq 'ge') {
2113 $clause="$field>=?";
2114 push(@$values,$rha);
2115 }
2116 elsif($op eq 'cs') {
2117 $clause="$field LIKE '" . '%' . $rha_escaped . '%' . "'";
2118 }
2119 elsif($op eq 'sw') {
2120 $clause="$field LIKE '" . $rha_escaped . '%' . "'";
2121 }
2122 elsif($op eq 'ws') {
2123 my $tf;
2124 ($clause,$tf)=$self->_driver->search_clause_ws($field,$rha,$rha_escaped);
2125 if(!$clause) {
2126 $clause="$field LIKE '" . '%' . $rha_escaped . '%' . "'";
2127 $$post_process=1;
2128 }
2129 elsif(defined($tf)) {
2130 push(@$values,$tf);
2131 }
2132 }
2133 elsif($op eq 'wq') {
2134 my $tf;
2135 ($clause,$tf)=$self->_driver->search_clause_wq($field,$rha,$rha_escaped);
2136 if(!$clause) {
2137 $clause="$field LIKE '" . '%' . $rha_escaped . '%' . "'";
2138 $$post_process=1;
2139 }
2140 elsif(defined($tf)) {
2141 push(@$values,$tf);
2142 }
2143 }
2144 else {
2145 throw $self "_build_search_clause - unknown operator '$op'";
2146 }
2147  
2148 return $clause;
2149 }
2150  
2151 ###############################################################################
2152  
2153 =item _list_setup ()
2154  
2155 Sets up list reference fields - relation to upper hash. Makes sense
2156 only in derived objects.
2157  
2158 =cut
2159  
2160 sub _list_setup ($) {
2161 my $self=shift;
2162 my $glue=$$self->{'glue'};
2163 $glue || $self->throw("_setup_list - meaningless on Glue object");
2164 my $class_name=$$self->{'class_name'} || $self->throw("_setup_list - no class name given");
2165 my $base_name=$$self->{'base_name'} || $self->throw("_setup_list - no base class name given");
2166 $$self->{'connector_name'}=$glue->_connector_name($class_name,$base_name);
2167 $$self->{'class_description'}=$$glue->{'classes'}->{$class_name};
2168 $$self->{'key_name'}=$glue->_list_key_name($class_name,$base_name);
2169  
2170 my $kdesc=$$self->{'class_description'}->{'fields'}->{$$self->{'key_name'}};
2171 $$self->{'key_format'}=$kdesc->{'key_format'};
2172 $$self->{'key_length'}=$kdesc->{'key_length'} || 30;
2173 $$self->{'key_charset'}=$kdesc->{'key_charset'} || 'binary';
2174 $$self->{'key_unique_id'}=$kdesc->{'key_unique_id'};
2175 }
2176  
2177 ###############################################################################
2178  
2179 # Finds specific value unique ID for list object. Works only in derived
2180 # objects.
2181  
2182 sub _find_unique_id ($$) {
2183 my $self=shift;
2184 my $name=shift;
2185 my $key_name=$$self->{'key_name'} || $self->throw("_find_unique_id - no key name");
2186 my $connector_name=$$self->{'connector_name'};
2187 my $table=$$self->{'class_description'}->{'table'};
2188 $self->_driver->unique_id($table,
2189 $key_name,$name,
2190 $connector_name,$$self->{'base_id'});
2191 }
2192  
2193 ###############################################################################
2194  
2195 # Unlinks object from list. If object is not linked anywhere else calls
2196 # destroy() on the object first.
2197  
2198 sub _list_unlink_object ($$$) {
2199 my $self=shift;
2200 my $name=shift;
2201  
2202 my $object=$self->get($name) || $self->throw("_list_unlink_object - no object exists (name=$name)");
2203 my $class_desc=$object->_class_description();
2204  
2205 ##
2206 # Asking destroy to delete lists only, otherwise it will delete each
2207 # and every field separately thus being very very slow.
2208 #
2209 $object->destroy(1);
2210  
2211 ##
2212 # And now dropping the row itself.
2213 #
2214 $self->_driver->delete_row($class_desc->{'table'},
2215 $$object->{'unique_id'});
2216 }
2217  
2218 ##
2219 # Stores data object into list. Must be called on List object.
2220 #
2221 sub _list_store_object ($$$) {
2222 my $self=shift;
2223 my ($key_value,$value)=@_;
2224  
2225 ref($value) ||
2226 $self->throw("_list_store_object - value must be an object reference");
2227 $value->objname eq $$self->{'class_name'} ||
2228 $self->throw("_list_store_object - wrong objname ".$value->objname.", should be $self->{'class_name'}");
2229  
2230 my $desc=$value->_class_description;
2231 my @flist;
2232 foreach my $fn (keys %{$desc->{'fields'}}) {
2233 my $type=$desc->{'fields'}->{$fn}->{'type'};
2234 next if $type eq 'list';
2235 next if $type eq 'key';
2236 next if $type eq 'connector';
2237 push @flist, $fn;
2238 }
2239 my %fields;
2240 @fields{@flist}=$value->get(@flist) if @flist;
2241  
2242 my $table=$desc->{'table'};
2243 $table || $self->throw("_list_store_object - no table");
2244  
2245 ##
2246 # If there is no name for the object then it needs to be generated
2247 # according to key_format.
2248 #
2249 my $driver=$self->_driver;
2250 my $key_name=$$self->{'key_name'};
2251 if(!$key_value) {
2252 my $format=$$self->{'key_format'} || '<$RANDOM$>';
2253 my $uid=$$self->{'key_unique_id'};
2254 my $translate=sub {
2255 my ($kw,$opt)=@_;
2256 my $text='';
2257 if($kw eq 'RANDOM') {
2258 $text=XAO::Utils::generate_key($opt || 8);
2259 }
2260 elsif($kw eq 'AUTOINC') {
2261 $uid || throw $self "_list_store_object - no key_unique_id known, internal bug";
2262 my $seq=$driver->increment_key_seq($uid);
2263 $text=$opt ? sprintf('%0'.$opt.'u',$seq)
2264 : sprintf('%u',$seq);
2265 }
2266 elsif($kw eq 'GMTIME') {
2267 $text=time;
2268 }
2269 elsif($kw eq 'DATE') {
2270 my @t=localtime;
2271 $text=sprintf('%04u%02u%02u%02u%02u%02u',
2272 $t[5]+1900,$t[4]+1,$t[3],
2273 $t[2],$t[1],$t[0]);
2274 }
2275 else {
2276 throw $self "_list_store_object - unsupported key format '$format'";
2277 }
2278 return $text;
2279 };
2280 $key_value=sub {
2281 my $key=$format;
2282 $key=~s{<\$(\w+)(?:/(\w+))?\$>}
2283 {&$translate($1,$2)}ge;
2284 return $key;
2285 };
2286 }
2287  
2288 ##
2289 # Storing...
2290 #
2291 $key_value=$driver->store_row($table,
2292 $key_name,$key_value,
2293 $$self->{'connector_name'},$$self->{'base_id'},
2294 \%fields);
2295  
2296 return $key_value;
2297 }
2298  
2299 # Returns true if meta-data consistency has been checked at startup
2300 # (default is now not to check)
2301 #
2302 sub _consistency_checked($) {
2303 my $self=shift;
2304 return $self->_driver->consistency_checked;
2305 }
2306  
2307 # Adds new data field to the hash object.
2308 #
2309 sub _add_data_placeholder ($%) {
2310 my $self=shift;
2311 my $args=get_args(\@_);
2312  
2313 my $name=$args->{'name'};
2314 my $type=$args->{'type'};
2315  
2316 my $desc=$self->_class_description;
2317 my $table=$self->_class_description->{'table'};
2318 my $driver=$self->_driver;
2319  
2320 # Copying args to avoid destroying external hash
2321 #
2322 my %fdesc;
2323 @fdesc{keys %{$args}}=CORE::values %{$args};
2324 undef $args;
2325  
2326 # Checking if this is a hash in a list stored in some other hash
2327 # other then Global.
2328 #
2329 my $upper_class=$self->upper_class;
2330 my $connected=(!$upper_class || $upper_class eq 'FS::Global') ? 0 : 1;
2331  
2332 # Checking or setting the default value.
2333 #
2334 $fdesc{'default'}=$self->_field_default($name,\%fdesc,1);
2335  
2336 # Adding...
2337 #
2338 if($type eq 'words') {
2339 throw $self "- 'words' not supported any more";
2340 }
2341 elsif ($type eq 'text') {
2342 if(!$fdesc{'maxlength'}) {
2343 eprint "Default maxlength is deprecated for field '$name', type '$type'";
2344 $fdesc{'maxlength'}=100;
2345 }
2346  
2347 $fdesc{'charset'}||='binary';
2348  
2349 my $dl=length($fdesc{'default'});
2350 $dl <= 30 ||
2351 throw $self "- default text for '$name' is longer than 30 characters";
2352 $dl <= $fdesc{'maxlength'} ||
2353 throw $self "- default text for '$name' is longer than maxlength ($fdesc{'maxlength'})";
2354  
2355 $driver->add_field_text($table,$name,$fdesc{'index'},$fdesc{'unique'},
2356 $fdesc{'maxlength'},$fdesc{'default'},$fdesc{'charset'},$connected);
2357 }
2358 elsif ($type eq 'blob') {
2359 my $maxlength=$fdesc{'maxlength'} ||
2360 throw $self "($name) - no blob maxlength specified";
2361  
2362 my $dl=length($fdesc{'default'});
2363 $dl <= 30 ||
2364 throw $self "- default blob for '$name' is longer than 30 characters";
2365 $dl <= $maxlength ||
2366 throw $self "- default blob for '$name' is longer than maxlength ($maxlength)";
2367  
2368 $driver->add_field_text($table,$name,$fdesc{'index'},$fdesc{'unique'},
2369 $maxlength,$fdesc{'default'},'binary',$connected);
2370 }
2371 elsif ($type eq 'integer') {
2372 $fdesc{'minvalue'}//=-0x80000000;
2373  
2374 $fdesc{'maxvalue'}//=$fdesc{'minvalue'}<0 ? 0x7FFFFFFF : 0xFFFFFFFF;
2375  
2376 $fdesc{'minvalue'} <= $fdesc{'maxvalue'} ||
2377 throw $self "- minvalue $fdesc{'minvalue'} is above maxvalue $fdesc{'maxvalue'} for $name";
2378  
2379 $driver->add_field_integer($table,$name,$fdesc{'index'},$fdesc{'unique'},
2380 $fdesc{'minvalue'},$fdesc{'maxvalue'},$fdesc{'default'},$connected);
2381 }
2382 elsif ($type eq 'real') {
2383 $fdesc{'minvalue'}+=0 if defined($fdesc{'minvalue'});
2384 $fdesc{'maxvalue'}+=0 if defined($fdesc{'maxvalue'});
2385  
2386 !defined $fdesc{'minvalue'} || !defined $fdesc{'maxvalue'} || $fdesc{'minvalue'} <= $fdesc{'maxvalue'} ||
2387 throw $self "- minvalue $fdesc{'minvalue'} is above maxvalue $fdesc{'maxvalue'} for $name";
2388  
2389 $driver->add_field_real($table,$name,$fdesc{'index'},$fdesc{'unique'},
2390 $fdesc{'minvalue'},$fdesc{'maxvalue'},$fdesc{'scale'},$fdesc{'default'},$connected);
2391 }
2392 else {
2393 $self->throw("- unknown type '$type'");
2394 }
2395  
2396 ##
2397 # Updating in-memory data with our new field.
2398 #
2399 $desc->{'fields'}->{$name}=\%fdesc;
2400  
2401 ##
2402 # Updating Global_Fields
2403 #
2404 $driver->store_row('Global_Fields',
2405 'field_name',$name,
2406 'table_name',$table,
2407 { type => $fdesc{'type'},
2408 index => $fdesc{'unique'} ? 2 : ($fdesc{'index'} ? 1 : 0),
2409 default => $fdesc{'default'},
2410 maxlength => $fdesc{'maxlength'} || $fdesc{'scale'},
2411 maxvalue => $fdesc{'maxvalue'},
2412 minvalue => $fdesc{'minvalue'},
2413 charset => $fdesc{'charset'},
2414 });
2415 }
2416  
2417 # Adds list placeholder to the Hash object.
2418 #
2419 # It gets here when name was already checked for being correct and
2420 # unique.
2421 #
2422 sub _add_list_placeholder ($%) {
2423 my $self=shift;
2424 my $args=get_args(\@_);
2425  
2426 my $desc=$self->_class_description;
2427  
2428 my $name=$args->{'name'} || $self->throw("_add_list_placeholder - no 'name' argument");
2429 my $class=$args->{'class'} || $self->throw("_add_list_placeholder - no 'class' argument");
2430 my $key=$args->{'key'} || $self->throw("_add_list_placeholder - no 'key' argument");
2431 $self->check_name($key) || $self->throw("_add_list_placeholder - bad key name ($key)");
2432 my $connector;
2433 if($self->objname ne 'FS::Global') {
2434 $connector=$args->{'connector'} || 'parent_unique_id';
2435 $self->check_name($connector) ||
2436 $self->throw("_add_list_placeholder - bad connector name ($key)");
2437 }
2438  
2439 my $key_format=$args->{'key_format'} || '<$RANDOM$>';
2440 if($key_format !~ /<\$RANDOM(?:\/\d+)?\$>/ && $key_format !~ /<\$AUTOINC(?:\/\d+)?\$>/) {
2441 throw $self "_add_list_placeholder - key_format must include either <\$RANDOM\$> or <\$AUTOINC\$> ($key_format)";
2442 }
2443  
2444 my $key_length=$args->{'key_length'} || 30;
2445 $key_length < 255 ||
2446 throw $self "_add_list_placeholder - key_length ($key_length) must be less then 255";
2447  
2448 my $key_charset=$args->{'key_charset'} || 'binary';
2449  
2450 XAO::Objects->load(objname => $class);
2451  
2452 my $table=$args->{'table'};
2453 if(!$table) {
2454 $table=$class;
2455 $table =~ s/^Data:://;
2456 $table =~ s/::/_/g;
2457 $table =~ s/_{2,}/_/g;
2458 $table='fs' . $table;
2459 }
2460  
2461 my $driver=$self->_driver;
2462 my $glue=$self->_glue;
2463 if($$glue->{'classes'}->{$class}) {
2464 throw $self "_add_list_placeholder - multiple lists for the same class ($class) are not allowed";
2465 }
2466 else {
2467 foreach my $c (keys %{$$self->{'classes'}}) {
2468 $c->{'table'} ne $table ||
2469 throw $self "_add_list_placeholder - such table ($table) is already used";
2470 }
2471  
2472 $driver->add_table($table,$key,$key_length,$key_charset,$connector);
2473  
2474 $$glue->{'classes'}->{$class}={
2475 table => $table,
2476 fields => {
2477 $key => {
2478 type => 'key',
2479 refers => $self->objname,
2480 key_format => $key_format,
2481 key_length => $key_length,
2482 key_charset => $key_charset,
2483 }
2484 }
2485 };
2486 if(defined($connector)) {
2487 $$glue->{'classes'}->{$class}->{'fields'}->{$connector}={
2488 type => 'connector',
2489 refers => $self->objname,
2490 }
2491 }
2492  
2493 $driver->store_row('Global_Classes',
2494 'class_name',$class,
2495 'table_name',$table);
2496 }
2497  
2498 ##
2499 # Updating Global_Fields
2500 #
2501 $driver->store_row('Global_Fields',
2502 'field_name',$key,
2503 'table_name',$table,
2504 { type => 'key',
2505 refers => $self->objname,
2506 key_format => $key_format,
2507 key_seq => 1,
2508 maxlength => $key_length,
2509 charset => $key_charset,
2510 });
2511 $driver->store_row('Global_Fields',
2512 'field_name',$connector,
2513 'table_name',$table,
2514 { type => 'connector',
2515 refers => $self->objname
2516 }) if defined($connector);
2517 $desc->{'fields'}->{$name}=$args;
2518 $driver->store_row('Global_Fields',
2519 'field_name',$name,
2520 'table_name',$desc->{'table'},
2521 { type => 'list',
2522 refers => $class
2523 });
2524  
2525 ##
2526 # Setting unique_id of the row where key sequence is stored. This is
2527 # used later in storing auto-keyed objects.
2528 #
2529 my $key_uid=$driver->unique_id('Global_Fields',
2530 'field_name',$key,
2531 'table_name',$table);
2532 $$glue->{'classes'}->{$class}->{'fields'}->{$key}->{'key_unique_id'}=$key_uid;
2533 }
2534  
2535 ##
2536 # Drops data field from table.
2537 #
2538 sub _drop_data_placeholder ($$) {
2539 my $self=shift;
2540 my $name=shift;
2541  
2542 my $desc=$self->_class_description;
2543 my $table=$self->_class_description->{'table'};
2544 my $driver=$self->_driver;
2545  
2546 my $uid=$driver->unique_id('Global_Fields',
2547 'field_name',$name,
2548 'table_name',$table);
2549 $uid || $self->throw("_drop_data_placeholder - no description for $table.$name in the Global_Fields");
2550 $driver->delete_row('Global_Fields',$uid);
2551  
2552 ##
2553 # If that field was marked as 'unique' or 'index' then we need to
2554 # drop index as well.
2555 #
2556 my $upper_class=$self->upper_class;
2557 my $connected=(!$upper_class || $upper_class eq 'FS::Global') ? 0 : 1;
2558 my $index=$desc->{'fields'}->{$name}->{'index'};
2559 my $unique=$desc->{'fields'}->{$name}->{'unique'};
2560  
2561 $driver->drop_field($table,$name,$index,$unique,$connected);
2562  
2563 delete $desc->{'fields'}->{$name};
2564 }
2565  
2566 ##
2567 # Drops list placeholder. This is recursive - when you drop a list you
2568 # also drop all objects in that list and if these objects had any lists
2569 # on them - these lists too.
2570 #
2571 # Instead of dropping each object individually we just drop entire
2572 # tables here. Potentially very dangerous.
2573 #
2574 sub _drop_list_placeholder ($$;$$) {
2575 my ($self,$name,$recursive,$upper_class)=@_;
2576  
2577 my $desc=$recursive || $self->_field_description($name);
2578 my $class=$desc->{'class'};
2579 my $glue=$self->_glue;
2580 my $cdesc=$$glue->{'classes'}->{$class};
2581 my $cf=$cdesc->{'fields'};
2582  
2583 foreach my $fname (keys %{$cf}) {
2584 if($cf->{$fname}->{'type'} eq 'list') {
2585 $self->_drop_list_placeholder($fname,$cf->{$fname},$class);
2586 }
2587 }
2588  
2589 my $driver=$self->_driver;
2590 my $table=$cdesc->{'table'};
2591  
2592 my $uid=$driver->unique_id('Global_Classes',
2593 'class_name',$class,
2594 'table_name',$table);
2595 $uid || $self->throw("_drop_list_placeholder - no description for $table in the Global_Classes");
2596 $driver->delete_row('Global_Classes',$uid);
2597  
2598 my $ul=$driver->list_keys('Global_Fields','unique_id','table_name',$table);
2599 foreach $uid (@{$ul}) {
2600 $driver->delete_row('Global_Fields',$uid);
2601 }
2602  
2603 if(! $recursive) {
2604 my $selftable=$$glue->{'classes'}->{$self->objname}->{'table'};
2605 $uid=$driver->unique_id('Global_Fields',
2606 'field_name',$name,
2607 'table_name',$selftable);
2608 $uid || $self->throw("_drop_list_placeholder - no description for $selftable.$name in the Global_Fields");
2609 $driver->delete_row('Global_Fields',$uid);
2610 }
2611  
2612 delete $$glue->{'classes'}->{$class};
2613 delete $$glue->{'list_keys_cache'}->{$class};
2614 delete $$glue->{'connectors_cache'}->{$class};
2615  
2616 if($recursive) {
2617 delete $$glue->{'classes'}->{$upper_class}->{'fields'}->{$name};
2618 }
2619 else {
2620 delete $$glue->{'classes'}->{$self->objname}->{'fields'}->{$name};
2621 }
2622  
2623 $self->_driver->drop_table($table);
2624 }
2625  
2626 ###############################################################################
2627  
2628 =item check_name ($)
2629  
2630 Checks if the given name is a valid field name to be used in put() or
2631 get(). Should not be overriden unless you fully understand potential
2632 effects.
2633  
2634 Valid name must start from a letter and may consist from letters, digits
2635 and underscore symbol. Length is limited to 30 characters.
2636  
2637 Returns boolean value.
2638  
2639 =cut
2640  
2641 sub check_name ($$) {
2642 my $self=shift;
2643 my $name=shift;
2644 defined($name) && $name =~ /^[a-z][a-z0-9_]*$/i && length($name)<=30;
2645 }
2646  
2647 sub _check_name ($$) {
2648 my $self=shift;
2649 dprint ref($self) . "_check_name - obsolete, please change to 'check_name'";
2650 $self->check_name(@_);
2651 }
2652  
2653 sub normalize_path ($$) {
2654 my $self=shift;
2655 my $path=shift;
2656 $path=~s/\s//g;
2657 $path=~s/\/{2,}/\//g;
2658 $path;
2659 }
2660  
2661 ###############################################################################
2662 1;
2663 __END__