1 package GOsaSI::DBmysql;
3 use strict;
4 use warnings;
6 use Data::Dumper;
7 use Time::HiRes qw(usleep);
8 use GOsaSI::GosaSupportDaemon;
10 use DBI;
12 my $col_names = {};
14 sub new {
15 my $class = shift;
16 my $database = shift;
17 my $host = shift;
18 my $username = shift;
19 my $password = shift;
21 my $self = {dbh=>undef};
22 my $dbh = DBI->connect("dbi:mysql:database=$database;host=$host", $username, $password,{ RaiseError => 1, AutoCommit => 1 });
23 $dbh->{mysql_auto_reconnect} = 1;
24 $self->{dbh} = $dbh;
25 bless($self,$class);
27 return($self);
28 }
31 sub create_table {
32 my $self = shift;
33 my $table_name = shift;
34 my $col_names_ref = shift;
35 my $recreate_table = shift || 0;
36 my @col_names;
37 my $col_names_string = join(", ", @$col_names_ref);
39 if($recreate_table) {
40 $self->{dbh}->do("DROP TABLE $table_name");
41 }
42 my $sql_statement = "CREATE TABLE IF NOT EXISTS $table_name ( $col_names_string ) ENGINE=INNODB";
43 # &main::daemon_log("DEBUG: $sql_statement");
44 eval {
45 $self->{dbh}->do($sql_statement);
46 };
47 if($@) {
48 &main::daemon_log("ERROR: $sql_statement failed with $@", 1);
49 }
51 return 0;
52 }
55 sub add_dbentry {
56 my $self = shift;
57 my $arg = shift;
58 my $res = 0; # default value
60 # if dbh not specified, return errorflag 1
61 my $table = $arg->{table};
62 if( not defined $table ) {
63 return 1 ;
64 }
66 # if timestamp is not provided, add timestamp
67 if( not exists $arg->{timestamp} ) {
68 $arg->{timestamp} = &get_time;
69 }
71 # check primkey and run insert or update
72 my $primkeys = $arg->{'primkey'};
73 my $prim_statement="";
74 if( 0 != @$primkeys ) { # more than one primkey exist in list
75 my @prim_list;
76 foreach my $primkey (@$primkeys) {
77 if( not exists $arg->{$primkey} ) {
78 return (3, "primkey '$primkey' has no value for add_dbentry");
79 }
80 push(@prim_list, "$primkey='".$arg->{$primkey}."'");
81 }
82 $prim_statement = "WHERE ".join(" AND ", @prim_list);
84 # check wether primkey is unique in table, otherwise return errorflag
85 my $sql_statement = "SELECT * FROM $table $prim_statement";
86 eval {
87 # &main::daemon_log("DEBUG: $sql_statement");
88 my $sth = $self->{dbh}->prepare($sql_statement);
89 $sth->execute;
90 $res = @{ $sth->fetchall_arrayref() };
91 $sth->finish;
92 };
93 if($@) {
94 &main::daemon_log("ERROR: $sql_statement failed with $@", 1);
95 }
97 }
99 # primkey is unique or no primkey specified -> run insert
100 if ($res == 0) {
101 # fetch column names of table
102 my $col_names = &get_table_columns($self, $table);
104 #my $create_id=0;
105 #foreach my $col_name (@{$col_names}) {
106 # #if($col_name eq "id" && (! exists $arg->{$col_name})) {
107 # #&main::daemon_log("0 DEBUG: id field found without value! Creating autoincrement statement!", 7);
108 # $create_id=1;
109 # }
110 #}
112 # assign values to column name variables
113 my @col_list;
114 my @val_list;
115 foreach my $col_name (@{$col_names}) {
116 # use function parameter for column values
117 if (exists $arg->{$col_name}) {
118 push(@col_list, $col_name);
119 push(@val_list, "'".$arg->{$col_name}."'");
120 }
121 }
123 my $sql_statement;
124 #if($create_id==1) {
125 # $sql_statement = "INSERT INTO $table (id, ".join(", ", @col_list).") VALUES ((select coalesce(max(id),0)+1), ".join(", ", @val_list).")";
126 #} else {
127 $sql_statement = "INSERT INTO $table (".join(", ", @col_list).") VALUES (".join(", ", @val_list).")";
128 #}
129 my $db_res;
130 # &main::daemon_log("DEBUG: $sql_statement",1);
131 eval {
132 $db_res = $self->{dbh}->do($sql_statement);
133 };
134 if($@) {
135 &main::daemon_log("ERROR: $sql_statement failed with $@", 1);
136 }
138 if( $db_res != 1 ) {
139 return (4, $sql_statement);
140 }
142 # entry already exists -> run update
143 } else {
144 my @update_l;
145 while( my ($pram, $val) = each %{$arg} ) {
146 if( $pram eq 'table' ) { next; }
147 if( $pram eq 'primkey' ) { next; }
148 push(@update_l, "$pram='$val'");
149 }
150 my $update_str= join(", ", @update_l);
151 $update_str= " SET $update_str";
153 my $sql_statement= "UPDATE $table $update_str $prim_statement";
154 my $db_res = &update_dbentry($self, $sql_statement );
155 }
157 return 0;
158 }
161 sub update_dbentry {
162 my ($self, $sql)= @_;
163 my $db_answer= &exec_statement($self, $sql);
164 return $db_answer;
165 }
168 sub del_dbentry {
169 my ($self, $sql)= @_;
170 my $db_res= &exec_statement($self, $sql);
171 return $db_res;
172 }
175 sub get_table_columns {
176 my $self = shift;
177 my $table = shift;
178 my @column_names;
180 my @res;
181 eval {
182 my $sth = $self->{dbh}->prepare("describe $table") or &main::daemon_log("ERROR: Preparation of statement 'describe $table' failed!", 1);
183 $sth->execute or &main::daemon_log("ERROR: Execution of statement 'describe $table' failed!", 1);
184 @res = @{ $sth->fetchall_arrayref() };
185 $sth->finish or &main::daemon_log("ERROR: Finishing the statement handle failed!", 1);
186 };
187 if($@) {
188 &main::daemon_log("ERROR: describe ('$table') failed with $@", 1);
189 }
191 foreach my $column (@res) {
192 push(@column_names, @$column[0]);
193 }
195 return \@column_names;
196 }
199 sub select_dbentry {
200 my ($self, $sql)= @_;
201 my $error= 0;
202 my $answer= {};
203 my $db_answer= &exec_statement($self, $sql);
204 my @column_list;
206 # fetch column list of db and create a hash with column_name->column_value of the select query
207 $sql =~ /SELECT ([\S\s]*?) FROM ([\S]*?)( |$)/g;
208 my $selected_cols = $1;
209 my $table = $2;
211 # all columns are used for creating answer
212 if ($selected_cols eq '*') {
213 @column_list = @{ &get_table_columns($self, $table) };
215 # specific columns are used for creating answer
216 } else {
217 # remove all blanks and split string to list of column names
218 $selected_cols =~ s/ //g;
219 @column_list = split(/,/, $selected_cols);
220 }
222 # create answer
223 my $hit_counter = 0;
224 my $list_len = @column_list;
225 foreach my $hit ( @{$db_answer} ){
226 $hit_counter++;
227 for ( my $i = 0; $i < $list_len; $i++) {
228 $answer->{ $hit_counter }->{ $column_list[$i] } = @{ $hit }[$i];
229 }
230 }
232 return $answer;
233 }
236 sub show_table {
237 my $self = shift;
238 my $table_name = shift;
240 my $sql_statement= "SELECT * FROM $table_name ORDER BY timestamp";
241 my $res= &exec_statement($self, $sql_statement);
242 my @answer;
243 foreach my $hit (@{$res}) {
244 push(@answer, "hit: ".join(', ', @{$hit}));
245 }
247 return join("\n", @answer);
248 }
251 sub exec_statement {
252 my $self = shift;
253 my $sql_statement = shift;
254 my $sth;
255 my @db_answer;
257 # print STDERR Dumper($sql_statement);
258 # eval {
259 if($sql_statement =~ /^SELECT/i) {
260 $sth = $self->{dbh}->prepare($sql_statement) or &main::daemon_log("0 ERROR: Preparation of statement '$sql_statement' failed!", 1);
261 $sth->execute or &main::daemon_log("0 ERROR: Execution of statement '$sql_statement' failed!", 1);
262 if($sth->rows > 0) {
263 @db_answer = @{ $sth->fetchall_arrayref() } or &main::daemon_log("0 ERROR: Fetch() failed!", 1);
264 # print STDERR Dumper(@db_answer);
265 }
266 $sth->finish or &main::daemon_log("0 ERROR: Finishing the statement handle failed!", 1);
267 } else {
268 $self->{dbh}->do($sql_statement);
269 }
270 # };
271 # if($@) {
272 # &main::daemon_log("0 ERROR: '$sql_statement' failed with '$@'", 1);
273 # }
274 # TODO : maybe an error handling and an erro feedback to invoking function
275 my $error = $self->{dbh}->err;
276 if ($error) {
277 &main::daemon_log("0 ERROR: ".@$self->{dbh}->errstr, 1);
278 }
280 return \@db_answer;
281 }
284 sub exec_statementlist {
285 my $self = shift;
286 my $sql_list = shift;
287 my @db_answer;
289 foreach my $sql (@$sql_list) {
290 if(defined($sql) && length($sql) > 0) {
291 # &main::daemon_log("DEBUG: $sql");
292 eval {
293 if($sql =~ /^SELECT/i) {
294 my $sth = $self->{dbh}->prepare($sql);
295 # &main::daemon_log("DEBUG: ".$sth->execute);
296 if($sth->rows > 0) {
297 my @answer = @{$sth->fetchall_arrayref()};
298 push @db_answer, @answer;
299 }
300 $sth->finish;
301 } else {
302 $self->{dbh}->do($sql);
303 }
304 };
305 if($@) {
306 &main::daemon_log("ERROR: $sql failed with $@", 1);
307 }
308 } else {
309 next;
310 }
311 }
313 return \@db_answer;
314 }
317 sub count_dbentries {
318 my ($self, $table)= @_;
319 my $error= 0;
320 my $answer= -1;
322 my $sql_statement= "SELECT * FROM $table";
323 my $db_answer= &select_dbentry($self, $sql_statement);
325 my $count = keys(%{$db_answer});
326 return $count;
327 }
330 sub move_table {
331 my ($self, $from, $to) = @_;
333 my $sql_statement_drop = "DROP TABLE IF EXISTS $to";
334 my $sql_statement_alter = "ALTER TABLE $from RENAME TO $to";
336 eval {
337 $self->{dbh}->do($sql_statement_drop);
338 $self->{dbh}->do($sql_statement_alter);
339 };
341 if($@) {
342 &main::daemon_log("ERROR: $sql_statement_drop failed with $@", 1);
343 }
345 return;
346 }
349 1;