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

Legend:
Removed from v.1.9  
changed lines
  Added in v.1.42

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