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

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

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