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

Legend:
Removed from v.1.11  
changed lines
  Added in v.1.40

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