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

Legend:
Removed from v.1.4  
changed lines
  Added in v.1.49

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