/[cvs]/nfo/perl/libs/Data/Storage/Handler/Tangram.pm
ViewVC logotype

Diff of /nfo/perl/libs/Data/Storage/Handler/Tangram.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.15 by joko, Thu Dec 5 13:55:21 2002 UTC revision 1.44 by joko, Thu Dec 4 01:01:50 2003 UTC
# Line 3  Line 3 
3  #  $Id$  #  $Id$
4  #  #
5  #  $Log$  #  $Log$
6    #  Revision 1.44  2003/12/04 01:01:50  joko
7    #  + sendQuery now returns result even on crud=UPDATE
8    #
9    #  Revision 1.43  2003/07/02 11:07:12  jonen
10    #  re-activate filtering of results *after* results are fetched from tangram
11    #    (needed for e.g. UserManagment)
12    #
13    #  Revision 1.42  2003/07/01 23:24:17  joko
14    #  now using package before using function
15    #
16    #  Revision 1.41  2003/06/29 02:03:45  joko
17    #  fix:? initialize schema on startup
18    #
19    #  Revision 1.40  2003/06/25 22:57:54  joko
20    #  major rework of "sub sendQuery / sub getListFiltered": now should be capable of "sorting"
21    #
22    #  Revision 1.39  2003/06/06 11:40:40  jonen
23    #  fixed bug at 'getFilteredList'
24    #
25    #  Revision 1.38  2003/05/13 16:38:38  joko
26    #  problems with "tied" on 5.6.1/win32
27    #
28    #  Revision 1.37  2003/05/10 17:37:39  jonen
29    #  corrected last commit
30    #
31    #  Revision 1.36  2003/05/10 17:31:18  jonen
32    #  + added new functions related to 'create' item
33    #   - createNode()
34    #     # creates non-persistent 'deep dummy filled' object
35    #   - insertChildNode()
36    #     # inserts child node at given parent (child node haven't to exists,
37    #         createNode will be injected transparently)
38    #
39    #  Revision 1.35  2003/04/19 16:09:48  jonen
40    #  + added operator dispatching (currently for getting ref-type) at 'getListFiltered'
41    #
42    #  Revision 1.34  2003/04/11 01:18:53  joko
43    #  sendQuery:
44    #  + introduced crud action 'DELETE'
45    #
46    #  Revision 1.33  2003/04/09 06:07:43  joko
47    #  revamped 'sub sendQuery'
48    #
49    #  Revision 1.32  2003/04/08 22:52:22  joko
50    #  modified 'querySchema': better behaviour regarding filtering result
51    #
52    #  Revision 1.31  2003/04/05 21:24:09  joko
53    #  modified 'sub getChildNodes': now contains code from 'querySchema'
54    #
55    #  Revision 1.30  2003/03/27 15:31:14  joko
56    #  fixes to modules regarding new namespace(s) below Data::Mungle::*
57    #
58    #  Revision 1.29  2003/02/21 01:47:18  joko
59    #  purged old code
60    #  minor cosmetics
61    #
62    #  Revision 1.28  2003/02/20 20:20:26  joko
63    #  tried to get auto-disconnect working again - failed with that
64    #
65    #  Revision 1.27  2003/01/31 06:30:59  joko
66    #  + enabled 'sendQuery'
67    #
68    #  Revision 1.26  2003/01/30 22:29:47  joko
69    #  + fixed module usage (removed dependency on 'libp.pm')
70    #
71    #  Revision 1.25  2003/01/19 02:30:05  joko
72    #  + fix: modified call to '_initSchema'
73    #
74    #  Revision 1.24  2002/12/22 14:13:01  joko
75    #  + sub dropDb
76    #
77    #  Revision 1.23  2002/12/19 16:31:53  joko
78    #  +- renamed sub to 'rebuildDb'
79    #
80    #  Revision 1.22  2002/12/18 22:28:16  jonen
81    #  + added extended logging at 'getObjectByGuid()'
82    #
83    #  Revision 1.21  2002/12/16 22:20:49  jonen
84    #  + fixed bug at 'getObjectByGuid()'
85    #
86    #  Revision 1.20  2002/12/16 20:49:17  jonen
87    #  + added sub 'getObjectByGuid()'
88    #  + added functionality to use 'getObjectByGuid' at 'getObjectAsHash()'
89    #
90    #  Revision 1.19  2002/12/16 06:46:09  joko
91    #  + attempt to introduce a generic '_patchSchema' - cancelled!
92    #
93    #  Revision 1.18  2002/12/13 21:48:07  joko
94    #  + fix to 'sub sendQuery'
95    #
96    #  Revision 1.17  2002/12/12 02:51:09  joko
97    #  + cosmetics
98    #
99    #  Revision 1.16  2002/12/11 06:54:10  joko
100    #  + fix: encapsulated object-loading inside an 'eval'
101    #
102  #  Revision 1.15  2002/12/05 13:55:21  joko  #  Revision 1.15  2002/12/05 13:55:21  joko
103  #  + now utilizing 'object2hash' instead of 'var_deref'  #  + now utilizing 'expand' instead of 'var_deref'
104  #  + played around with having fresh-objects - no progress....  #  + played around with having fresh-objects - no progress....
105  #  #
106  #  Revision 1.14  2002/12/05 09:40:30  jonen  #  Revision 1.14  2002/12/05 09:40:30  jonen
# Line 77  use warnings; Line 173  use warnings;
173  use base ("Data::Storage::Handler");  use base ("Data::Storage::Handler");
174  use base ("Data::Storage::Handler::Abstract");  use base ("Data::Storage::Handler::Abstract");
175    
176  use Tangram;  
177  use Data::Dumper;  use Data::Dumper;
178  use libp qw( getNewPerlObjectByPkgName );  use Tangram;
179  use Data::Storage::Result::Tangram;  use Class::Tangram;
 use Data::Compare::Struct qw( isEmpty );  
 use Data::Transform::Deep qw( object2hash );  
 use Data::Transform::Encode qw( var2utf8 );  
