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

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

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