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

Legend:
Removed from v.1.2  
changed lines
  Added in v.1.43

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