1 package GOSA::DBmysql;
3 use strict;
4 use warnings;
5 use DBI;
6 use Data::Dumper;
7 use GOSA::GosaSupportDaemon;
8 use Time::HiRes qw(usleep);
10 my $col_names = {};
12 sub new {
13 my $class = shift;
14 my $database = shift;
15 my $host = shift;
16 my $username = shift;
17 my $password = shift;
19 my $self = {dbh=>undef};
20 my $dbh = DBI->connect("dbi:mysql:database=$database;host=$host", $username, $password,{ RaiseError => 1, AutoCommit => 1 });
21 $dbh->{mysql_auto_reconnect} = 1;
22 $self->{dbh} = $dbh;
23 bless($self,$class);
25 return($self);
26 }
29 sub create_table {
30 my $self = shift;
31 my $table_name = shift;
32 my $col_names_ref = shift;
33 my $recreate_table = shift || 0;
34 my @col_names;
35 my $col_names_string = join(", ", @$col_names_ref);
37 if($recreate_table) {
38 $self->{dbh}->do("DROP TABLE $table_name");
39 }
40 my $sql_statement = "CREATE TABLE IF NOT EXISTS $table_name ( $col_names_string ) ENGINE=INNODB";
41 # &main::daemon_log("DEBUG: $sql_statement");
42 eval {
43 $self->{dbh}->do($sql_statement);
44 };
45 if($@) {
46 &main::daemon_log("ERROR: $sql_statement failed with $@", 1);
47 }
49 return 0;
50 }
53 sub add_dbentry {
54 my $self = shift;
55 my $arg = shift;
56 my $res = 0; # default value
58 # if dbh not specified, return errorflag 1
59 my $table = $arg->{table};
60 if( not defined $table ) {
61 return 1 ;
62 }
64 # if timestamp is not provided, add timestamp
65 if( not exists $arg->{timestamp} ) {
66 $arg->{timestamp} = &get_time;
67 }
69 # check primkey and run insert or update
70 my $primkeys = $arg->{'primkey'};
71 my $prim_statement="";
72 if( 0 != @$primkeys ) { # more than one primkey exist in list
73 my @prim_list;
74 foreach my $primkey (@$primkeys) {
75 if( not exists $arg->{$primkey} ) {
76 return (3, "primkey '$primkey' has no value for add_dbentry");
77 }
78 push(@prim_list, "$primkey='".$arg->{$primkey}."'");
79 }
80 $prim_statement = "WHERE ".join(" AND ", @prim_list);
82 # check wether primkey is unique in table, otherwise return errorflag
83 my $sql_statement = "SELECT * FROM $table $prim_statement";
84 eval {
85 # &main::daemon_log("DEBUG: $sql_statement");
86 my $sth = $self->{dbh}->prepare($sql_statement);
87 $sth->execute;
88 $res = @{ $sth->fetchall_arrayref() };
89 $sth->finish;
90 };
91 if($@) {
92 &main::daemon_log("ERROR: $sql_statement failed with $@", 1);
93 }
95 }
97 # primkey is unique or no primkey specified -> run insert
98 if ($res == 0) {
99 # fetch column names of table
100 my $col_names = &get_table_columns($self, $table);
102 #my $create_id=0;
103 #foreach my $col_name (@{$col_names}) {
104 # #if($col_name eq "id" && (! exists $arg->{$col_name})) {
105 # #&main::daemon_log("0 DEBUG: id field found without value! Creating autoincrement statement!", 7);
106 # $create_id=1;
107 # }
108 #}
110 # assign values to column name variables
111 my @col_list;
112 my @val_list;
113 foreach my $col_name (@{$col_names}) {
114 # use function parameter for column values
115 if (exists $arg->{$col_name}) {
116 push(@col_list, $col_name);
117 push(@val_list, "'".$arg->{$col_name}."'");
118 }
119 }
121 my $sql_statement;
122 #if($create_id==1) {
123 # $sql_statement = "INSERT INTO $table (id, ".join(", ", @col_list).") VALUES ((select coalesce(max(id),0)+1), ".join(", ", @val_list).")";
124 #} else {
125 $sql_statement = "INSERT INTO $table (".join(", ", @col_list).") VALUES (".join(", ", @val_list).")";
126 #}
127 my $db_res;
128 # &main::daemon_log("DEBUG: $sql_statement",1);
129 eval {
130 $db_res = $self->{dbh}->do($sql_statement);
131 };
132 if($@) {
133 &main::daemon_log("ERROR: $sql_statement failed with $@", 1);
134 }
136 if( $db_res != 1 ) {
137 return (4, $sql_statement);
138 }
140 # entry already exists -> run update
141 } else {
142 my @update_l;
143 while( my ($pram, $val) = each %{$arg} ) {
144 if( $pram eq 'table' ) { next; }
145 if( $pram eq 'primkey' ) { next; }
146 push(@update_l, "$pram='$val'");
147 }
148 my $update_str= join(", ", @update_l);
149 $update_str= " SET $update_str";
151 my $sql_statement= "UPDATE $table $update_str $prim_statement";
152 my $db_res = &update_dbentry($self, $sql_statement );
153 }
155 return 0;
156 }
159 sub update_dbentry {
160 my ($self, $sql)= @_;
161 my $db_answer= &exec_statement($self, $sql);
162 return $db_answer;
163 }
166 sub del_dbentry {
167 my ($self, $sql)= @_;
168 my $db_res= &exec_statement($self, $sql);
169 return $db_res;
170 }
173 sub get_table_columns {
174 my $self = shift;
175 my $table = shift;
176 my @column_names;
178 my @res;
179 eval {
180 my $sth = $self->{dbh}->prepare("describe $table") or &main::daemon_log("ERROR: Preparation of statement 'describe $table' failed!", 1);
181 $sth->execute or &main::daemon_log("ERROR: Execution of statement 'describe $table' failed!", 1);
182 @res = @{ $sth->fetchall_arrayref() };
183 $sth->finish or &main::daemon_log("ERROR: Finishing the statement handle failed!", 1);
184 };
185 if($@) {
186 &main::daemon_log("ERROR: describe ('$table') failed with $@", 1);
187 }
189 foreach my $column (@res) {
190 push(@column_names, @$column[0]);
191 }
193 return \@column_names;
194 }
197 sub select_dbentry {
198 my ($self, $sql)= @_;
199 my $error= 0;
200 my $answer= {};
201 my $db_answer= &exec_statement($self, $sql);
202 my @column_list;
204 # fetch column list of db and create a hash with column_name->column_value of the select query
205 $sql =~ /SELECT ([\S\s]*?) FROM ([\S]*?)( |$)/g;
206 my $selected_cols = $1;
207 my $table = $2;
209 # all columns are used for creating answer
210 if ($selected_cols eq '*') {
211 @column_list = @{ &get_table_columns($self, $table) };
213 # specific columns are used for creating answer
214 } else {
215 # remove all blanks and split string to list of column names
216 $selected_cols =~ s/ //g;
217 @column_list = split(/,/, $selected_cols);
218 }
220 # create answer
221 my $hit_counter = 0;
222 my $list_len = @column_list;
223 foreach my $hit ( @{$db_answer} ){
224 $hit_counter++;
225 for ( my $i = 0; $i < $list_len; $i++) {
226 $answer->{ $hit_counter }->{ $column_list[$i] } = @{ $hit }[$i];
227 }
228 }
230 return $answer;
231 }
234 sub show_table {
235 my $self = shift;
236 my $table_name = shift;
238 my $sql_statement= "SELECT * FROM $table_name ORDER BY timestamp";
239 my $res= &exec_statement($self, $sql_statement);
240 my @answer;
241 foreach my $hit (@{$res}) {
242 push(@answer, "hit: ".join(', ', @{$hit}));
243 }
245 return join("\n", @answer);
246 }
249 sub exec_statement {
250 my $self = shift;
251 my $sql_statement = shift;
252 my $sth;
253 my @db_answer;
255 # print STDERR Dumper($sql_statement);
256 # eval {
257 if($sql_statement =~ /^SELECT/i) {
258 $sth = $self->{dbh}->prepare($sql_statement) or &main::daemon_log("0 ERROR: Preparation of statement '$sql_statement' failed!", 1);
259 $sth->execute or &main::daemon_log("0 ERROR: Execution of statement '$sql_statement' failed!", 1);
260 if($sth->rows > 0) {
261 @db_answer = @{ $sth->fetchall_arrayref() } or &main::daemon_log("0 ERROR: Fetch() failed!", 1);
262 # print STDERR Dumper(@db_answer);
263 }
264 $sth->finish or &main::daemon_log("0 ERROR: Finishing the statement handle failed!", 1);
265 } else {
266 $self->{dbh}->do($sql_statement);
267 }
268 # };
269 # if($@) {
270 # &main::daemon_log("0 ERROR: '$sql_statement' failed with '$@'", 1);
271 # }
272 # TODO : maybe an error handling and an erro feedback to invoking function
273 my $error = $self->{dbh}->err;
274 if ($error) {
275 &main::daemon_log("0 ERROR: ".@$self->{dbh}->errstr, 1);
276 }
278 return \@db_answer;
279 }
282 sub exec_statementlist {
283 my $self = shift;
284 my $sql_list = shift;
285 my @db_answer;
287 foreach my $sql (@$sql_list) {
288 if(defined($sql) && length($sql) > 0) {
289 # &main::daemon_log("DEBUG: $sql");
290 eval {
291 if($sql =~ /^SELECT/i) {
292 my $sth = $self->{dbh}->prepare($sql);
293 # &main::daemon_log("DEBUG: ".$sth->execute);
294 if($sth->rows > 0) {
295 my @answer = @{$sth->fetchall_arrayref()};
296 push @db_answer, @answer;
297 }
298 $sth->finish;
299 } else {
300 $self->{dbh}->do($sql);
301 }
302 };
303 if($@) {
304 &main::daemon_log("ERROR: $sql failed with $@", 1);
305 }
306 } else {
307 next;
308 }
309 }
311 return \@db_answer;
312 }
315 sub count_dbentries {
316 my ($self, $table)= @_;
317 my $error= 0;
318 my $answer= -1;
320 my $sql_statement= "SELECT * FROM $table";
321 my $db_answer= &select_dbentry($self, $sql_statement);
323 my $count = keys(%{$db_answer});
324 return $count;
325 }
328 sub move_table {
329 my ($self, $from, $to) = @_;
331 my $sql_statement_drop = "DROP TABLE IF EXISTS $to";
332 my $sql_statement_alter = "ALTER TABLE $from RENAME TO $to";
334 eval {
335 $self->{dbh}->do($sql_statement_drop);
336 $self->{dbh}->do($sql_statement_alter);
337 };
339 if($@) {
340 &main::daemon_log("ERROR: $sql_statement_drop failed with $@", 1);
341 }
343 return;
344 }
347 1;