180    
181    use DesignPattern::Object;
182    use Data::Storage::Result::Tangram;
183    use Data::Mungle::Compare::Struct qw( isEmpty );
184    use Data::Mungle::Transform::Deep qw( expand deep_copy merge_to );
185    
186  # get logger instance  # get logger instance
187  my $logger = Log::Dispatch::Config->instance;  my $logger = Log::Dispatch::Config->instance;
188    
189    #$Tangram::TRACE = *STDOUT;
190    
191  # this holds the complete instantiated schema from tangram  # this holds the complete instantiated schema from tangram
192  my $schema_tangram;  my $schema_tangram;
# Line 105  sub _initSchema { Line 203  sub _initSchema {
203    my $self = shift;    my $self = shift;
204    $logger->debug( __PACKAGE__ . "->_initSchema()" );    $logger->debug( __PACKAGE__ . "->_initSchema()" );
205    #if (!$schema_tangram) {    #if (!$schema_tangram) {
206      my $obj = getNewPerlObjectByPkgName($self->{locator}->{schema}, { EXPORT_OBJECTS => $self->{locator}->{classnames}, want_transactions => $self->{locator}->{want_transactions} } );      #my $obj = getNewPerlObjectByPkgName($self->{locator}->{schema}, { EXPORT_OBJECTS => $self->{locator}->{classnames}, want_transactions => $self->{locator}->{want_transactions} } );
207      $schema_tangram = $obj->getSchema();      my $obj = DesignPattern::Object->fromPackage($self->{locator}->{schema}, { 'EXPORT_OBJECTS' => $self->{locator}->{classnames}, 'want_transactions' => $self->{locator}->{want_transactions} } );
208        $schema_tangram = $obj->getSchema() if $obj;
209    #}    #}
210    if (!$schema_tangram) {    if (!$schema_tangram) {
211      $logger->error( __PACKAGE__ . "->_initSchema: No Schema available for $self->{schema}" );      $logger->error( __PACKAGE__ . "->_initSchema: No Schema available for $self->{locator}->{schema}." );
212      return 0;      return 0;
213    }    }
214      #$self->_patchSchema();
215    return 1;    return 1;
216  }  }
217    
218    sub _patchSchema {
219      my $self = shift;
220      foreach (keys %{$schema_tangram->{classes}}) {
221        next if $schema_tangram->{classes}->{$_}->{abstract};
222        #next if ($_ ne 'TsBankAccount');
223        #$_ ne 'AbstractAccount' &&
224        print "class: $_", "\n";
225    #print Dumper($schema_tangram->{classes}->{$_});
226        # create new string property named 'guid'
227        my $tstring = Tangram::String->new();
228        $tstring->{name} = $tstring->{col} = 'guid';
229        # inject property into schema
230        #$schema_tangram->{classes}->{$_}->{root}->{SPECS}->[0]->{fields}->{string}->{$tstring->{name}} = $tstring;
231        print Dumper($schema_tangram->{classes}->{$_}->{root}->{SPECS}->[0]->{fields});
232      }
233    }
234    
235  sub connect {  sub connect {
236    
237      my $self = shift;      my $self = shift;
238            
239      my $dsn = shift;      my $dsn = shift;
240    
241    #print Dumper($self);
242    #exit;
243    
244        # TODO: re-enable
245      $dsn ||= $self->{locator}->{dbi}->{dsn};      $dsn ||= $self->{locator}->{dbi}->{dsn};
       
246      $logger->debug( __PACKAGE__ . "->connect( dsn $dsn )" );      $logger->debug( __PACKAGE__ . "->connect( dsn $dsn )" );
247            
248      #my $storage = Tangram::Relational->connect( $schema, $dsn );      #my $storage = Tangram::Relational->connect( $schema, $dsn );
# Line 134  sub connect { Line 255  sub connect {
255  #    }  #    }
256    
257      return unless $self->_initSchema();      return unless $self->_initSchema();
258        #$self->_initSchema();
259    
260      # create the main tangram storage object      # create the main tangram storage object
261      #$self->{COREHANDLE} = Tangram::Relational->connect( $schema, $dsn );      #$self->{COREHANDLE} = Tangram::Relational->connect( $schema, $dsn );
# Line 160  sub connect { Line 282  sub connect {
282  sub getChildNodes {  sub getChildNodes {
283    
284    my $self = shift;    my $self = shift;
285    my @nodes;    my $mode = shift;
286      my $filter = shift;
287      
288      $mode ||= 'core';
289      $filter ||= 'all';
290      
291      $logger->debug( __PACKAGE__ . "->getChildNodes($mode)" );
292    
293    $logger->debug( __PACKAGE__ . "->getChildNodes()" );    if ($mode eq 'core') {
294    
295    # create new DBI - Data::Storage - object from already connected DBI::db - handle inside the current COREHANDLE      my @nodes;
296    #my $loc = new Data::Storage::Locator( type => "DBI", dbi => { db => $self->{COREHANDLE}->{db} });      
297    #my $loc = new Data::Storage::Locator( type => "DBI", COREHANDLE => $self->{COREHANDLE}->{db} );      # create new DBI - Data::Storage - object from already connected DBI::db - handle inside the current COREHANDLE
298          #my $loc = new Data::Storage::Locator( type => "DBI", dbi => { db => $self->{COREHANDLE}->{db} });
299    # todo: should we retrieve information from the schema here      #my $loc = new Data::Storage::Locator( type => "DBI", COREHANDLE => $self->{COREHANDLE}->{db} );
300    # rather than poorly getting table names from underlying dbi?      
301    my $storage = $self->_getSubLayerHandle();      # todo: should we retrieve information from the schema here
302    @nodes = @{$storage->getChildNodes()};      # rather than poorly getting table names from underlying dbi?
303    #$storage->_configureCOREHANDLE();      my $storage = $self->_getSubLayerHandle();
304  #print "getchildnodes\n";      @nodes = @{$storage->getChildNodes()};
305  #print Dumper($self);      #$storage->_configureCOREHANDLE();
306    #if (my $result = $self->sendCommand( 'SHOW TABLES;' ) ) {    #print "getchildnodes\n";
307      #print Dumper($self);
308        #if (my $result = $self->sendCommand( 'SHOW TABLES;' ) ) {
309        
310        # TODO: REVIEW
311        #$storage->disconnect();
312        
313        $self->{meta}->{childnodes} = \@nodes;
314    
315        return \@nodes;
316        
317    # TODO: REVIEW    } elsif ($mode eq 'root') {
318    #$storage->disconnect();      
319        # FIXME: this will return *all* known classes to 'Class::Tangram',
320        # which might not be what you expect since more than one instance
321        # of Tangram may be in memory and Class::Tangram seems to
322        # offer no methods to determine this or filter its result(s) according
323        # to a specific database.
324        my @object_names = Class::Tangram::known_classes();
325        my @concret_names;
326        my $o_cnt;
327        foreach (sort @object_names) {
328          push @concret_names, $_  if (!Class::Tangram::class_is_abstract($_));
329          $o_cnt++;
330        }
331    
332        if ($filter eq 'all') {
333          return \@object_names;
334        } elsif ($filter eq 'concrete') {
335          return \@concret_names;
336        }
337        
338    $self->{meta}->{childnodes} = \@nodes;    }
339        
   return \@nodes;  
340    
341  }  }
342    
   
343  sub testIntegrity {  sub testIntegrity {
344    
345    my $self = shift;    my $self = shift;
# Line 260  sub configureCOREHANDLE { Line 413  sub configureCOREHANDLE {
413    $logger->debug( __PACKAGE__ . "->configureCOREHANDLE" );    $logger->debug( __PACKAGE__ . "->configureCOREHANDLE" );
414    
415    #my $subLayer = $self->_getSubLayerHandle();    #my $subLayer = $self->_getSubLayerHandle();
416      #print Dumper($self);
417      #exit;
418    
419    # apply configured modifications    # apply configured modifications
420      if (exists $self->{dbi}->{trace_level} && exists $self->{dbi}->{trace_file}) {      if (exists $self->{dbi}->{trace_level} && exists $self->{dbi}->{trace_file}) {
# Line 325  sub retreatSchema { Line 480  sub retreatSchema {
480    return $ok;    return $ok;
481  }  }
482    
483  sub rebuildDbAndSchema {  sub rebuildDb {
484    my $self = shift;    my $self = shift;
485    $logger->info( __PACKAGE__ . "->rebuildDbAndSchema()" );    $logger->info( __PACKAGE__ . "->rebuildDb()" );
486    my @results;    my @results;
487    
488    # sum up results (bool (0/1)) in array    # sum up results (bool (0/1)) in array
# Line 362  sub getListFiltered { Line 517  sub getListFiltered {
517    # redirect to unfiltered mode    # redirect to unfiltered mode
518    #return $self->getListUnfiltered(@_);    #return $self->getListUnfiltered(@_);
519    
520    my $nodename = shift;    my $in = {};
521    my $filters = shift;    $in->{nodename} = shift;
522      $in->{filters} = shift;
523      $in->{sorting} = shift;
524      
525    my @results;    my @results;
526    $logger->debug( __PACKAGE__ . "->getListFiltered( nodename => '" . $nodename . "' )" );    $logger->debug( __PACKAGE__ . "->getListFiltered( nodename => '" . $in->{nodename} . "' )" );
527    
528    #print Dumper($filters);    #print Dumper($filters);
529    
530      # 1. "Remote Object Handle" - get set of objects from odbms by object name
531      my $remote = $self->{_COREHANDLE}->remote($in->{nodename});
532      
533      # 2. Transfer $in to $orm_query
534      my $orm_query = {};
535        
536      # 2.a. Filters
537    my @tfilters;    my @tfilters;
538      my $orm_filter = undef;
539        
540    foreach my $filter (@$filters) {    foreach my $filter (@{$in->{filters}}) {
541        
542      # get filter - TODO: for each filter      # get filter - TODO: for each filter
543      #my $filter = $filters->[0];      #my $filter = $filters->[0];
544      
545      # build filter      # 1. The parts of a filter source entry
546      my $lexpr = $filter->{key};      my $lexpr = $filter->{key};
547      #my $op = $filter->{op};      #my $op = $filter->{op};
548      my $op = '=';      my $op = '=';
549      my $rexpr = $filter->{val};      my $rexpr = $filter->{val};
550      my $tight = 100;      my $tight = 100;
551    
552        # 2. Build filter target entry
553            
554    #  my $tfilter = Tangram::Filter->new(      # Test 1 - didn't work out!
555    #    expr => "t1.$lexpr $op '$rexpr'",      #  my $tfilter = Tangram::Filter->new(
556    #    tight => $tight,      #    expr => "t1.$lexpr $op '$rexpr'",
557    #    objects => $objects,      #    tight => $tight,
558    #  );      #    objects => $objects,
559          #  );
560      # HACK: build eval-string (sorry) to get filtered list - please give advice here  
561      push @tfilters, '$remote->{' . $filter->{key} . '}' . " $filter->{op} '$filter->{val}'";      my $orm_filter_tmp = undef;
562        # was:
563        # TODO: is_op?
564        # dispatch un-common operators if exists
565        if ($filter->{op} eq "ref") {
566          # do nothing, results will be filtered later cause 'tangram-filter' doesn't support 'ref' query
567          #print "Filter->op eq 'ref'.\n";
568          #push @tfilters, 'ref($remote->{' . $filter->{key} . '})' . " eq '$filter->{val}'";
569        } else {
570          # HACK: build eval-string (sorry) to get filtered list - please give advice here
571          #push @tfilters, '$remote->{' . $filter->{key} . '}' . " $filter->{op} '$filter->{val}'";
572          # better: calculate expression right here!
573          #push @tfilters, '$remote->{' . $filter->{key} . '}' . " $filter->{op} '$filter->{val}'";
574          
575          #print "key: ", $filter->{key}, "\n";
576          
577          my $left = $remote->{$filter->{key}};
578          #my $r = Tangram::Expr->new( 'string' => "'" . $filter->{val} . "'" );
579          my $right = $filter->{val};
580          my $op = $filter->{op};
581          $orm_filter_tmp = $left->$op($right);
582        }
583    
584        if (not $orm_filter) {
585          $orm_filter = $orm_filter_tmp;
586        } else {
587          $orm_filter = $orm_filter->and($orm_filter_tmp);
588        }
589    
590    }    }
591    
592    my $tfilter = join(' & ', @tfilters);    $orm_query->{filter} = $orm_filter;
593    
   # get set of objects from odbms by object name  
   my $remote = $self->{_COREHANDLE}->remote($nodename);  
     
594    # was:    # was:
595    #@results = $self->{COREHANDLE}->select($object_set, $tfilter);  
596      # 2.b. sorting [new as of 2003-06-17]
597      if ($in->{sorting}) {
598        my $sorting_rules = [];
599        my $sorting_order = 'ASC';
600        foreach my $sorting_column (keys %{$in->{sorting}}) {
601          $sorting_order = $in->{sorting}->{$sorting_column} if $in->{sorting}->{$sorting_column};
602          push @$sorting_rules, Tangram::Expr->new( 'string' => $sorting_column );
603        }
604        $orm_query->{order} = $sorting_rules;
605        if ($sorting_order eq 'DESC') {
606          $orm_query->{desc} = 1;
607        }
608      }
609    
610    
611      # 3. build and issue query - return result as Tangram::Cursor
612      
613      # coerce hash into array (This is valid in Perl)
614      my @orm_query_args = %$orm_query;
615      # send query (arguments) to orm
616      @results = $self->{_COREHANDLE}->select($remote, @orm_query_args);
617      
618      #my $cursor = $self->{_COREHANDLE}->cursor($remote, @orm_query_args);
619      #return $cursor;
620      #print Dumper(@results);
621    
622    # is:    # is:
623    # HACK: build eval-string (sorry) to get filtered list - please give advice here    # HACK: build eval-string (sorry) to get filtered list - please give advice here
624    my $evalstring = 'return $self->{_COREHANDLE}->select($remote, ' . $tfilter . ');';      #my $evalstring = 'return $self->{_COREHANDLE}->select($remote, ' . $tfilter . $sorting . ');';
625          #print "eval: $evalstring", "\n";
626    # get filtered list/set      # get filtered list/set
627    @results = eval($evalstring);      #@results = eval($evalstring);
628    die $@ if $@;      #die $@ if $@;
629    
630      # filter results - NEEDED for e.g. UserManagment !!
631      if ($in->{filters}->[0]->{op} && ($in->{filters}->[0]->{op} eq "ref")) {
632          #print "Filter->op eq 'ref'.\n";
633          my $att_name = $in->{filters}->[0]->{key};
634          my $att_val = $in->{filters}->[0]->{val};
635          my @filtered;
636          foreach(@results) {
637            if(ref($_->{$att_name}) eq $att_val) {
638              push @filtered, $_;
639            }
640          }
641          @results = @filtered;
642      }
643    
644      #print "results: " . Dumper(\@results);
645        
646    return \@results;    return \@results;
647  }  }
# Line 423  sub createCursor { Line 656  sub createCursor {
656    
657  sub createSet {  sub createSet {
658    my $self = shift;    my $self = shift;
659    #print "-" x 80, "\n";
660    #print Dumper(@_);
661    my @objects = @_;    my @objects = @_;
662    my $rh = Set::Object->new();    my $rh = Set::Object->new();
663    foreach (@objects) {    foreach (@objects) {
664      #print Dumper($_);      if (!isEmpty($_)) {
665      $rh->insert($_) if !isEmpty($_);  #print Dumper($_);
666          $rh->insert($_);
667        }
668    }    }
669    #print Dumper($rh->members());    #print Dumper($rh->members());
670    my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $rh );    my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $rh );
671    return $result;    return $result;
672  }  }
673    
674    sub createResult {
675      my $self = shift;
676      my $rh = shift;
677      my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $rh );
678      return $result;
679    }
680    
681  sub sendQuery {  sub sendQuery {
682    my $self = shift;    my $self = shift;
683    my $query = shift;    my $query = shift;
   #my $sql = "SELECT cs FROM $self->{metainfo}->{$descent}->{node} WHERE $self->{metainfo}->{$descent}->{IdentProvider}->{arg}='$self->{entry}->{source}->{ident}';";  
   #my $result = $self->{metainfo}->{$descent}->{storage}->sendCommand($sql);  
684    
685    #print Dumper($query);    #print Dumper($query);
686    
687    # HACK: special case: querying by id does not translate into a common tangram query    # type = ITEM|LIST|TRANSPARENT
688    # just load the object by given id(ent)    my $type = '';
689    if ($query->{criterias}->[0]->{key} eq 'id' && $query->{criterias}->[0]->{op} eq 'eq') {    # mode = OID|SPECIAL
690      #print "LOAD!!!", "\n";    my $mode = '';
691      #exit;    my $ident = '';
692      #return Set::Object->new( $self->{COREHANDLE}->load($query->{criterias}->[0]->{val}) );    my $crud = '';
693      my $ident = $query->{criterias}->[0]->{val};    
694  #print "load obj", "\n";    
695      #return $self->createSet() if $ident == 5;    # dispatch type and mode
696      my $object = $self->{_COREHANDLE}->load($ident);    
697  #print "get id", "\n";      # defaults - 1
698      my $oid = $self->{_COREHANDLE}->id($object);      if ($query->{options}) {
699      return $self->createSet($object);        $crud = $query->{options}->{crud};
700      #return $self->createSet( $self->{COREHANDLE}->load('300090018') );        $crud ||= $query->{options}->{action};
701    }      }
702    
703    die("This should not be reached for now - redirect to \$self->getListFiltered() here!");      # defaults - 2
704        $type ||= 'TRANSPARENT';
705    # TODO: do a common tangram query here      $crud ||= 'RETRIEVE';
706    
707    my @crits;      if ($query->{options}->{OID}) {
708    foreach (@{$query->{criterias}}) {        $type = 'ITEM';
709      my $op = '';        $mode = 'OID';
710      $op = '=' if lc $_->{op} eq 'eq';        $ident = $query->{options}->{OID};
711      push @crits, "$_->{key}$op'$_->{val}'";      
712    }      } elsif (my $guid = $query->{options}->{GUID}) {
713    my $subnodes = {};        $type = 'TRANSPARENT';
714    map { $subnodes->{$_}++ } @{$query->{subnodes}};        $query->{criterias} = [ { key => 'guid', op => 'eq', val => $guid } ];    
715    # HACK: this is hardcoded ;(    expand possibilities!  
716    #my $crit = join(' AND ', @crits);      # if operator is different (dispatcher for 'getListFiltered')
717    #my $sql = hash2Sql($query->{node}, $subnodes, 'SELECT', $crit);      } elsif (my $op = $query->{options}->{op}) {
718    #return $self->sendCommand($sql);        $type = 'TRANSPARENT';
719    #my $h = $self->{COREHANDLE}->remote($query->{node});        $query->{criterias} = [ { key => $query->{options}->{meta_label}, op => $op, val => $query->{options}->{meta_value} } ];    
720    #my $res = $self->{COREHANDLE}->select($h, $h->{);  
721    return $self->createCursor($query->{node});      }
722      
723        # HACK: special case: querying by id does not translate into a common tangram query
724        # just load the object by given identifier (OID) named 'id' - this is required by Data::Transfer::Sync!
725        if ($query->{criterias} && ($query->{criterias}->[0]->{key} eq 'id' && $query->{criterias}->[0]->{op} eq 'eq')) {
726          $type = 'ITEM';
727          $mode = 'SPECIAL.SYNC';
728          $ident = $query->{criterias}->[0]->{val};
729        }
730      
731    
732      # execute query
733      my $result;
734    
735      if ($type eq 'ITEM' && $ident) {
736    
737        if ($mode eq 'OID') {    
738          # TODO: review this case!
739          $result = $self->getObject($ident, $query->{options});
740        
741        } elsif ($mode eq 'SPECIAL.SYNC') {
742    
743          # V1 - failed
744          #return Set::Object->new( $self->{COREHANDLE}->load($query->{criterias}->[0]->{val}) );
745      
746          # hmm....
747          #return $self->createSet() if $ident == 5;
748          
749          # Unload single object before doing any further operations to
750          # expect a "fresh" object from orm when performing the next calls.
751          $self->{_COREHANDLE}->unload($ident);
752          
753          # Load object from orm.
754          my $object = $self->{_COREHANDLE}->load($ident);
755      
756          # determine object identifier (OID)
757          my $oid = $self->{_COREHANDLE}->id($object);
758          
759          # encapsulate into result/response container and return this one
760          $result = $self->createSet($object);
761          
762          # debugging
763          #$result = $self->createSet( $self->{COREHANDLE}->load('300090018') );
764    
765        }
766        
767      
768      } elsif ($type eq 'TRANSPARENT') {
769    
770        if ($crud eq 'RETRIEVE') {
771    
772          my $list = $self->getListFiltered($query->{node}, $query->{criterias}, $query->{sorting});
773          #return $list;
774          return $self->createResult($list);
775          
776          #return $self->createSet($object);
777          #return $self->createSet($list);
778          return $self->createSet(@$list);
779        
780          #die("This should not be reached for now - redirect to \$self->getListFiltered() here!");
781        
782          # try a generic tangram query here
783          # TODO: try to place an oql on top of that (search.cpan.org!)
784          my @crits;
785          foreach (@{$query->{criterias}}) {
786            my $op = '';
787            $op = '=' if lc $_->{op} eq 'eq';
788            push @crits, "$_->{key}$op'$_->{val}'";
789          }
790          my $subnodes = {};
791          map { $subnodes->{$_}++ } @{$query->{subnodes}};
792          # HACK: this is hardcoded ;(    expand possibilities!
793          #my $crit = join(' AND ', @crits);
794          #my $sql = hash2Sql($query->{node}, $subnodes, 'SELECT', $crit);
795          #return $self->sendCommand($sql);
796          #my $h = $self->{COREHANDLE}->remote($query->{node});
797          #my $res = $self->{COREHANDLE}->select($h, $h->{);
798          $result = $self->createCursor($query->{node});
799    
800        } elsif ($crud eq 'UPDATE') {
801    
802          # Patch current query to be a loader (e.g. change action, remove payload) ...
803          my $childquery = deep_copy($query);
804          $childquery->{options}->{crud} = 'RETRIEVE';
805          delete $childquery->{payload};
806    
807          # ... to use it to fetch a fresh object using ourselves (sendQuery).
808          my $cursor = $self->sendQuery($childquery);
809          my $status = $cursor->getStatus();
810          my $object = $cursor->getNextEntry();
811    
812          # Merge values and apply value modifiers.
813          my $options = { utf8 => 1, php => 1 };
814          merge_to($object, $query->{payload}, $options);
815    
816          #print Dumper($object);
817          
818          # Execute update operation at orm.
819          $self->update($object);
820          $result = $self->createResult([ $object ]);
821        
822        } elsif ($crud eq 'DELETE') {
823    
824          # Patch current query to be a loader (e.g. change action) ...
825          my $childquery = deep_copy($query);
826          $childquery->{options}->{crud} = 'RETRIEVE';
827    
828          # ... to use it to fetch a fresh object using ourselves (sendQuery).
829          my $cursor = $self->sendQuery($childquery);
830          my $status = $cursor->getStatus();
831          my $object = $cursor->getNextEntry();
832    
833          $self->erase($object);
834    
835        } elsif ($crud eq 'CREATE') {
836          
837          my $nodename = $query->{node};      
838          my $newnode = $self->createNode($nodename);
839          my $id = $self->{_COREHANDLE}->insert($newnode);
840      
841          print "Saved new node $nodename with GUID $newnode->{guid}, OID '$id': " . Dumper($newnode) . "\n";
842          
843          return $newnode;
844    
845        }
846    
847      }
848    
849      return $result;
850    
851  }  }
852    
853  sub eraseAll {  sub eraseAll {
# Line 497  sub getObject { Line 868  sub getObject {
868    my $self = shift;    my $self = shift;
869    my $oid = shift;    my $oid = shift;
870    my $options = shift;    my $options = shift;
871    # TODO: create a deep_unload method  
872      # TODO: create a deep_unload method (currently _all_ objects are unloaded)
873    # unload($oid) will only unload object, not deep object hashes    # unload($oid) will only unload object, not deep object hashes
874    $self->{_COREHANDLE}->unload() if($options->{destroy});    $self->{_COREHANDLE}->unload() if ($options->{destroy});
875    
876    # TODO: review this    # TODO: review this
877    #if (!$self->{COREHANDLE}) { return; }    #if (!$self->{COREHANDLE}) { return; }
878    return $self->{_COREHANDLE}->load($oid);  
879      # TODO: review this
880      my $object = eval('$self->{_COREHANDLE}->load($oid);');
881      print $@, "\n" if $@;
882    
883      return $object if $object;
884  }  }
885    
886  sub getObjectAsHash {  sub getObjectByGuid_old {
887    my $self = shift;    my $self = shift;
888    my $oid = shift;    my $guid = shift;
889    my $options = shift;    my $options = shift;
890    my $obj = $self->getObject($oid, $options);    
891      # Guid and Classname is needed
892      if(!$guid || !$options->{classname}) {
893       $logger->error( __PACKAGE__ . "->getObjectByGuid: No 'guid' OR no Classname in options hash was given but needed!" );
894        return;
895      }
896      
897      # TODO: create a deep_unload method (currently _all_ objects are unloaded)
898      # unload($oid) will only unload object, not deep object hashes
899      $self->{_COREHANDLE}->unload() if ($options->{destroy});
900    
901      # search for object with given Classname and Guid
902      my $obj_tmp = $self->{_COREHANDLE}->remote($options->{classname});
903      my @result = $self->{_COREHANDLE}->select($obj_tmp, $obj_tmp->{guid} eq $guid);
904      
905      # we searched for global unique identifer of some object,
906      # so I think we can trust there would be only one result
907      if($result[0]) {
908        return $result[0];
909      } else {
910        $logger->error( __PACKAGE__ . "->getObjectByGuid: No Object with Classname $options->{classname} and GUID $guid found!" );
911        return;
912      }
913      
914    }
915    
916    sub getObjectAsHash_old {
917      my $self = shift;
918      my $oid = shift;
919      my $options = shift;  
920      my $obj;
921      
922      if($options->{guid}) {
923        $obj = $self->getObjectByGuid($oid, $options);
924      } else {
925        $obj = $self->getObject($oid, $options);
926      }
927        
928    # build options (a callback to unload autovivified objects) for 'expand'    # build options (a callback to unload autovivified objects) for 'expand'
929    # TODO: use $logger to write to debug here!    # TODO: use $logger to write to debug here!
930    my $cb; # = sub {};    my $cb; # = sub {};
931    
932      # deactivated way to get rid of used instances, if requested
933  =pod  =pod
934    if ($options->{destroy}) {      if ($options->{destroy}) {
935      $options->{cb}->{destroy} = sub {        $options->{cb}->{destroy} = sub {
936        print "================ DESTROY", "\n";          print "================ DESTROY", "\n";
937        my $object = shift;          my $object = shift;
938        #print Dumper($object);          #print Dumper($object);
939        $self->{_COREHANDLE}->unload($object);          $self->{_COREHANDLE}->unload($object);
940        #undef($object);          #undef($object);
941      };        };
942    }      }
943  =cut  =cut
944    
945    my $hash = object2hash($obj, $options);    my $hash = expand($obj, $options);
946    #$options->{cb}->{destroy}->($obj);  
947    #$self->{_COREHANDLE}->unload($obj);    # old (unsuccessful) attempts to get rid of used instances, if requested
948      
949    # convert values in hash to utf8 to be ready for (e.g.) encapsulation in XML      # V1:
950    # now done in object2hash      #$options->{cb}->{destroy}->($obj);
951    #var2utf8($hash) if ($options->{utf8});      #$self->{_COREHANDLE}->unload($obj);
952        
953    # old (wrong) attempts to get rid of used instances, if requested      # V2:
954      #$obj->clear_refs;      #$obj->clear_refs;
955      #$self->{COREHANDLE}->unload($obj) if($options->{destroy});      #$self->{COREHANDLE}->unload($obj) if($options->{destroy});
956      #$obj->DESTROY;      #$obj->DESTROY;
# Line 552  sub getCOREHANDLE { Line 968  sub getCOREHANDLE {
968    return $self->{_COREHANDLE};    return $self->{_COREHANDLE};
969  }  }
970    
971    sub dropDb {
972      my $self = shift;
973      my $storage = $self->_getSubLayerHandle();
974      return $storage->dropDb();
975    }
976    
977    sub testAvailability {
978      my $self = shift;
979      my $storage = $self->_getSubLayerHandle();
980      return $storage->testAvailability();
981    }
982    
983    sub disconnect2 {
984      my $self = shift;
985      my $storage = $self->_getSubLayerHandle();
986      print "DISC!", "\n";
987    
988      my $storage_ll = $storage->{_COREHANDLE};
989      $storage_ll->disconnect();
990      
991      print Dumper($storage);
992      exit;
993      
994      #$self->{_COREHANDLE}
995      #$storage->disconnect();
996      $self->{dataStorageLayer}->disconnect();
997    }
998    
999    
1000    sub createNode {
1001      my $self = shift;
1002      my $classname = shift;
1003    
1004      my $obj = $classname->new();
1005      
1006      my $attr_options = Class::Tangram::attribute_options($classname);
1007      #print "Attribute Options: " . Dumper($attr_options);
1008    
1009      my $attr_types = Class::Tangram::attribute_types($classname);
1010      #print "Attribute Types: " . Dumper($attr_types);
1011      
1012      foreach(keys %{$attr_types}) {
1013        if($attr_types->{$_} eq 'string') {
1014          $obj->{$_} = '';
1015        } elsif($attr_types->{$_} eq 'int') {
1016          $obj->{$_} = 0;
1017        } elsif($attr_types->{$_} eq 'real') {
1018          $obj->{$_} = 0;
1019        } elsif($attr_types->{$_} eq 'rawdatetime') {
1020          $obj->{$_} = '0000-00-00 00:00:00';
1021        } elsif($attr_types->{$_} eq 'ref') {
1022          if($attr_options->{$_}->{class}) {
1023            $obj->{$_} = $self->createNode($attr_options->{$_}->{class});
1024          } else {
1025            #$obj->{$_} = undef();
1026          }
1027        } elsif($attr_types->{$_} eq 'iarray') {
1028            $obj->{$_} = [ ];
1029        } elsif($attr_types->{$_} eq 'hash') {
1030            $obj->{$_} = {  };
1031        } elsif($attr_types->{$_} eq 'flat_hash') {
1032            $obj->{$_} = { };
1033        }
1034      }
1035      
1036      #print "New Object: " . Dumper($obj);
1037      
1038      return $obj;
1039    }
1040    
1041    
1042      sub insertChildNode {
1043        my $self = shift;
1044        my $child_entry = shift;
1045        my $query_args = shift;
1046        
1047        my $core = $self->{_COREHANDLE};
1048        my $nodename = $query_args->{nodename};
1049        
1050        # get parent object
1051        my $query = {
1052              node => $query_args->{parent}->{nodename},
1053              options => { GUID => $query_args->{parent}->{guid}, },
1054              };
1055        my $cursor = $self->sendQuery($query);
1056        my $parent = $cursor->getNextEntry();
1057    
1058        # debug
1059        #print "Parent_org: " . Dumper($parent);
1060            
1061        # Create child node object if isn't already done
1062        # ($child_entry have to be the class name then...)
1063        if(!ref($child_entry)) {
1064          $child_entry = $self->createNode($child_entry);
1065          # it could be insert 'manually' or will be insert 'transparent' if parent will be updated
1066          #$core->insert($child_entry);
1067          #print "Create child object [$nodename]: " . Dumper($child_entry);
1068        }
1069    
1070        # get reference of tied node (seems, only on Linux node's are tied!!)
1071        my $tied_node = tied $parent->{$nodename};
1072    
1073        # insert/change child entry at parent
1074        #print "reference: " . ref($parent->{$nodename}) . "\n";
1075        if(ref($parent->{$nodename}) eq 'ARRAY') {
1076          # (seems, only on Linux node's are tied!!)
1077          if($tied_node) {
1078            # all tangram types are tied as 'SCALAR' with special 'FETCH', 'STORE' methods per type,
1079            # so a 'PUSH' is not implemented (which could be then done transparently)
1080            my $array = $tied_node->FETCH;
1081            push @$array, $child_entry;
1082            $tied_node->STORE($array);
1083            # node will be normaly untied at 'STORE'
1084            if(tied $parent->{$nodename}) { print "already tied !!\n"; }
1085            else { undef $tied_node; }
1086          } else {
1087            push @{$parent->{$nodename}}, $child_entry;
1088          }
1089        }
1090        elsif(ref($parent->{$nodename}) eq 'HASH') {
1091          if(my $key = $query_args->{hash_key}) {
1092            # (seems, only on Linux node's are tied!!)
1093            if($tied_node) {
1094              # same problem as with 'ARRAY':
1095              # all tangram types are tied as 'SCALAR' with special 'FETCH', 'STORE' methods per type.
1096              my $hash = $tied_node->FETCH;
1097              $hash->{$key} = $child_entry;
1098              $tied_node->STORE($hash);
1099              # node will be normaly untied at 'STORE'
1100              if(tied $parent->{$nodename}) { print "already tied !!\n"; }
1101              else { undef $tied_node; }
1102            } else {
1103              $parent->{$nodename}->{$key} = $child_entry;
1104            }
1105          } else {
1106           print "ERROR: No HASH KEY given, so not able to insert hash entry!";
1107          }
1108        }
1109        else {
1110          $parent->{$nodename} = $child_entry;
1111        }
1112    
1113        # debug
1114        #print "Parent_new: " . Dumper($parent);
1115        
1116        # save parent
1117        $core->update($parent);
1118        
1119        # debug
1120        #print "Saved Parent: ". Dumper($parent);
1121        
1122        return $child_entry;
1123      }
1124    
1125    
1126  1;  1;
1127    __END__

Legend:
Removed from v.1.15  
changed lines
  Added in v.1.44

MailToCvsAdmin">MailToCvsAdmin
ViewVC Help
Powered by ViewVC 1.1.26 RSS 2.0 feed