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

Diff of /nfo/perl/libs/Data/Storage/Handler/DBI.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.3 by joko, Sun Nov 17 06:34:39 2002 UTC revision 1.17 by joko, Sat Jun 19 01:49:47 2004 UTC
# Line 3  Line 3 
3  #  $Id$  #  $Id$
4  #  #
5  #  $Log$  #  $Log$
6    #  Revision 1.17  2004/06/19 01:49:47  joko
7    #  (re-)activated "getCOREHANDLE"
8    #
9    #  Revision 1.16  2003/04/11 01:17:18  joko
10    #  sendQuery:
11    #  + introduced crud action 'DELETE'
12    #  + some pre-flight checks
13    #
14    #  Revision 1.15  2003/04/09 07:53:33  joko
15    #  minor namespace update
16    #
17    #  Revision 1.14  2003/04/09 06:06:04  joko
18    #  sendQuery now is capable of doing 'SELECT'- or 'INSERT'-queries
19    #
20    #  Revision 1.13  2003/04/08 23:06:45  joko
21    #  renamed core database helper functions
22    #
23    #  Revision 1.12  2003/01/30 22:28:21  joko
24    #  + implemented new concrete methods
25    #
26    #  Revision 1.11  2002/12/19 16:31:05  joko
27    #  + sub dropDb
28    #  + sub rebuildDb
29    #
30    #  Revision 1.10  2002/12/15 02:02:22  joko
31    #  + fixed logging-message
32    #
33    #  Revision 1.9  2002/12/05 07:58:20  joko
34    #  + now using Tie::SecureHash as a base for the COREHANDLE
35    #  + former public COREHANDLE becomes private _COREHANDLE now
36    #
37    #  Revision 1.8  2002/12/01 22:20:43  joko
38    #  + sub createDb (from Storage.pm)
39    #
40    #  Revision 1.7  2002/12/01 07:09:09  joko
41    #  + sub getListFiltered (dummy redirecting to getListUnfiltered)
42    #
43    #  Revision 1.6  2002/12/01 04:46:01  joko
44    #  + sub eraseAll
45    #
46    #  Revision 1.5  2002/11/29 05:00:26  joko
47    #  + sub getListUnfiltered
48    #  + sub sendQuery
49    #
50    #  Revision 1.4  2002/11/17 08:46:42  jonen
51    #  + wrapped eval around DBI->connect to prevent deaths
52    #
53  #  Revision 1.3  2002/11/17 06:34:39  joko  #  Revision 1.3  2002/11/17 06:34:39  joko
54  #  + locator metadata can now be reached via ->{locator}  #  + locator metadata can now be reached via ->{locator}
55  #  - sub hash2sql now taken from libdb  #  - sub hash2sql now taken from libdb
# Line 24  use warnings; Line 71  use warnings;
71    
72  use base ("Data::Storage::Handler::Abstract");  use base ("Data::Storage::Handler::Abstract");
73    
74    
75  use DBI;  use DBI;
76  use Data::Dumper;  use Data::Dumper;
77  use libdb;  use shortcuts::database qw( hash2sql dsn2dbname );
78    use Data::Storage::Result::DBI;
79    
80    
81  # get logger instance  # get logger instance
82  my $logger = Log::Dispatch::Config->instance;  my $logger = Log::Dispatch::Config->instance;
83    
84    
85  our $metainfo = {  sub getMetaInfo {
86    'disconnectMethod' => 'disconnect',    my $self = shift;
87  };    $logger->debug( __PACKAGE__ . "->getMetaInfo()"  );
88      return {
89        'disconnectMethod' => 'disconnect',
90      };
91    }
92    
93  sub connect {  sub connect {
94    
# Line 52  sub connect { Line 106  sub connect {
106                    
107          #use Data::Dumper; print Dumper($self->{dbi});          #use Data::Dumper; print Dumper($self->{dbi});
108                    
109          $self->{COREHANDLE} = DBI->connect( $dsn, '', '', $self->{locator}->{dbi} );          eval {
110          if (!$self->{COREHANDLE}) {            $self->{_COREHANDLE} = DBI->connect( $dsn, '', '', $self->{locator}->{dbi} );
111            $logger->warning( __PACKAGE__ . "->connect failed: " . DBI::errstr );            if (!$self->{_COREHANDLE}) {
112            return;              $logger->warning( __PACKAGE__ . "->connect failed: " . DBI::errstr );
113          }              return;
114              }
115            };
116            $logger->warning( __PACKAGE__ . "->connect failed: " . $@ ) if $@;
117    
118        }        }
119        $self->configureCOREHANDLE();        $self->configureCOREHANDLE();
120    
# Line 72  sub configureCOREHANDLE { Line 130  sub configureCOREHANDLE {
130    
131    $logger->debug( __PACKAGE__ . "->configureCOREHANDLE" );    $logger->debug( __PACKAGE__ . "->configureCOREHANDLE" );
132    
133    # apply configured modifications    return if !$self->{_COREHANDLE};
134    
135      # apply configured modifications to DBI-handle
136      if (exists $self->{locator}->{dbi}->{trace_level} && exists $self->{locator}->{dbi}->{trace_file}) {      if (exists $self->{locator}->{dbi}->{trace_level} && exists $self->{locator}->{dbi}->{trace_file}) {
137        $self->{COREHANDLE}->trace($self->{locator}->{dbi}->{trace_level}, $self->{locator}->{dbi}->{trace_file});        $self->{_COREHANDLE}->trace($self->{locator}->{dbi}->{trace_level}, $self->{locator}->{dbi}->{trace_file});
138      }      }
139      if (exists $self->{locator}->{dbi}->{RaiseError}) {      if (exists $self->{locator}->{dbi}->{RaiseError}) {
140        $self->{COREHANDLE}->{RaiseError} = $self->{locator}->{dbi}->{RaiseError};        $self->{_COREHANDLE}->{RaiseError} = $self->{locator}->{dbi}->{RaiseError};
141      }      }
142      if (exists $self->{locator}->{dbi}->{PrintError}) {      if (exists $self->{locator}->{dbi}->{PrintError}) {
143        $self->{COREHANDLE}->{PrintError} = $self->{locator}->{dbi}->{PrintError};        $self->{_COREHANDLE}->{PrintError} = $self->{locator}->{dbi}->{PrintError};
144      }      }
145      if (exists $self->{locator}->{dbi}->{HandleError}) {      if (exists $self->{locator}->{dbi}->{HandleError}) {
146        $self->{COREHANDLE}->{HandleError} = $self->{locator}->{dbi}->{HandleError};        $self->{_COREHANDLE}->{HandleError} = $self->{locator}->{dbi}->{HandleError};
147      }      }
148    
149  }  }
# Line 92  sub _sendSql { Line 152  sub _sendSql {
152    my $self = shift;    my $self = shift;
153    my $sql = shift;    my $sql = shift;
154        
155      # pre-flight check: is $sql defined?
156      if (!$sql) {
157        $logger->warning( __PACKAGE__ . "->_sendSql: \$sql was empty." );
158        return;
159      }
160      
161    # two-level handling for implicit connect:    # two-level handling for implicit connect:
162    # if there's no corehandle ...    # if there's no corehandle ...
163    if (!$self->{COREHANDLE}) {    if (!$self->{_COREHANDLE}) {
164      # ... try to connect, but ...      # ... try to connect, but ...
165      $self->connect();      $self->connect();
166      # ... if this still fails, there's something wrong probably, so we won't continue      # ... if this still fails, there's something wrong probably, so we won't continue
167      if (!$self->{COREHANDLE}) {      if (!$self->{_COREHANDLE}) {
168        return;        return;
169      }      }
170    }    }
171        
172    #print "prepare sql: $sql\n";    #print "prepare sql: $sql\n";
173        
174    my $sth = $self->{COREHANDLE}->prepare($sql);    my $sth = $self->{_COREHANDLE}->prepare($sql);
175    $sth->execute();    $sth->execute();
176    return $sth;    return $sth;
177  }  }
# Line 113  sub _sendSql { Line 179  sub _sendSql {
179  sub sendCommand {  sub sendCommand {
180    my $self = shift;    my $self = shift;
181    my $command = shift;    my $command = shift;
182      # TODO: when tracing: yes, do actually log this
183    #$logger->debug( __PACKAGE__ . "->sendCommand( command $command )" );    #$logger->debug( __PACKAGE__ . "->sendCommand( command $command )" );
184    my $cmdHandle = $self->_sendSql($command);    my $cmdHandle = $self->_sendSql($command);
185    my $result = Data::Storage::Result::DBI->new( RESULTHANDLE => $cmdHandle );    my $result = Data::Storage::Result::DBI->new( RESULTHANDLE => $cmdHandle );
186    return $result;    return $result;
187  }  }
188    
189  sub quoteSql {  sub getChildNodes {
190      my $self = shift;
191      my @nodes;
192      $logger->debug( __PACKAGE__ . "->getChildNodes()" );
193      my $locator = $self->{locator};
194      #print Dumper($locator); exit;
195      if (my $result = $self->sendCommand( 'SHOW TABLES;' ) ) {
196        my $dbname = dsn2dbname($self->{locator}->{dbi}->{dsn});
197        my $key = "Tables_in_$dbname";
198        while ( my $row = $result->getNextEntry() ) {
199          push @nodes, $row->{$key};
200        }
201      }
202      return \@nodes;
203    }
204    
205    sub getListUnfiltered {
206    my $self = shift;    my $self = shift;
207    my $string = shift;    my $nodename = shift;
208    if ($string) {    my @list;
209      $string =~ s/'/\\'/g;    $logger->debug( __PACKAGE__ . "->getListUnfiltered( nodename => '" . $nodename . "' )" );
210      # get list of rows from rdbms by table name
211      my $result = $self->sendCommand("SELECT * FROM $nodename");
212      while ( my $row = $result->getNextEntry() ) {
213        push @list, $row;
214    }    }
215    return $string;    return \@list;
216  }  }
217    
218    sub sendQuery {
219      my $self = shift;
220      my $query = shift;
221    
222  sub getChildNodes {    $logger->debug( __PACKAGE__ . "->sendQuery" );
223    
224      my $crud = $query->{options}->{crud};
225      $crud ||= $query->{options}->{action};
226      $crud ||= 'RETRIEVE';
227    
228      if (my $guid = $query->{options}->{GUID}) {
229        $query->{criterias} = [ { key => 'guid', op => 'eq', val => $guid } ];
230      }
231    
232      # check criterias (load & save)
233      #my $sql = "SELECT cs FROM $self->{metainfo}->{$descent}->{node} WHERE $self->{metainfo}->{$descent}->{IdentProvider}->{arg}='$self->{entry}->{source}->{ident}';";
234      #my $result = $self->{metainfo}->{$descent}->{storage}->sendCommand($sql);
235      my @crits;
236      foreach (@{$query->{criterias}}) {
237        my $op = '';
238        $op = '=' if lc $_->{op} eq 'eq';
239        push @crits, "$_->{key}$op'$_->{val}'";
240      }
241      # HACK: this is hardcoded ;(    expand possibilities!
242      my $crit = join(' AND ', @crits);
243      
244      # check subnodes (load)
245      my $subnodes = {};
246      map { $subnodes->{$_}++ } @{$query->{subnodes}};
247      
248      # check payload (save)
249      #print Dumper($query->{payload});
250      #$subnodes ||= $query->{payload};
251      
252      # dispatch action
253      if ($crud eq 'RETRIEVE') {
254        my $sql = hash2sql($query->{node}, $subnodes, 'SELECT', $crit);
255        return $self->sendCommand($sql);
256    
257      } elsif ($crud eq 'UPDATE') {
258        my $sql = hash2sql($query->{node}, $query->{payload}, 'UPDATE', $crit);
259        $self->sendCommand($sql);
260    
261      } elsif ($crud eq 'DELETE') {
262        my $sql = hash2sql($query->{node}, $query->{payload}, 'DELETE', $crit);
263        $self->sendCommand($sql);
264    
265      }
266    
267    }
268    
269    sub eraseAll {
270    my $self = shift;    my $self = shift;
271    my @nodes;    my $classname = shift;
272      $logger->debug( __PACKAGE__ . "->eraseAll" );
273      my $sql = "DELETE FROM $classname";
274      $self->sendCommand($sql);
275    }
276    
277    $logger->debug( __PACKAGE__ . "->getChildNodes()" );  # TODO: actually implement the filtering functionality using $this->sendQuery
278    sub getListFiltered {
279      my $self = shift;
280      my $nodename = shift;
281      return $self->getListUnfiltered($nodename);
282    }
283    
284    if (my $result = $self->sendCommand( 'SHOW TABLES;' ) ) {  # TODO: do this via a parametrized "$self->connect(<connect just to database server - don't select database>)"
285      my $dbname = getDbNameByDsn($self->{locator}->{dbi}->{dsn});  sub createDb {
286      my $key = "Tables_in_$dbname";    
287      while ( my $row = $result->_getNextEntry() ) {    my $self = shift;
288        push @nodes, $row->{$key};    
289      # get dsn from Data::Storage::Locator instance
290      my $dsn = $self->{locator}->{dbi}->{dsn};
291    
292      $logger->debug( __PACKAGE__ .  "->createDb( dsn $dsn )" );
293    
294      # remove database setting from dsn-string
295      $dsn =~ s/database=(.+?);//;
296      
297      # remember extracted database name to know what actually to create right now
298      my $database_name = $1;
299    
300      # flag to indicate goodness
301      my $ok;
302      
303      # connect to database server - don't select/use any specific database
304      #if ( my $dbh = DBI->connect($dsn, '', '', { PrintError => 0 } ) ) {
305      if ( my $dbh = DBI->connect($dsn, '', '', $self->{locator}->{dbi} ) ) {
306    
307        if ($database_name) {
308          if ($dbh->do("CREATE DATABASE $database_name")) {
309            $ok = 1;
310          }
311      }      }
312    
313        $dbh->disconnect();
314    
315    }    }
316        
317    return \@nodes;    return $ok;
318      
319    }
320    
321    sub getCOREHANDLE {
322      my $self = shift;
323      return $self->{_COREHANDLE};
324  }  }
325    
326    sub dropDb {
327      my $self = shift;
328      my $dsn = $self->{locator}->{dbi}->{dsn};
329    
330      $logger->debug( __PACKAGE__ .  "->dropDb( dsn $dsn )" );
331    
332      $dsn =~ s/database=(.+?);//;
333      my $database_name = $1;
334    
335  package Data::Storage::Result::DBI;    my $ok;
336      
337      if ( my $dbh = DBI->connect($dsn, '', '', {
338                                                          PrintError => 0,
339                                                          } ) ) {
340        if ($database_name) {
341          if ($dbh->do("DROP DATABASE $database_name;")) {
342            $ok = 1;
343          }
344        }
345    
346  use strict;      $dbh->disconnect();
 use warnings;  
347    
348  use base ("Data::Storage::Result");    }
349      
350      return $ok;
351    }
352    
353  sub DESTROY {  sub rebuildDb {
354    my $self = shift;    my $self = shift;
355    #$logger->debug( __PACKAGE__ . "->" . "DESTROY" );    $logger->info( __PACKAGE__ . "->rebuildDb()" );
356    $self->{RESULTHANDLE} && $self->{RESULTHANDLE}->finish();    my @results;
357    
358      # sum up results (bool (0/1)) in array
359      #push @results, $self->retreatSchema();
360      push @results, $self->dropDb();
361      push @results, $self->createDb();
362      #push @results, $self->deploySchema();
363    
364      # scan array for "bad ones"
365      my $res = 1;
366      map {
367        $res = 0 if (!$_);
368      } @results;
369      
370      return $res;
371  }  }
372    
373  sub _getNextEntry {  sub testAvailability {
374    my $self = shift;    my $self = shift;
375    $self->{RESULTHANDLE} && return $self->{RESULTHANDLE}->fetchrow_hashref;    my $status = $self->testDsn();
376      $self->{locator}->{status}->{available} = $status;
377      return $status;
378  }  }
379    
380    sub testDsn {
381      my $self = shift;
382      my $dsn = $self->{locator}->{dbi}->{dsn};
383      my $result;
384      if ( my $dbh = DBI->connect($dsn, '', '', {
385                                                          PrintError => 0,
386                                                          } ) ) {
387        
388        # TODO: REVIEW
389        $dbh->disconnect();
390        
391        return 1;
392      } else {
393        $logger->warning( __PACKAGE__ .  "[$self->{locator}->{type}]" . "->testDsn(): " . "DBI-error: " . $DBI::errstr );
394      }
395    }
396    
 1;  
397    1;
398    __END__

Legend:
Removed from v.1.3  
changed lines
  Added in v.1.17

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