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

Legend:
Removed from v.1.10  
changed lines
  Added in v.1.48

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