Code

e6ec1048c289149ddeb576211a72b3b491c8b3a6
[gosa.git] / trunk / gosa-si / modules / DBsqlite.pm
1 package GOSA::DBsqlite;
3 use strict;
4 use warnings;
5 use Carp;
6 use DBI;
7 use GOSA::GosaSupportDaemon;
8 use Time::HiRes qw(usleep);
9 use Fcntl qw/:DEFAULT :flock/; # import LOCK_* constants
11 our $col_names = {};
13 sub new {
14         my $class = shift;
15         my $db_name = shift;
17         my $lock = $db_name.".si.lock";
18         my $self = {dbh=>undef,db_name=>undef,db_lock=>undef,db_lock_handle=>undef};
19         my $dbh = DBI->connect("dbi:SQLite:dbname=$db_name", "", "", {RaiseError => 1, AutoCommit => 1, PrintError => 0});
20         
21         $self->{dbh} = $dbh;
22         $self->{db_name} = $db_name;
23         $self->{db_lock} = $lock;
24         bless($self,$class);
26         my $sth = $self->{dbh}->prepare("pragma integrity_check");
27            $sth->execute();
28         my @ret = $sth->fetchall_arrayref();
29            $sth->finish();
30         if(length(@ret)==1 && $ret[0][0][0] eq 'ok') {
31                 &main::daemon_log("0 DEBUG: Database disk image '".$self->{db_name}."' is ok.", 7);
32         } else {
33                 &main::daemon_log("0 ERROR: Database disk image '".$self->{db_name}."' is malformed, creating new database!", 1);
34                 $self->{dbh}->disconnect() or &main::daemon_log("0 ERROR: Could not disconnect from database '".$self->{db_name}."'!", 1);
35                 $self->{dbh}= undef;
36                 unlink($db_name);
37         }
38         return($self);
39 }
42 sub connect {
43         my $self = shift;
44         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
45                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::connect was called static! Argument was '$self'!", 1);
46                 return;
47         }
48                 
49         $self->{dbh} = DBI->connect("dbi:SQLite:dbname=".$self->{db_name}, "", "", {PrintError => 0, RaiseError => 1, AutoCommit => 1}) or 
50           &main::daemon_log("0 ERROR: Could not connect to database '".$self->{db_name}."'!", 1);
52         return;
53 }
56 sub disconnect {
57         my $self = shift;
58         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
59                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::disconnect was called static! Argument was '$self'!", 1);
60                 return;
61         }
63         eval {
64                 $self->{dbh}->disconnect();
65         };
66   if($@) {
67                 &main::daemon_log("ERROR: Could not disconnect from database '".$self->{db_name}."'!", 1);
68         }
70         $self->{dbh}= undef;
72         return;
73 }
76 sub lock {
77         my $self = shift;
78         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
79                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::lock was called static! Argument was '$self'!", 1);
80                 return;
81         }
83         if(not ref $self->{db_lock_handle} or not fileno $self->{db_lock_handle}) {
84                 sysopen($self->{db_lock_handle}, $self->{db_lock}, O_RDWR | O_CREAT, 0600) or &main::daemon_log("0 ERROR: Opening the database ".$self->{db_name}." failed with $!", 1);
85         }
86 get_lock:
87         my $lock_result = flock($self->{db_lock_handle}, LOCK_EX | LOCK_NB);
88         if(not $lock_result) {
89                 &main::daemon_log("0 ERROR: Could not acquire lock for database ".$self->{db_name}, 1);
90                 usleep(250+rand(500));
91                 goto get_lock;
92         } else {
93                 seek($self->{db_lock_handle}, 0, 2);
94                 &main::daemon_log("0 DEBUG: Acquired lock for database ".$self->{db_name}, 8);
95                 $self->connect();
96         }
97         return;
98 }
101 sub unlock {
102         my $self = shift;
103         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
104                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::unlock was called static! Argument was '$self'!", 1);
105                 return;
106         }
107         if(not ref $self->{db_lock_handle}) {
108                 &main::daemon_log("0 BIG ERROR: Lockfile for database ".$self->{db_name}."got closed within critical section!", 1);
109         }
110         flock($self->{db_lock_handle}, LOCK_UN);
111         &main::daemon_log("0 DEBUG: Released lock for database ".$self->{db_name}, 8);
112         $self->disconnect();
113         return;
117 sub create_table {
118         my $self = shift;
119         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
120                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::create_table was called static! Statement was '$self'!", 1);
121                 return;
122         }
123         my $table_name = shift;
124         my $col_names_ref = shift;
125         my $index_names_ref = shift || undef;
126         my @col_names;
127         my @col_names_creation;
128         foreach my $col_name (@$col_names_ref) {
129                 push(@col_names, $col_name);
130         }
131         
132         $col_names->{ $table_name } = \@col_names;
133         my $col_names_string = join(", ", @col_names);
134         my $sql_statement = "CREATE TABLE IF NOT EXISTS $table_name ( $col_names_string )"; 
135         my $res = $self->exec_statement($sql_statement);
136         
137         # Add indices
138         if(defined($index_names_ref) and ref($index_names_ref) eq 'ARRAY') {
139                 foreach my $index_name (@$index_names_ref) {
140                         $self->exec_statement("CREATE ".(($index_name eq 'id')?'UNIQUE':'')." INDEX IF NOT EXISTS $index_name on $table_name ($index_name);");
141                 }
142         }
144         return 0;
148 sub add_dbentry {
149         my $self = shift;
150         my $arg = shift;
151         my $res = 0;   # default value
153         # if dbh not specified, return errorflag 1
154         my $table = $arg->{table};
155         if( not defined $table ) {
156                 return 1 ;
157         }
159         # if timestamp is not provided, add timestamp   
160         if( not exists $arg->{timestamp} ) {
161                 $arg->{timestamp} = &get_time;
162         }
164         # check primkey and run insert or update
165         my $primkeys = $arg->{'primkey'};
166         my $prim_statement="";
167         if( 0 != @$primkeys ) {   # more than one primkey exist in list
168                 my @prim_list;
169                 foreach my $primkey (@$primkeys) {
170                         if( not exists $arg->{$primkey} ) {
171                                 return (3, "primkey '$primkey' has no value for add_dbentry");
172                         }
173                         push(@prim_list, "$primkey='".$arg->{$primkey}."'");
174                 }
175                 $prim_statement = "WHERE ".join(" AND ", @prim_list);
177                 # check wether primkey is unique in table, otherwise return errorflag
178                 my $sql_statement = "SELECT * FROM $table $prim_statement";
179                 $res = @{ $self->exec_statement($sql_statement) };
180         }
182         # primkey is unique or no primkey specified -> run insert
183         if ($res == 0) {
184                 # fetch column names of table
185                 my $col_names = &get_table_columns($self, $table);
187                 my $create_id=0;
188                 foreach my $col_name (@{$col_names}) {
189                         if($col_name eq "id" && (! exists $arg->{$col_name})) {
190                                 $create_id=1;
191                         }
192                 }
193                 # assign values to column name variables
194                 my @col_list;
195                 my @val_list;
196                 foreach my $col_name (@{$col_names}) {
197                         # use function parameter for column values
198                         if (exists $arg->{$col_name}) {
199                                 push(@col_list, "'".$col_name."'");
200                                 push(@val_list, "'".$arg->{$col_name}."'");
201                         }
202                 }
204                 my $sql_statement;
205                 if($create_id==1) {
206                         $sql_statement = "INSERT INTO $table (id, ".join(", ", @col_list).") VALUES (null, ".join(", ", @val_list).")";
207                 } else {
208                         $sql_statement = "INSERT INTO $table (".join(", ", @col_list).") VALUES (".join(", ", @val_list).")";
209                 }
210                 my $db_res;
211                 my $success=0;
212                 $self->lock();
213                 eval {
214                         my $sth = $self->{dbh}->prepare($sql_statement);
215                         $db_res = $sth->execute();
216                         $sth->finish();
217                         &main::daemon_log("0 DEBUG: Execution of statement '$sql_statement' succeeded!", 9);
218                         $success = 1;
219                 };
220                 if($@) {
221                         eval {
222                                 $self->{dbh}->do("ANALYZE");
223                                 $self->{dbh}->do("VACUUM");
224                         };
225                 }
226                 if($success==0) {
227                         eval {
228                                 my $sth = $self->{dbh}->prepare($sql_statement);
229                                 $db_res = $sth->execute();
230                                 $sth->finish();
231                                 &main::daemon_log("0 DEBUG: Execution of statement '$sql_statement' succeeded!", 9);
232                                 $success = 1;
233                         };
234                         if($@) {
235                                 eval {
236                                         $self->{dbh}->do("ANALYZE");
237                                         $self->{dbh}->do("VACUUM");
238                                 };
239                         }
240                 }
241                 if($success==0) {
242                         eval {
243                                 my $sth = $self->{dbh}->prepare($sql_statement);
244                                 $db_res = $sth->execute();
245                                 $sth->finish();
246                                 &main::daemon_log("0 DEBUG: Execution of statement '$sql_statement' succeeded!", 7);
247                                 $success = 1;
248                         };
249                         if($@) {
250                                 &main::daemon_log("0 ERROR: Execution of statement '$sql_statement' failed with $@", 1);
251                         }
252                 }
253                 $self->unlock();
255                 if( $db_res != 1 ) {
256                         return (4, $sql_statement);
257                 }
259                 # entry already exists -> run update
260         } else  {
261                 my @update_l;
262                 while( my ($pram, $val) = each %{$arg} ) {
263                         if( $pram eq 'table' ) { next; }
264                         if( $pram eq 'primkey' ) { next; }
265                         push(@update_l, "$pram='$val'");
266                 }
267                 my $update_str= join(", ", @update_l);
268                 $update_str= " SET $update_str";
270                 my $sql_statement= "UPDATE $table $update_str $prim_statement";
271                 my $db_res = &update_dbentry($self, $sql_statement );
272         }
274         return 0;
278 sub update_dbentry {
279         my ($self, $sql)= @_;
280         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
281                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::update_dbentry was called static! Statement was '$self'!", 1);
282                 return;
283         }
284         my $db_answer= $self->exec_statement($sql); 
285         return $db_answer;
289 sub del_dbentry {
290         my ($self, $sql)= @_;;
291         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
292                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::del_dbentry was called static! Statement was '$self'!", 1);
293                 return;
294         }
295         my $db_res= $self->exec_statement($sql);
296         return $db_res;
300 sub get_table_columns {
301         my $self = shift;
302         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
303                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::get_table_columns was called static! Statement was '$self'!", 1);
304                 return;
305         }
306         my $table = shift;
307         my @column_names;
309         if(exists $col_names->{$table}) {
310                 foreach my $col_name (@{$col_names->{$table}}) {
311                         push @column_names, ($1) if $col_name =~ /^(.*?)\s.*$/;
312                 }
313         } else {
314                 my @res;
315                 foreach my $column ( @{ $self->exec_statement ( "pragma table_info('$table')" ) } ) {
316                         push(@column_names, @$column[1]);
317                 }
318         }
320         return \@column_names;
324 sub select_dbentry {
325         my ($self, $sql)= @_;
326         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
327                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::select_dbentry was called static! Statement was '$self'!", 1);
328                 return;
329         }
330         my $error= 0;
331         my $answer= {};
332         my $db_answer= $self->exec_statement($sql); 
333         my @column_list;
335         # fetch column list of db and create a hash with column_name->column_value of the select query
336         $sql =~ /SELECT ([\S\s]*?) FROM ([\S]*?)( |$)/g;
337         my $selected_cols = $1;
338         my $table = $2;
340         # all columns are used for creating answer
341         if ($selected_cols eq '*') {
342                 @column_list = @{ $self->get_table_columns($table) };    
344                 # specific columns are used for creating answer
345         } else {
346                 # remove all blanks and split string to list of column names
347                 $selected_cols =~ s/ //g;          
348                 @column_list = split(/,/, $selected_cols);
349         }
351         # create answer
352         my $hit_counter = 0;
353         my $list_len = @column_list;
354         foreach my $hit ( @{$db_answer} ){
355                 $hit_counter++;
356                 for ( my $i = 0; $i < $list_len; $i++) {
357                         $answer->{ $hit_counter }->{ $column_list[$i] } = @{ $hit }[$i];
358                 }
359         }
361         return $answer;  
365 sub show_table {
366         my $self = shift;
367         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
368                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::show_table was called static! Statement was '$self'!", 1);
369                 return;
370         }
371         my $table_name = shift;
373         my $sql_statement= "SELECT * FROM $table_name ORDER BY timestamp";
374         my $res= $self->exec_statement($sql_statement);
375         my @answer;
376         foreach my $hit (@{$res}) {
377                 push(@answer, "hit: ".join(', ', @{$hit}));
378         }
380         return join("\n", @answer);
384 sub exec_statement {
385         my $self = shift;
386         my $sql_statement = shift;
387         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
388                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::exec_statement was called static! Statement was '$self'!", 1);
389                 return;
390         }
392         if(not defined($sql_statement) or length($sql_statement) == 0) {
393                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::exec_statement was called with empty statement!", 1);
394                 return;
395         }
397         my @db_answer;
398         my $success= 0;
399         $self->lock();
400         # Give three chances to the sqlite database
401         # 1st chance
402         eval {
403                 my $sth = $self->{dbh}->prepare($sql_statement);
404                 my $res = $sth->execute();
405                 @db_answer = @{$sth->fetchall_arrayref()};
406                 $sth->finish();
407                 $success=1;
408                 &main::daemon_log("0 DEBUG: $sql_statement succeeded.", 9);
409         };
410         if($@) {
411                 eval {
412                         $self->{dbh}->do("ANALYZE");
413                         $self->{dbh}->do("VACUUM");
414                         $self->{dbh}->do("pragma integrity_check");
415                 };
416         }
417         if($success) {
418                 $self->unlock();
419                 return \@db_answer ;
420         }
422         # 2nd chance
423         eval {
424                 usleep(200);
425                 my $sth = $self->{dbh}->prepare($sql_statement);
426                 my $res = $sth->execute();
427                 @db_answer = @{$sth->fetchall_arrayref()};
428                 $sth->finish();
429                 $success=1;
430                 &main::daemon_log("0 DEBUG: $sql_statement succeeded.", 9);
431         };
432         if($@) {
433                 eval {
434                         $self->{dbh}->do("ANALYZE");
435                         $self->{dbh}->do("VACUUM");
436                         $self->{dbh}->do("pragma integrity_check");
437                 };
438         }
439         if($success) {
440                 $self->unlock();
441                 return \@db_answer ;
442         }
444         # 3rd chance
445         eval {
446                 usleep(200);
447                 DBI->trace(6) if($main::verbose >= 7);
448                 my $sth = $self->{dbh}->prepare($sql_statement);
449                 my $res = $sth->execute();
450                 @db_answer = @{$sth->fetchall_arrayref()};
451                 $sth->finish();
452                 DBI->trace(0);
453                 &main::daemon_log("0 DEBUG: $sql_statement succeeded.", 9);
454         };
455         if($@) {
456                 DBI->trace(0);
457                 &main::daemon_log("ERROR: $sql_statement failed with $@", 1);
458         }
459         # TODO : maybe an error handling and an erro feedback to invoking function
460         #my $error = @$self->{dbh}->err;
461         #if ($error) {
462         #       my $error_string = @$self->{dbh}->errstr;
463         #}
465         $self->unlock();
466         return \@db_answer;
470 sub exec_statementlist {
471         my $self = shift;
472         my $sql_list = shift;
473         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
474                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::exec_statementlist was called static!", 1);
475                 return;
476         }
477         my @db_answer;
479         foreach my $sql_statement (@$sql_list) {
480                 if(defined($sql_statement) && length($sql_statement) > 0) {
481                         push @db_answer, $self->exec_statement($sql_statement);
482                 } else {
483                         next;
484                 }
485         }
487         return \@db_answer;
491 sub count_dbentries {
492         my ($self, $table)= @_;
493         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
494                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::count_dbentries was called static!", 1);
495                 return;
496         }
497         my $error= 0;
498         my $count= -1;
500         my $sql_statement= "SELECT count() FROM $table";
501         my $db_answer= $self->select_dbentry($sql_statement); 
502         if(defined($db_answer) && defined($db_answer->{1}) && defined($db_answer->{1}->{'count()'})) {
503                 $count = $db_answer->{1}->{'count()'};
504         }
506         return $count;
510 sub move_table {
511         my ($self, $from, $to) = @_;
512         if(not defined($self) or ref($self) ne 'GOSA::DBsqlite') {
513                 &main::daemon_log("0 ERROR: GOSA::DBsqlite::move_table was called static!", 1);
514                 return;
515         }
517         my $sql_statement_drop = "DROP TABLE IF EXISTS $to";
518         my $sql_statement_alter = "ALTER TABLE $from RENAME TO $to";
519         my $success = 0;
521         $self->lock();
522         eval {
523                 $self->{dbh}->begin_work();
524                 $self->{dbh}->do($sql_statement_drop);
525                 $self->{dbh}->do($sql_statement_alter);
526                 $self->{dbh}->commit();
527                 $success = 1;
528         };
529         if($@) {
530                 $self->{dbh}->rollback();
531                 eval {
532                         $self->{dbh}->do("ANALYZE");
533                 };
534                 if($@) {
535                         &main::daemon_log("ERROR: 'ANALYZE' on database '".$self->{db_name}."' failed with $@", 1);
536                 }
537                 eval {
538                         $self->{dbh}->do("VACUUM");
539                 };
540                 if($@) {
541                         &main::daemon_log("ERROR: 'VACUUM' on database '".$self->{db_name}."' failed with $@", 1);
542                 }
543         }
545         if($success == 0) {
546                 eval {
547                         $self->{dbh}->begin_work();
548                         $self->{dbh}->do($sql_statement_drop);
549                         $self->{dbh}->do($sql_statement_alter);
550                         $self->{dbh}->commit();
551                         $success = 1;
552                 };
553                 if($@) {
554                         $self->{dbh}->rollback();
555                         eval {
556                                 $self->{dbh}->do("ANALYZE");
557                         };
558                         if($@) {
559                                 &main::daemon_log("ERROR: 'ANALYZE' on database '".$self->{db_name}."' failed with $@", 1);
560                         }
561                         eval {
562                                 $self->{dbh}->do("VACUUM");
563                         };
564                         if($@) {
565                                 &main::daemon_log("ERROR: 'VACUUM' on database '".$self->{db_name}."' failed with $@", 1);
566                         }
567                 }
568         }
569         
570         if($success == 0) {
571                 eval {
572                         $self->{dbh}->begin_work();
573                         $self->{dbh}->do($sql_statement_drop);
574                         $self->{dbh}->do($sql_statement_alter);
575                         $self->{dbh}->commit();
576                         $success = 1;
577                 };
578                 if($@) {
579                         $self->{dbh}->rollback();
580                         &main::daemon_log("0 ERROR: GOSA::DBsqlite::move_table crashed! Operation failed with $@", 1);
581                 }
582         }
584         &main::daemon_log("0 INFO: GOSA::DBsqlite::move_table: Operation successful!", 7);
585         $self->unlock();
587         return;
588
591 1;