/[cvs]/nfo/perl/libs/Data/Storage/Handler/Tangram.pm
ViewVC logotype

Contents of /nfo/perl/libs/Data/Storage/Handler/Tangram.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.46 - (show annotations)
Thu May 6 12:54:34 2004 UTC (20 years, 2 months ago) by jonen
Branch: MAIN
Changes since 1.45: +11 -3 lines
+ bugfix related to multiple select-'filter'

1 ############################################
2 #
3 # $Id: Tangram.pm,v 1.45 2003/12/14 01:48:36 jonen Exp $
4 #
5 # $Log: Tangram.pm,v $
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
161 # + removed dependency from tsobj.pm, schema is now independent
162 # + sub getNewPerlObjectByPkgName
163 # + sub deploySchema
164 # + sub retreatSchema
165 #
166 # Revision 1.1 2002/10/10 03:44:07 cvsjoko
167 # + new
168 #
169 ############################################
170
171
172 package Data::Storage::Handler::Tangram;
173
174 use strict;
175 use warnings;
176
177 use base ("Data::Storage::Handler");
178 use base ("Data::Storage::Handler::Abstract");
179
180
181 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
191 my $logger = Log::Dispatch::Config->instance;
192
193 #$Tangram::TRACE = *STDOUT;
194
195 # this holds the complete instantiated schema from tangram
196 my $schema_tangram;
197
198 sub getMetaInfo {
199 my $self = shift;
200 $logger->debug( __PACKAGE__ . "->getMetaInfo()" );
201 return {
202 'disconnectMethod' => 'disconnect',
203 };
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 {
240
241 my $self = shift;
242
243 my $dsn = shift;
244
245 #print Dumper($self);
246 #exit;
247
248 # TODO: re-enable
249 $dsn ||= $self->{locator}->{dbi}->{dsn};
250 $logger->debug( __PACKAGE__ . "->connect( dsn $dsn )" );
251
252 #my $storage = Tangram::Relational->connect( $schema, $dsn );
253 #my $storage = Tangram::mysql->connect( $schema, $dsn );
254 #$storage = Tangram::Relational->connect( Project->schema, $dsn );
255
256 # if (!testDsn($dsn)) {
257 # croak("Database at \"$dsn\" is not available");
258 # return;
259 # }
260
261 return unless $self->_initSchema();
262 #$self->_initSchema();
263
264 # create the main tangram storage object
265 #$self->{COREHANDLE} = Tangram::Relational->connect( $schema, $dsn );
266 $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();
274 #$self->{STORAGEHANDLE_UNDERLYING}->_configureCOREHANDLE();
275 #$self->_configureUnderlyingStorage;
276
277 # ..... encapsulation wins!
278 $self->configureCOREHANDLE();
279
280 $self->{locator}->{status}->{connected} = 1;
281
282 return 1;
283
284 }
285
286 sub getChildNodes {
287
288 my $self = shift;
289 my $mode = shift;
290 my $filter = shift;
291
292 $mode ||= 'core';
293 $filter ||= 'all';
294
295 $logger->debug( __PACKAGE__ . "->getChildNodes($mode)" );
296
297 if ($mode eq 'core') {
298
299 my @nodes;
300
301 # 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 return \@nodes;
320
321 } elsif ($mode eq 'root') {
322
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 }
343
344
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
370
371 sub _getSubLayerHandle {
372
373 my $self = shift;
374
375 $logger->debug( __PACKAGE__ . "->_getSubLayerHandle()" );
376
377 #print Dumper($self);
378
379 # hack, make more generic!
380 if (!$self->{dataStorageLayer}) {
381 $logger->debug( __PACKAGE__ . "->_getSubLayerHandle() creating new dataStorageLayer" );
382 #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();
386 #$self->{STORAGE_UNDER_THE_HOOD}->_configureCOREHANDLE();
387 }
388
389 #print Dumper($self->{STORAGE_UNDER_THE_HOOD});
390
391 return $self->{dataStorageLayer};
392
393 }
394
395 sub _configureUnderlyingStorage {
396
397 my $self = shift;
398
399 $logger->debug( __PACKAGE__ . "->_configureUnderlyingStorage" );
400
401 $self->_configureCOREHANDLE_DBI();
402 return;
403
404 foreach my $key (keys %{$self->{dbi}}) {
405 my $val = $self->{dbi}->{$key};
406 print "entry: $key; $val", "\n";
407 $self->{_COREHANDLE}->{db}->{$key} = $val;
408 }
409 #print Dumper($self->{COREHANDLE}->{db});
410 }
411
412
413 sub configureCOREHANDLE {
414
415 my $self = shift;
416
417 $logger->debug( __PACKAGE__ . "->configureCOREHANDLE" );
418
419 #my $subLayer = $self->_getSubLayerHandle();
420 #print Dumper($self);
421 #exit;
422
423 # apply configured modifications
424 if (exists $self->{dbi}->{trace_level} && exists $self->{dbi}->{trace_file}) {
425 $self->{_COREHANDLE}->{db}->trace($self->{dbi}->{trace_level}, $self->{dbi}->{trace_file});
426 }
427 if (exists $self->{dbi}->{RaiseError}) {
428 $self->{_COREHANDLE}->{db}->{RaiseError} = $self->{dbi}->{RaiseError};
429 }
430 if (exists $self->{dbi}->{PrintError}) {
431 $self->{_COREHANDLE}->{db}->{PrintError} = $self->{dbi}->{PrintError};
432 }
433 if (exists $self->{dbi}->{HandleError}) {
434 $self->{_COREHANDLE}->{db}->{HandleError} = $self->{dbi}->{HandleError};
435 }
436
437 }
438
439 sub deploySchema {
440 my $self = shift;
441 my $args = shift;
442
443 my $dsn = $self->{locator}->{dbi}->{dsn};
444
445 $logger->debug( __PACKAGE__ . "->deploySchema( dsn $dsn )" );
446
447 my $ok;
448 if ( my $dbh = DBI->connect($dsn, '', '', $self->{locator}->{dbi} ) ) {
449 return unless $self->_initSchema();
450 $ok = Tangram::Relational->deploy($schema_tangram, $dbh );
451 $dbh->disconnect();
452 }
453 return $ok;
454 }
455
456 sub retreatSchema {
457
458 my $self = shift;
459 my $dsn = $self->{locator}->{dbi}->{dsn};
460
461 $logger->debug( __PACKAGE__ . "->retreatSchema( dsn $dsn )" );
462
463 my $ok;
464 if ( my $dbh = DBI->connect($dsn, '', '', $self->{locator}->{dbi} ) ) {
465
466 return unless $self->_initSchema();
467
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();
482
483 }
484 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 "Filter_payload: " . Dumper($in->{filters}) . "\n";
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 (!ref($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 # debug point:
599 #print "Filter: " . Dumper($orm_query->{filter}) . "\n";
600
601 # was:
602
603 # 2.b. sorting [new as of 2003-06-17]
604 if ($in->{sorting}) {
605 my $sorting_rules = [];
606 my $sorting_order = 'ASC';
607 foreach my $sorting_column (keys %{$in->{sorting}}) {
608 $sorting_order = $in->{sorting}->{$sorting_column} if $in->{sorting}->{$sorting_column};
609 push @$sorting_rules, Tangram::Expr->new( 'string' => $sorting_column );
610 }
611 $orm_query->{order} = $sorting_rules;
612 if ($sorting_order eq 'DESC') {
613 $orm_query->{desc} = 1;
614 }
615 }
616
617
618 # 3. build and issue query - return result as Tangram::Cursor
619
620 # coerce hash into array (This is valid in Perl)
621 my @orm_query_args = %$orm_query;
622 # send query (arguments) to orm
623 @results = $self->{_COREHANDLE}->select($remote, @orm_query_args);
624
625 #my $cursor = $self->{_COREHANDLE}->cursor($remote, @orm_query_args);
626 #return $cursor;
627 #print Dumper(@results);
628
629 # is:
630 # HACK: build eval-string (sorry) to get filtered list - please give advice here
631 #my $evalstring = 'return $self->{_COREHANDLE}->select($remote, ' . $tfilter . $sorting . ');';
632 #print "eval: $evalstring", "\n";
633 # get filtered list/set
634 #@results = eval($evalstring);
635 #die $@ if $@;
636
637 # filter results - NEEDED for e.g. UserManagment !!
638 if ($in->{filters}->[0]->{op} && ($in->{filters}->[0]->{op} eq "ref")) {
639 #print "Filter->op eq 'ref'.\n";
640 my $att_name = $in->{filters}->[0]->{key};
641 my $att_val = $in->{filters}->[0]->{val};
642 my @filtered;
643 foreach(@results) {
644 if(ref($_->{$att_name}) eq $att_val) {
645 push @filtered, $_;
646 }
647 }
648 @results = @filtered;
649 }
650
651 #print "results: " . Dumper(\@results);
652
653 return \@results;
654 }
655
656 sub createCursor {
657 my $self = shift;
658 my $node = shift;
659 my $cmdHandle = $self->{_COREHANDLE}->cursor($node);
660 my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $cmdHandle );
661 return $result;
662 }
663
664 sub createSet {
665 my $self = shift;
666 #print "-" x 80, "\n";
667 #print Dumper(@_);
668 my @objects = @_;
669 my $rh = Set::Object->new();
670 foreach (@objects) {
671 if (!isEmpty($_)) {
672 #print Dumper($_);
673 $rh->insert($_);
674 }
675 }
676 #print Dumper($rh->members());
677 my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $rh );
678 return $result;
679 }
680
681 sub createResult {
682 my $self = shift;
683 my $rh = shift;
684 my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $rh );
685 return $result;
686 }
687
688 sub sendQuery {
689 my $self = shift;
690 my $query = shift;
691
692 #print Dumper($query);
693
694 # type = ITEM|LIST|TRANSPARENT
695 my $type = '';
696 # mode = OID|SPECIAL
697 my $mode = '';
698 my $ident = '';
699 my $crud = '';
700
701
702 # dispatch type and mode
703
704 # defaults - 1
705 if ($query->{options}) {
706 $crud = $query->{options}->{crud};
707 $crud ||= $query->{options}->{action};
708 }
709
710 # defaults - 2
711 $type ||= 'TRANSPARENT';
712 $crud ||= 'RETRIEVE';
713
714 if ($query->{options}->{OID}) {
715 $type = 'ITEM';
716 $mode = 'OID';
717 $ident = $query->{options}->{OID};
718
719 } elsif (my $guid = $query->{options}->{GUID}) {
720 $type = 'TRANSPARENT';
721 $query->{criterias} = [ { key => 'guid', op => 'eq', val => $guid } ];
722
723 # if operator is different (dispatcher for 'getListFiltered')
724 } elsif (my $op = $query->{options}->{op}) {
725 $type = 'TRANSPARENT';
726 $query->{criterias} = [ { key => $query->{options}->{meta_label}, op => $op, val => $query->{options}->{meta_value} } ];
727
728 }
729
730 # HACK: special case: querying by id does not translate into a common tangram query
731 # just load the object by given identifier (OID) named 'id' - this is required by Data::Transfer::Sync!
732 if ($query->{criterias} && ($query->{criterias}->[0]->{key} eq 'id' && $query->{criterias}->[0]->{op} eq 'eq')) {
733 $type = 'ITEM';
734 $mode = 'SPECIAL.SYNC';
735 $ident = $query->{criterias}->[0]->{val};
736 }
737
738
739 # execute query
740 my $result;
741
742 if ($type eq 'ITEM' && $ident) {
743
744 if ($mode eq 'OID') {
745 # TODO: review this case!
746 $result = $self->getObject($ident, $query->{options});
747
748 } elsif ($mode eq 'SPECIAL.SYNC') {
749
750 # V1 - failed
751 #return Set::Object->new( $self->{COREHANDLE}->load($query->{criterias}->[0]->{val}) );
752
753 # hmm....
754 #return $self->createSet() if $ident == 5;
755
756 # Unload single object before doing any further operations to
757 # expect a "fresh" object from orm when performing the next calls.
758 $self->{_COREHANDLE}->unload($ident);
759
760 # Load object from orm.
761 my $object = $self->{_COREHANDLE}->load($ident);
762
763 # determine object identifier (OID)
764 my $oid = $self->{_COREHANDLE}->id($object);
765
766 # encapsulate into result/response container and return this one
767 $result = $self->createSet($object);
768
769 # debugging
770 #$result = $self->createSet( $self->{COREHANDLE}->load('300090018') );
771
772 }
773
774
775 } elsif ($type eq 'TRANSPARENT') {
776
777 if ($crud eq 'RETRIEVE') {
778
779 my $list = $self->getListFiltered($query->{node}, $query->{criterias}, $query->{sorting});
780 #return $list;
781 return $self->createResult($list);
782
783 #return $self->createSet($object);
784 #return $self->createSet($list);
785 return $self->createSet(@$list);
786
787 #die("This should not be reached for now - redirect to \$self->getListFiltered() here!");
788
789 # try a generic tangram query here
790 # TODO: try to place an oql on top of that (search.cpan.org!)
791 my @crits;
792 foreach (@{$query->{criterias}}) {
793 my $op = '';
794 $op = '=' if lc $_->{op} eq 'eq';
795 push @crits, "$_->{key}$op'$_->{val}'";
796 }
797 my $subnodes = {};
798 map { $subnodes->{$_}++ } @{$query->{subnodes}};
799 # HACK: this is hardcoded ;( expand possibilities!
800 #my $crit = join(' AND ', @crits);
801 #my $sql = hash2Sql($query->{node}, $subnodes, 'SELECT', $crit);
802 #return $self->sendCommand($sql);
803 #my $h = $self->{COREHANDLE}->remote($query->{node});
804 #my $res = $self->{COREHANDLE}->select($h, $h->{);
805 $result = $self->createCursor($query->{node});
806
807 } elsif ($crud eq 'UPDATE') {
808
809 # Patch current query to be a loader (e.g. change action, remove payload) ...
810 my $childquery = deep_copy($query);
811 $childquery->{options}->{crud} = 'RETRIEVE';
812 delete $childquery->{payload};
813
814 # ... to use it to fetch a fresh object using ourselves (sendQuery).
815 my $cursor = $self->sendQuery($childquery);
816 my $status = $cursor->getStatus();
817 my $object = $cursor->getNextEntry();
818
819 # Merge values and apply value modifiers.
820 my $options = { utf8 => 1, php => 1 };
821 merge_to($object, $query->{payload}, $options);
822
823 #print Dumper($object);
824
825 # Execute update operation at orm.
826 $self->update($object);
827 $result = $self->createResult([ $object ]);
828
829 } elsif ($crud eq 'DELETE') {
830
831 # Patch current query to be a loader (e.g. change action) ...
832 my $childquery = deep_copy($query);
833 $childquery->{options}->{crud} = 'RETRIEVE';
834
835 # ... to use it to fetch a fresh object using ourselves (sendQuery).
836 my $cursor = $self->sendQuery($childquery);
837 my $status = $cursor->getStatus();
838 my $object = $cursor->getNextEntry();
839
840 $self->erase($object);
841 $self->unload($object);
842
843 } elsif ($crud eq 'CREATE') {
844
845 my $nodename = $query->{node};
846 my $newnode = $self->createNode($nodename);
847 my $id = $self->{_COREHANDLE}->insert($newnode);
848
849 print "Saved new node $nodename with GUID $newnode->{guid}, OID '$id': " . Dumper($newnode) . "\n";
850
851 return $newnode;
852
853 }
854
855 }
856
857 return $result;
858
859 }
860
861 sub eraseAll {
862 my $self = shift;
863 my $classname = shift;
864 my $remote = $self->{_COREHANDLE}->remote($classname);
865 my @objs = $self->{_COREHANDLE}->select($remote);
866 $self->{_COREHANDLE}->erase(@objs);
867 }
868
869 sub createDb {
870 my $self = shift;
871 my $storage = $self->_getSubLayerHandle();
872 return $storage->createDb();
873 }
874
875 sub getObject {
876 my $self = shift;
877 my $oid = shift;
878 my $options = shift;
879
880 # TODO: create a deep_unload method (currently _all_ objects are unloaded)
881 # unload($oid) will only unload object, not deep object hashes
882 $self->{_COREHANDLE}->unload() if ($options->{destroy});
883
884 # TODO: review this
885 #if (!$self->{COREHANDLE}) { return; }
886
887 # TODO: review this
888 my $object = eval('$self->{_COREHANDLE}->load($oid);');
889 print $@, "\n" if $@;
890
891 return $object if $object;
892 }
893
894 sub getObjectByGuid_old {
895 my $self = shift;
896 my $guid = shift;
897 my $options = shift;
898
899 # Guid and Classname is needed
900 if(!$guid || !$options->{classname}) {
901 $logger->error( __PACKAGE__ . "->getObjectByGuid: No 'guid' OR no Classname in options hash was given but needed!" );
902 return;
903 }
904
905 # TODO: create a deep_unload method (currently _all_ objects are unloaded)
906 # unload($oid) will only unload object, not deep object hashes
907 $self->{_COREHANDLE}->unload() if ($options->{destroy});
908
909 # search for object with given Classname and Guid
910 my $obj_tmp = $self->{_COREHANDLE}->remote($options->{classname});
911 my @result = $self->{_COREHANDLE}->select($obj_tmp, $obj_tmp->{guid} eq $guid);
912
913 # we searched for global unique identifer of some object,
914 # so I think we can trust there would be only one result
915 if($result[0]) {
916 return $result[0];
917 } else {
918 $logger->error( __PACKAGE__ . "->getObjectByGuid: No Object with Classname $options->{classname} and GUID $guid found!" );
919 return;
920 }
921
922 }
923
924 sub getObjectAsHash_old {
925 my $self = shift;
926 my $oid = shift;
927 my $options = shift;
928 my $obj;
929
930 if($options->{guid}) {
931 $obj = $self->getObjectByGuid($oid, $options);
932 } else {
933 $obj = $self->getObject($oid, $options);
934 }
935
936 # build options (a callback to unload autovivified objects) for 'expand'
937 # TODO: use $logger to write to debug here!
938 my $cb; # = sub {};
939
940 # deactivated way to get rid of used instances, if requested
941 =pod
942 if ($options->{destroy}) {
943 $options->{cb}->{destroy} = sub {
944 print "================ DESTROY", "\n";
945 my $object = shift;
946 #print Dumper($object);
947 $self->{_COREHANDLE}->unload($object);
948 #undef($object);
949 };
950 }
951 =cut
952
953 my $hash = expand($obj, $options);
954
955 # old (unsuccessful) attempts to get rid of used instances, if requested
956
957 # V1:
958 #$options->{cb}->{destroy}->($obj);
959 #$self->{_COREHANDLE}->unload($obj);
960
961 # V2:
962 #$obj->clear_refs;
963 #$self->{COREHANDLE}->unload($obj) if($options->{destroy});
964 #$obj->DESTROY;
965 #undef($obj) if($options->{destroy});
966
967 return $hash;
968 }
969
970 sub getSchema {
971 return $schema_tangram;
972 }
973
974 sub getCOREHANDLE {
975 my $self = shift;
976 return $self->{_COREHANDLE};
977 }
978
979 sub dropDb {
980 my $self = shift;
981 my $storage = $self->_getSubLayerHandle();
982 return $storage->dropDb();
983 }
984
985 sub testAvailability {
986 my $self = shift;
987 my $storage = $self->_getSubLayerHandle();
988 return $storage->testAvailability();
989 }
990
991 sub disconnect2 {
992 my $self = shift;
993 my $storage = $self->_getSubLayerHandle();
994 print "DISC!", "\n";
995
996 my $storage_ll = $storage->{_COREHANDLE};
997 $storage_ll->disconnect();
998
999 print Dumper($storage);
1000 exit;
1001
1002 #$self->{_COREHANDLE}
1003 #$storage->disconnect();
1004 $self->{dataStorageLayer}->disconnect();
1005 }
1006
1007
1008 sub createNode {
1009 my $self = shift;
1010 my $classname = shift;
1011
1012 my $obj = $classname->new();
1013
1014 my $attr_options = Class::Tangram::attribute_options($classname);
1015 #print "Attribute Options: " . Dumper($attr_options);
1016
1017 my $attr_types = Class::Tangram::attribute_types($classname);
1018 #print "Attribute Types: " . Dumper($attr_types);
1019
1020 foreach(keys %{$attr_types}) {
1021 if($attr_types->{$_} eq 'string') {
1022 $obj->{$_} = '';
1023 } elsif($attr_types->{$_} eq 'int') {
1024 $obj->{$_} = 0;
1025 } elsif($attr_types->{$_} eq 'real') {
1026 $obj->{$_} = 0;
1027 } elsif($attr_types->{$_} eq 'rawdatetime') {
1028 $obj->{$_} = '0000-00-00 00:00:00';
1029 } elsif($attr_types->{$_} eq 'ref') {
1030 if($attr_options->{$_}->{class}) {
1031 # HACK!!!
1032 # STANDALONE Objects (objects which make sense to instanciat alone) should not created automaticly
1033 # because they maybe exists and should only be SETTED not CREATED!
1034 # TODO: Create a flag at the scheme for that reason!
1035 # (e.g child_node => 1 for child-nodes only like e.g. UserData)
1036 if($attr_options->{$_}->{class} eq 'NetPerson' || $attr_options->{$_}->{class} eq 'Event') {
1037 #$obj->{$_} = undef();
1038 } else {
1039 $obj->{$_} = $self->createNode($attr_options->{$_}->{class});
1040 }
1041 } else {
1042 #$obj->{$_} = undef();
1043 }
1044 } elsif($attr_types->{$_} eq 'iarray') {
1045 $obj->{$_} = [ ];
1046 } elsif($attr_types->{$_} eq 'hash') {
1047 $obj->{$_} = { };
1048 } elsif($attr_types->{$_} eq 'flat_hash') {
1049 $obj->{$_} = { };
1050 }
1051 }
1052
1053 #print "New Object: " . Dumper($obj);
1054
1055 return $obj;
1056 }
1057
1058
1059 sub insertChildNode {
1060 my $self = shift;
1061 my $child_entry = shift;
1062 my $query_args = shift;
1063
1064 my $core = $self->{_COREHANDLE};
1065 my $nodename = $query_args->{nodename};
1066
1067 # get parent object
1068 my $query = {
1069 node => $query_args->{parent}->{nodename},
1070 options => { GUID => $query_args->{parent}->{guid}, },
1071 };
1072 my $cursor = $self->sendQuery($query);
1073 my $parent = $cursor->getNextEntry();
1074
1075 # debug
1076 #print "Parent_org: " . Dumper($parent);
1077
1078 # Create child node object if isn't already done
1079 # ($child_entry have to be the class name then...)
1080 if(!ref($child_entry)) {
1081 $child_entry = $self->createNode($child_entry);
1082 # it could be insert 'manually' or will be insert 'transparent' if parent will be updated
1083 #$core->insert($child_entry);
1084 #print "Create child object [$nodename]: " . Dumper($child_entry);
1085 }
1086
1087 # get reference of tied node (seems, only on Linux node's are tied!!)
1088 my $tied_node = tied $parent->{$nodename};
1089
1090 # insert/change child entry at parent
1091 #print "reference: " . ref($parent->{$nodename}) . "\n";
1092 if(ref($parent->{$nodename}) eq 'ARRAY') {
1093 # (seems, only on Linux node's are tied!!)
1094 if($tied_node) {
1095 # all tangram types are tied as 'SCALAR' with special 'FETCH', 'STORE' methods per type,
1096 # so a 'PUSH' is not implemented (which could be then done transparently)
1097 my $array = $tied_node->FETCH;
1098 push @$array, $child_entry;
1099 $tied_node->STORE($array);
1100 # node will be normaly untied at 'STORE'
1101 if(tied $parent->{$nodename}) { print "already tied !!\n"; }
1102 else { undef $tied_node; }
1103 } else {
1104 push @{$parent->{$nodename}}, $child_entry;
1105 }
1106 }
1107 elsif(ref($parent->{$nodename}) eq 'HASH') {
1108 if(my $key = $query_args->{hash_key}) {
1109 # (seems, only on Linux node's are tied!!)
1110 if($tied_node) {
1111 # same problem as with 'ARRAY':
1112 # all tangram types are tied as 'SCALAR' with special 'FETCH', 'STORE' methods per type.
1113 my $hash = $tied_node->FETCH;
1114 $hash->{$key} = $child_entry;
1115 $tied_node->STORE($hash);
1116 # node will be normaly untied at 'STORE'
1117 if(tied $parent->{$nodename}) { print "already tied !!\n"; }
1118 else { undef $tied_node; }
1119 } else {
1120 $parent->{$nodename}->{$key} = $child_entry;
1121 }
1122 } else {
1123 print "ERROR: No HASH KEY given, so not able to insert hash entry!";
1124 }
1125 }
1126 else {
1127 $parent->{$nodename} = $child_entry;
1128 }
1129
1130 # debug
1131 #print "Parent_new: " . Dumper($parent);
1132
1133 # save parent
1134 $core->update($parent);
1135
1136 # debug
1137 #print "Saved Parent: ". Dumper($parent);
1138
1139 return $child_entry;
1140 }
1141
1142
1143 1;
1144 __END__

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