/[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.44 - (show annotations)
Thu Dec 4 01:01:50 2003 UTC (20 years, 7 months ago) by joko
Branch: MAIN
Changes since 1.43: +9 -1 lines
+ sendQuery now returns result even on crud=UPDATE

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

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