| 1 | ############################################################################### | ||
| 2 | # DBIx::Wrap | ||
| 3 | # | ||
| 4 | # Copyright (c) 2002 Jonathan A. Waxman <jowaxman@bbl.med.upenn.edu> | ||
| 5 | # All rights reserved. | ||
| 6 | # | ||
| 7 | # This program is free software; you can redistribute it and/or | ||
| 8 | # modify it under the same terms as Perl itself. | ||
| 9 | ############################################################################### | ||
| 10 | package DBIx::Wrap; | ||
| 11 | |||
| 12 | |||
| 13 | use strict; | ||
| 14 | use vars qw($VERSION); | ||
| 15 | use DBI; | ||
| 16 | use Time::Local; | ||
| 17 | |||
| 18 | $VERSION = '1.00'; | ||
| 19 | |||
| 20 | |||
| 21 | =pod | ||
| 22 | |||
| 23 | =head1 NAME | ||
| 24 | |||
| 25 | DBIx::Wrap - Object oriented wrapper around DBI. | ||
| 26 | |||
| 27 | =head1 SYNOPSIS | ||
| 28 | |||
| 29 | use DBIx::Wrap; | ||
| 30 | |||
| 31 | my $dsn = "DBI:mysql:database=accounts"; | ||
| 32 | $db = DBIx::Wrap->new (DSN => $dsn, User => 'jowaxman', | ||
| 33 | Password => 'plipplop'); | ||
| 34 | |||
| 35 | # select | ||
| 36 | # Return a hash reference. | ||
| 37 | $user = $db->select (Table => 'passwd', | ||
| 38 | Fields => 'gcos,homedir,shell', | ||
| 39 | Where => "username='jowaxman'"); | ||
| 40 | $gcos = $user->{gcos}; | ||
| 41 | |||
| 42 | # Set the table. | ||
| 43 | $db->table ('employees'); | ||
| 44 | |||
| 45 | # Return an array of values. | ||
| 46 | @info = $db->select (Fields => 'ssn,address,phone', | ||
| 47 | Where => "ssn='123456789'"); | ||
| 48 | $ssn = $info[1]; | ||
| 49 | |||
| 50 | # iterate | ||
| 51 | my $id; | ||
| 52 | while (my ($username, $gcos) = $db->each (\$id, | ||
| 53 | Tables => 'passwd,employees', | ||
| 54 | Fields => 'passwd.username,address,phone', | ||
| 55 | Where => "passwd.username=employees.username and | ||
| 56 | employees.status='fulltime'")) { | ||
| 57 | # Note, could have done | ||
| 58 | # while (my $employee = $db->each (... | ||
| 59 | # to get a hash. | ||
| 60 | } | ||
| 61 | |||
| 62 | # insert | ||
| 63 | $db->insert (Table => 'passwd', | ||
| 64 | Values => {username => $username, | ||
| 65 | uid => $uid, | ||
| 66 | gcos => $gcos, | ||
| 67 | ...}); | ||
| 68 | |||
| 69 | # delete | ||
| 70 | $db->delete (Table => 'passwd', | ||
| 71 | Where => "username='jowaxman'"); | ||
| 72 | |||
| 73 | =head1 DESCRIPTION | ||
| 74 | |||
| 75 | This module is a wrapper around the DBI database class. It simplifies | ||
| 76 | database querying. You may use this as a base class for a derived class | ||
| 77 | that operates on a specific kind of database. | ||
| 78 | |||
| 79 | =head1 CONSTRUCTOR | ||
| 80 | |||
| 81 | You must give the constructor the named parameters DSN, User, and | ||
| 82 | Password so DBI can connect to the database. | ||
| 83 | |||
| 84 | =cut | ||
| 85 | |||
| 86 | sub new { | ||
| 87 | # Create myself. | ||
| 88 | my $proto = shift; | ||
| 89 | |||
| 90 | my $class = ref ($proto) || $proto; | ||
| 91 | my $self = {}; | ||
| 92 | bless ($self, $class); | ||
| 93 | |||
| 94 | # Get params. | ||
| 95 | my %params = @_; | ||
| 96 | |||
| 97 | $self->{_sth} = {}; | ||
| 98 | |||
| 99 | $self->{_dsn} = $params{DSN}; | ||
| 100 | $self->{_user} = $params{User}; | ||
| 101 | |||
| 102 | $self->{_dbh} = eval {DBI->connect ($self->{_dsn}, $self->{_user}, | ||
| 103 | $params{Password}, | ||
| 104 | {RaiseError => 0, | ||
| 105 | PrintError => 0})}; | ||
| 106 | return $proto->error ($@) if $@; | ||
| 107 | return $proto->error ($DBIx::errstr) if ! defined $self->{_dbh}; | ||
| 108 | |||
| 109 | return $self; | ||
| 110 | } | ||
| 111 | |||
| 112 | =head1 ERROR HANDLING | ||
| 113 | |||
| 114 | DBIx::Wrap provides the public method C<error> to do simple error | ||
| 115 | handling. If an argument is given (the error), it is stored, otherwise, | ||
| 116 | the stored error is returned. | ||
| 117 | |||
| 118 | C<error> may be called as a package method (e.g., C<DBIx::Wrap-E<gt>error | ||
| 119 | ($error);> or as an object method (e.g., C<$db-E<gt>error ($error);>. If | ||
| 120 | it is called as a package method, the error is stored as a package | ||
| 121 | variable. If it is called as an object method, the error is stored as a | ||
| 122 | private variable. | ||
| 123 | |||
| 124 | =cut | ||
| 125 | |||
| 126 | sub error { | ||
| 127 | my $self = shift; | ||
| 128 | my $error = shift; | ||
| 129 | |||
| 130 | # If an error given, set it in the object or package. | ||
| 131 | # Otherwise, return the error from the object or package. | ||
| 132 | if (defined $error) { | ||
| 133 | ref ($self) ? $self->{_error} = $error : $self::_error = $error; | ||
| 134 | return undef; | ||
| 135 | } else { | ||
| 136 | return ref ($self) ? $self->{_error} : $self::_error; | ||
| 137 | } | ||
| 138 | } | ||
| 139 | |||
| 140 | =pod | ||
| 141 | |||
| 142 | =head1 PRIVATE METHODS | ||
| 143 | |||
| 144 | =head2 _prepare_sql | ||
| 145 | |||
| 146 | my $sql = $self->_prepare_sql ('select', \%params); | ||
| 147 | |||
| 148 | This private method prepares an sql statement given a set of named | ||
| 149 | parameters. See the DBI or SQL documentation for more information on | ||
| 150 | valid SQL phrases. The following named parameters are used: | ||
| 151 | |||
| 152 | =over 4 | ||
| 153 | |||
| 154 | =item Table or Tables | ||
| 155 | |||
| 156 | Specified the database table or tables. You can fix the table by using | ||
| 157 | the | ||
| 158 | method table (see below). | ||
| 159 | |||
| 160 | =item Field or Fields | ||
| 161 | |||
| 162 | Single field name or comma separated list of field names. | ||
| 163 | |||
| 164 | =item Where | ||
| 165 | |||
| 166 | A valid SQL WHERE clause. | ||
| 167 | |||
| 168 | =item Values | ||
| 169 | |||
| 170 | An anonymous hash containing column name/value pairs. | ||
| 171 | |||
| 172 | =item OrderBy | ||
| 173 | |||
| 174 | The ordering criteria. | ||
| 175 | |||
| 176 | =item Limit | ||
| 177 | |||
| 178 | A constraint limiting the number of rows returned. | ||
| 179 | |||
| 180 | =back 4 | ||
| 181 | |||
| 182 | =cut | ||
| 183 | |||
| 184 | sub _prepare_sql { | ||
| 185 | my $self = shift; | ||
| 186 | my ($type, $params) = @_; | ||
| 187 | |||
| 188 | my $table; | ||
| 189 | if (exists $self->{_table}) { | ||
| 190 | $table = $self->{_table}; | ||
| 191 | } else { | ||
| 192 | if (exists $params->{Table}) { | ||
| 193 | $table = $params->{Table}; | ||
| 194 | } elsif (exists $params->{Tables}) { | ||
| 195 | $table = $params->{Tables}; | ||
| 196 | } elsif ($type ne 'show') { | ||
| 197 | return $self->error ("$type: No Table parameter given."); | ||
| 198 | } | ||
| 199 | } | ||
| 200 | my $where = $params->{Where} if exists $params->{Where}; | ||
| 201 | my $orderby = $params->{OrderBy} if exists $params->{OrderBy}; | ||
| 202 | my $limit = $params->{Limit} if exists $params->{Limit}; | ||
| 203 | my $match = $params->{Match} if exists $params->{Match}; | ||
| 204 | |||
| 205 | my $sql; | ||
| 206 | if ($type eq 'select') { | ||
| 207 | my $fields; | ||
| 208 | if (exists $params->{Fields}) { | ||
| 209 | $fields = $params->{Fields}; | ||
| 210 | } elsif (exists $params->{Field}) { | ||
| 211 | $fields = $params->{Field}; | ||
| 212 | } else { | ||
| 213 | $fields = '*'; | ||
| 214 | } | ||
| 215 | |||
| 216 | if (defined $match) { | ||
| 217 | $fields .= ',' if defined $fields; | ||
| 218 | if (defined $params->{Round} && $params->{Round} eq 'yes') { | ||
| 219 | $fields .= "ROUND(MATCH $match) AS _score"; | ||
| 220 | } else { | ||
| 221 | $fields .= "MATCH $match AS _score"; | ||
| 222 | } | ||
| 223 | $where .= ' and ' if defined $where; | ||
| 224 | $where .= "MATCH $match"; | ||
| 225 | } | ||
| 226 | |||
| 227 | $sql = "SELECT $fields FROM $table"; | ||
| 228 | $sql .= " WHERE $where" if defined $where; | ||
| 229 | $sql .= " ORDER BY $orderby" if defined $orderby; | ||
| 230 | $sql .= " LIMIT $limit" if defined $limit; | ||
| 231 | |||
| 232 | } elsif ($type eq 'insert') { | ||
| 233 | return $self->error ('insert: No Values parameter given.') | ||
| 234 | if ! defined $params->{Values}; | ||
| 235 | |||
| 236 | $sql = "INSERT INTO $table ("; | ||
| 237 | my ($col_names, $values); | ||
| 238 | foreach my $field (keys %{$params->{Values}}) { | ||
| 239 | $col_names .= ',' if defined $col_names; | ||
| 240 | $col_names .= $field; | ||
| 241 | $values .= ',' if defined $values; | ||
| 242 | if (exists $params->{Values}->{$field} && | ||
| 243 | ! defined $params->{Values}->{$field}) { | ||
| 244 | # If a CSV database, using null for an empty value will result in | ||
| 245 | # absent colons so you must set an empty string value. | ||
| 246 | if (exists $self->{_dbh}->{csv_tables}) { | ||
| 247 | $values .= "''"; | ||
| 248 | } else { | ||
| 249 | $values .= 'null'; | ||
| 250 | } | ||
| 251 | } else { | ||
| 252 | $params->{Values}->{$field} =~ s/'/''/g; | ||
| 253 | # xxx | ||
| 254 | if ($params->{Values}->{$field} =~ /FROM_UNIXTIME/ | ||
| 255 | || $params->{Values}->{$field} =~ /NOW/) { | ||
| 256 | $values .= "$params->{Values}->{$field}"; | ||
| 257 | } else { | ||
| 258 | $values .= "'$params->{Values}->{$field}'"; | ||
| 259 | } | ||
| 260 | } | ||
| 261 | } | ||
| 262 | $sql .= "$col_names) VALUES ($values)"; | ||
| 263 | |||
| 264 | } elsif ($type eq 'update') { | ||
| 265 | return $self->error ('insert: No Values parameter given.') | ||
| 266 | if ! defined $params->{Values}; | ||
| 267 | |||
| 268 | $sql = "UPDATE $table SET "; | ||
| 269 | my ($col_names, $values); | ||
| 270 | foreach my $field (keys %{$params->{Values}}) { | ||
| 271 | $col_names .= ',' if defined $col_names; | ||
| 272 | if (exists $params->{Values}->{$field} && | ||
| 273 | ! defined $params->{Values}->{$field}) { | ||
| 274 | # If a CSV database, using null for an empty value will result in | ||
| 275 | # absent colons so you must set an empty string value. | ||
| 276 | if (exists $self->{_dbh}->{csv_tables}) { | ||
| 277 | $col_names .= "$field=''"; | ||
| 278 | } else { | ||
| 279 | $col_names .= "$field=null"; | ||
| 280 | } | ||
| 281 | } else { | ||
| 282 | $params->{Values}->{$field} =~ s/'/''/g; | ||
| 283 | $col_names .= "$field='$params->{Values}->{$field}'"; | ||
| 284 | } | ||
| 285 | } | ||
| 286 | $sql .= $col_names; | ||
| 287 | $sql .= " WHERE $where" if defined $where; | ||
| 288 | |||
| 289 | } elsif ($type eq 'delete') { | ||
| 290 | $sql = "DELETE FROM $table"; | ||
| 291 | $sql .= " WHERE $where" if defined $where; | ||
| 292 | |||
| 293 | } elsif ($type eq 'describe') { | ||
| 294 | my $fields; | ||
| 295 | if (exists $params->{Fields}) { | ||
| 296 | $fields = $params->{Fields}; | ||
| 297 | } elsif (exists $params->{Field}) { | ||
| 298 | $fields = $params->{Field}; | ||
| 299 | } else { | ||
| 300 | $fields = '%'; | ||
| 301 | } | ||
| 302 | $sql = "DESCRIBE $table '$fields'"; | ||
| 303 | |||
| 304 | } elsif ($type eq 'alter') { | ||
| 305 | return $self->error ('alter: No Action parameter given.') | ||
| 306 | if ! defined $params->{Action}; | ||
| 307 | |||
| 308 | my $action = $params->{Action}; | ||
| 309 | |||
| 310 | $sql = "ALTER TABLE $params->{Table} ";# . uc $action . " "; | ||
| 311 | |||
| 312 | if ($action eq 'add') { | ||
| 313 | my $columns = $params->{Columns} || $params->{Column}; | ||
| 314 | |||
| 315 | if (defined $params->{PrimaryKey} && $params->{PrimaryKey}) { | ||
| 316 | return $self->error ('alter [ADD PRIMARY KEY]: No Column[s] parameter given.') | ||
| 317 | if ! defined $columns; | ||
| 318 | |||
| 319 | $sql .= "ADD PRIMARY KEY $columns"; | ||
| 320 | } elsif ((defined $params->{Unique} && $params->{Unique}) || | ||
| 321 | (defined $params->{FullText} && $params->{FullText})) { | ||
| 322 | my $add = $params->{Unique} ? 'UNIQUE' : 'FULLTEXT'; | ||
| 323 | |||
| 324 | return $self->error ("alter [ADD $add]: No Column[s] parameter given.") | ||
| 325 | if ! defined $columns; | ||
| 326 | |||
| 327 | $sql .= "ADD $add"; | ||
| 328 | $sql .= " $params->{Index}" if defined $params->{Index}; | ||
| 329 | $sql .= " ($columns)"; | ||
| 330 | |||
| 331 | # Index must come after Unique/Fulltext. | ||
| 332 | } elsif (defined $params->{Index}) { | ||
| 333 | return $self->error ('alter [ADD INDEX]: No Column[s] parameter given.') | ||
| 334 | if ! defined $columns; | ||
| 335 | |||
| 336 | $sql .= "ADD INDEX $params->{Index} ($columns)"; | ||
| 337 | |||
| 338 | } elsif (defined $params->{Definition}) { | ||
| 339 | return $self->error ('alter [ADD]: No Column parameter given.') | ||
| 340 | if ! defined $params->{Column}; | ||
| 341 | |||
| 342 | $sql .= "ADD $params->{Column} "; | ||
| 343 | $sql .= $self->_prepare_definition ($params->{Definition}) | ||
| 344 | || return $self->error ("alter [ADD]: " . $self->error ()); | ||
| 345 | $sql .= " $params->{Position}" if defined $params->{Position}; | ||
| 346 | } | ||
| 347 | |||
| 348 | } elsif ($action eq 'alter') { | ||
| 349 | return $self->error ('alter [ALTER]: No Column parameter given.') | ||
| 350 | if ! defined $params->{Column}; | ||
| 351 | return $self->error ('alter [ALTER]: No Default parameter given.') | ||
| 352 | if ! exists $params->{Default}; | ||
| 353 | |||
| 354 | $sql .= "ALTER $params->{Column}"; | ||
| 355 | # xxx default needs to be a literal. | ||
| 356 | $sql .= defined $params->{Default} ? " SET DEFAULT $params->{Default}" | ||
| 357 | : ' DROP DEFAULT'; | ||
| 358 | |||
| 359 | } elsif ($action eq 'change') { | ||
| 360 | return $self->error ('alter [CHANGE]: No Column parameter given.') | ||
| 361 | if ! defined $params->{Column}; | ||
| 362 | return $self->error ('alter [CHANGE]: No Definition parameter given.') | ||
| 363 | if ! defined $params->{Definition}; | ||
| 364 | |||
| 365 | $params->{Definition}->{Column} = $params->{Column} | ||
| 366 | if ! defined $params->{Definition}->{Column}; | ||
| 367 | |||
| 368 | $sql .= "CHANGE $params->{Column} "; | ||
| 369 | $sql .= $self->_prepare_definition ($params->{Definition}) | ||
| 370 | || return $self->error ("alter [CHANGE]: " . $self->error ()); | ||
| 371 | |||
| 372 | } elsif ($action eq 'modify') { | ||
| 373 | return $self->error ('alter [MODIFY]: No Column parameter given.') | ||
| 374 | if ! defined $params->{Column}; | ||
| 375 | return $self->error ('alter [MODIFY]: No Definition parameter given.') | ||
| 376 | if ! defined $params->{Definition}; | ||
| 377 | |||
| 378 | $sql .= "MODIFY "; | ||
| 379 | $sql .= $self->_prepare_definition ($params->{Definition}) | ||
| 380 | || return $self->error ("alter [MODIFY]: " . $self->error ()); | ||
| 381 | $sql .= " " . $params->{Position} if defined $params->{Position}; | ||
| 382 | |||
| 383 | } elsif ($action eq 'drop') { | ||
| 384 | if (defined $params->{PrimaryKey} && $params->{PrimaryKey}) { | ||
| 385 | $sql .= "DROP PRIMARY KEY"; | ||
| 386 | |||
| 387 | } elsif (defined $params->{Index}) { | ||
| 388 | return $self->error ('alter [DROP INDEX]: No Index parameter given.') | ||
| 389 | if ! defined $params->{Index}; | ||
| 390 | |||
| 391 | $sql .= "DROP INDEX $params->{Index}"; | ||
| 392 | |||
| 393 | } else { | ||
| 394 | return $self->error ('alter [DROP]: No Column parameter given.') | ||
| 395 | if ! defined $params->{Column}; | ||
| 396 | |||
| 397 | $sql .= "DROP $params->{Column}"; | ||
| 398 | } | ||
| 399 | |||
| 400 | } elsif ($action eq 'disable_keys') { | ||
| 401 | $sql .= "DISABLE KEYS"; | ||
| 402 | |||
| 403 | } elsif ($action eq 'enable_keys') { | ||
| 404 | $sql .= "ENABLE KEYS"; | ||
| 405 | |||
| 406 | } elsif ($action eq 'rename') { | ||
| 407 | return $self->error ('alter [RENAME]: No NewTable parameter given.') | ||
| 408 | if ! defined $params->{NewTable}; | ||
| 409 | |||
| 410 | $sql .= "RENAME $params->{NewTable}"; | ||
| 411 | |||
| 412 | } elsif ($action eq 'orderby') { | ||
| 413 | return $self->error ('alter [ORDER BY]: No Column parameter given.') | ||
| 414 | if ! defined $params->{Column}; | ||
| 415 | |||
| 416 | $sql .= "ORDER BY $params->{Column}"; | ||
| 417 | } | ||
| 418 | |||
| 419 | } elsif ($type eq 'show') { | ||
| 420 | return $self->error ('show: No Action parameter given.') | ||
| 421 | if ! defined $params->{Action}; | ||
| 422 | |||
| 423 | my $action = $params->{Action}; | ||
| 424 | |||
| 425 | $sql = "SHOW "; | ||
| 426 | |||
| 427 | if ($action eq 'table_status') { | ||
| 428 | $sql .= "TABLE STATUS"; | ||
| 429 | $sql .= " LIKE '$table'" if defined $table; | ||
| 430 | } | ||
| 431 | } | ||
| 432 | |||
| 433 | return $sql; | ||
| 434 | } | ||
| 435 | |||
| 436 | sub _prepare_definition { | ||
| 437 | my $self = shift; | ||
| 438 | my $params = shift; | ||
| 439 | |||
| 440 | my $definition; | ||
| 441 | |||
| 442 | return $self->error ('No Definition Type parameter given.') | ||
| 443 | if ! defined $params->{Type}; | ||
| 444 | return $self->error ('No Definition Length parameter given.') | ||
| 445 | if $params->{Type} =~ /^(decimal)|(numeric)|(char)|(varchar)$/i && | ||
| 446 | ! defined $params->{Length}; | ||
| 447 | return $self->error ('No Definition Decimals parameter given.') | ||
| 448 | if ($params->{Type} =~ /^(decimal)|(numeric)$/i || | ||
| 449 | (defined $params->{Length} && | ||
| 450 | $params->{Type} =~ /^(real)|(double)|(float)$/i)) && | ||
| 451 | ! defined $params->{Decimals}; | ||
| 452 | return $self->error ('No Definition Values parameter given.') | ||
| 453 | if $params->{Type} =~ /^(set)|(enum)$/i && | ||
| 454 | (! defined $params->{Values} || ! scalar @{$params->{Values}}); | ||
| 455 | |||
| 456 | $definition .= "$params->{Column} " if defined $params->{Column}; | ||
| 457 | $definition .= "$params->{Type}"; | ||
| 458 | if (defined $params->{Length}) { | ||
| 459 | $definition .= "($params->{Length}"; | ||
| 460 | $definition .= ",$params->{Decimals}" if defined $params->{Decimals}; | ||
| 461 | $definition .= ")"; | ||
| 462 | } elsif (defined $params->{Values}) { | ||
| 463 | $definition .= "('" . join ("','", @{$params->{Values}}) . "')"; | ||
| 464 | } | ||
| 465 | $definition .= " UNSIGNED" if defined $params->{Unsigned} && $params->{Unsigned}; | ||
| 466 | $definition .= " ZEROFILL" if defined $params->{ZeroFill} && $params->{ZeroFill}; | ||
| 467 | $definition .= " BINARY" if defined $params->{Binary} && $params->{Binary}; | ||
| 468 | $definition .= " NOT NULL" if defined $params->{Null} && ! $params->{Null}; | ||
| 469 | $definition .= " DEFAULT $params->{Default}" if defined $params->{Default}; | ||
| 470 | $definition .= " AUTO_INCREMENT" if defined $params->{AutoIncrement} && $params->{AutoIncrement}; | ||
| 471 | $definition .= " PRIMARY KEY" if defined $params->{PrimaryKey} && $params->{PrimaryKey}; | ||
| 472 | |||
| 473 | return $definition; | ||
| 474 | } | ||
| 475 | |||
| 476 | =pod | ||
| 477 | |||
| 478 | =head1 PUBLIC METHODS | ||
| 479 | |||
| 480 | =head2 table | ||
| 481 | |||
| 482 | $self->table ('passwd'); | ||
| 483 | |||
| 484 | This method fixes the table so that you do not have to specify the named | ||
| 485 | parameter Table in any database method. This is very useful for repeated | ||
| 486 | operations on the same table or when deriving a class that operates only | ||
| 487 | on one table (see DB::passwd, for example). | ||
| 488 | |||
| 489 | =cut | ||
| 490 | |||
| 491 | sub table { | ||
| 492 | my $self = shift; | ||
| 493 | my $table = shift; | ||
| 494 | |||
| 495 | $self->{_table} = $table; | ||
| 496 | } | ||
| 497 | |||
| 498 | =pod | ||
| 499 | |||
| 500 | =head2 select | ||
| 501 | |||
| 502 | $user = $db->select (Table => 'passwd', | ||
| 503 | Where => "username='jowaxman'"); | ||
| 504 | @info = $db->select (Table => 'passwd', | ||
| 505 | Fields => 'gcos,homedir,shell', | ||
| 506 | Where => "uid=12345"); | ||
| 507 | |||
| 508 | This method performs an SQL SELECT operation. See _prepare_sql for the | ||
| 509 | named parameters that are used. | ||
| 510 | |||
| 511 | If returning to a scalar, a reference to a hash containing column | ||
| 512 | name/value pairs is returned. If returning to an array, a list of values | ||
| 513 | in the same order as the fields specified in the named parameter Fields | ||
| 514 | is returned. If no named parameter Fields is given, all fields are | ||
| 515 | returned. | ||
| 516 | |||
| 517 | Note that if multiple entries match the WHERE clause, only the first will | ||
| 518 | be returned. | ||
| 519 | |||
| 520 | =cut | ||
| 521 | |||
| 522 | sub select { | ||
| 523 | my $self = shift; | ||
| 524 | my %params = @_; | ||
| 525 | |||
| 526 | my $sql = $self->_prepare_sql ('select', \%params) | ||
| 527 | || return undef; | ||
| 528 | |||
| 529 | my $sth = $self->{_dbh}->prepare ($sql); | ||
| 530 | $sth->execute | ||
| 531 | || return $self->error ("Could not execute '$sql': " | ||
| 532 | . $self->{_dbh}->errstr); | ||
| 533 | $self->{_error} = undef; | ||
| 534 | |||
| 535 | if (wantarray) { | ||
| 536 | my @row = $sth->fetchrow; | ||
| 537 | $sth->finish; | ||
| 538 | return @row; | ||
| 539 | } else { | ||
| 540 | my $hashref = $sth->fetchrow_hashref; | ||
| 541 | $sth->finish; | ||
| 542 | return $hashref; | ||
| 543 | } | ||
| 544 | } | ||
| 545 | |||
| 546 | sub selectall { | ||
| 547 | my $self = shift; | ||
| 548 | my %params = @_; | ||
| 549 | |||
| 550 | my $sql = $self->_prepare_sql ('select', \%params) | ||
| 551 | || return undef; | ||
| 552 | |||
| 553 | my $sth = $self->{_dbh}->prepare ($sql); | ||
| 554 | $sth->execute | ||
| 555 | || return $self->error ("Could not execute '$sql': " | ||
| 556 | . $self->{_dbh}->errstr); | ||
| 557 | $self->{_error} = undef; | ||
| 558 | |||
| 559 | if (wantarray) { | ||
| 560 | my @rows; | ||
| 561 | while (my @row = $sth->fetchrow) { | ||
| 562 | if (scalar (@row) == 1) { | ||
| 563 | push (@rows, $row[0]); | ||
| 564 | } else { | ||
| 565 | push (@rows, \@row); | ||
| 566 | } | ||
| 567 | } | ||
| 568 | $sth->finish; | ||
| 569 | return @rows; | ||
| 570 | } else { | ||
| 571 | my @rows; | ||
| 572 | while (my $row = $sth->fetchrow_hashref) { | ||
| 573 | push (@rows, $row); | ||
| 574 | } | ||
| 575 | $sth->finish; | ||
| 576 | return \@rows; | ||
| 577 | } | ||
| 578 | } | ||
| 579 | |||
| 580 | =pod | ||
| 581 | |||
| 582 | =head2 each | ||
| 583 | |||
| 584 | my $id; | ||
| 585 | while (my ($username, $gcos) = $db->each (\$id, | ||
| 586 | Table => 'passwd', | ||
| 587 | Fields => 'username,gcos', | ||
| 588 | )) { | ||
| 589 | # Note, could have done | ||
| 590 | # while (my $user = $db->each (... | ||
| 591 | # to get a hash. | ||
| 592 | } | ||
| 593 | |||
| 594 | Note that this method is deprecated. Use the C<iterator> method. | ||
| 595 | |||
| 596 | This method is used for iterating through multiple database entries. See | ||
| 597 | _prepare_sql for the named parameters used. | ||
| 598 | |||
| 599 | You must pass as the first arguement a reference to a scalar to store an | ||
| 600 | id for the iteration. This allows iterations to be nested without | ||
| 601 | conflict. | ||
| 602 | |||
| 603 | =cut | ||
| 604 | |||
| 605 | sub each { | ||
| 606 | my $self = shift; | ||
| 607 | my ($id, %params) = @_; | ||
| 608 | |||
| 609 | my $sth; | ||
| 610 | if (defined $$id) { | ||
| 611 | $sth = $self->{_sth}->{$$id}; | ||
| 612 | } else { | ||
| 613 | my $sql = $self->_prepare_sql ('select', \%params) | ||
| 614 | || return undef; | ||
| 615 | |||
| 616 | $sth = $self->{_dbh}->prepare ($sql); | ||
| 617 | $sth->execute | ||
| 618 | || return $self->error ("each: Could not execute: '$sql': " | ||
| 619 | . $self->{_dbh}->errstr); | ||
| 620 | $self->{_error} = undef; | ||
| 621 | |||
| 622 | $$id = scalar (keys %{$self->{_sth}}); | ||
| 623 | $self->{_sth}->{$$id} = $sth; | ||
| 624 | } | ||
| 625 | |||
| 626 | if (wantarray) { | ||
| 627 | my @row = $sth->fetchrow; | ||
| 628 | if (! @row) { | ||
| 629 | $sth->finish; | ||
| 630 | delete $self->{_sth}->{$$id}; | ||
| 631 | } | ||
| 632 | return @row; | ||
| 633 | } else { | ||
| 634 | my $hashref = $sth->fetchrow_hashref; | ||
| 635 | if (! $hashref) { | ||
| 636 | $sth->finish; | ||
| 637 | delete $self->{_sth}->{$$id}; | ||
| 638 | } | ||
| 639 | return $hashref; | ||
| 640 | } | ||
| 641 | } | ||
| 642 | |||
| 643 | =pod | ||
| 644 | |||
| 645 | =head2 iterator | ||
| 646 | |||
| 647 | my $iterator = $db->iterator (Table => 'passwd', | ||
| 648 | Fields => 'username,gcos,homedir', | ||
| 649 | Where => "homedir like '/home/j/%"); | ||
| 650 | while (my ($username, $gcos, $homedir) = $iterator->next ()) { | ||
| 651 | ... | ||
| 652 | } | ||
| 653 | |||
| 654 | This method returns an iterator object used to iterate over multiple rows | ||
| 655 | returned by an SQL query. See _prepare_sql for the named parameters used. | ||
| 656 | |||
| 657 | The iterator method C<next> is used to return the first or next row. If | ||
| 658 | C<next> is called in an array context, an array of column values for the | ||
| 659 | specified fields is returned. If C<next> is called in a scalar context, a | ||
| 660 | reference to a hash containing the name/values of the requested columns is | ||
| 661 | returned. | ||
| 662 | |||
| 663 | =cut | ||
| 664 | |||
| 665 | sub iterator { | ||
| 666 | my $self = shift; | ||
| 667 | my %params = @_; | ||
| 668 | |||
| 669 | my $sql = $self->_prepare_sql ('select', \%params) | ||
| 670 | || return undef; | ||
| 671 | |||
| 672 | my $sth = $self->{_dbh}->prepare ($sql); | ||
| 673 | $sth->execute | ||
| 674 | || return $self->error ("Could not execute '$sql': " | ||
| 675 | . $self->{_dbh}->errstr); | ||
| 676 | $self->{_error} = undef; | ||
| 677 | |||
| 678 | my $iterator = DBIx::Wrap::Iterator->new ($sth); | ||
| 679 | |||
| 680 | return $iterator; | ||
| 681 | } | ||
| 682 | |||
| 683 | =pod | ||
| 684 | |||
| 685 | =head2 insert | ||
| 686 | |||
| 687 | $db->insert (Table => 'passwd', | ||
| 688 | Values => {username => $username, | ||
| 689 | uid => $uid, | ||
| 690 | gcos => $gcos, | ||
| 691 | ...}); | ||
| 692 | |||
| 693 | This method inserts a new entry into a database table. See _prepare_sql | ||
| 694 | for the named parameters used. | ||
| 695 | |||
| 696 | =cut | ||
| 697 | |||
| 698 | sub insert { | ||
| 699 | my $self = shift; | ||
| 700 | my %params = @_; | ||
| 701 | |||
| 702 | my $sql = $self->_prepare_sql ('insert', \%params) | ||
| 703 | || return undef; | ||
| 704 | |||
| 705 | my $sth = $self->{_dbh}->prepare ($sql); | ||
| 706 | $sth->execute | ||
| 707 | || return $self->error ("Could not execute '$sql': " | ||
| 708 | . $self->{_dbh}->errstr); | ||
| 709 | $self->{_error} = undef; | ||
| 710 | |||
| 711 | return 1; | ||
| 712 | } | ||
| 713 | |||
| 714 | =pod | ||
| 715 | |||
| 716 | =head2 update | ||
| 717 | |||
| 718 | $db->update (Table => 'passwd', | ||
| 719 | Values => {username => $new_username, | ||
| 720 | pwd => 'x', | ||
| 721 | uid => $uid, | ||
| 722 | ...}, | ||
| 723 | Where => "username='$old_username'"); | ||
| 724 | |||
| 725 | This method updates an existing entry in a database table. See | ||
| 726 | _prepare_sql for the named parameters used. | ||
| 727 | |||
| 728 | =cut | ||
| 729 | |||
| 730 | sub update { | ||
| 731 | my $self = shift; | ||
| 732 | my %params = @_; | ||
| 733 | |||
| 734 | my $sql = $self->_prepare_sql ('update', \%params) | ||
| 735 | || return undef; | ||
| 736 | |||
| 737 | my $sth = $self->{_dbh}->prepare ($sql); | ||
| 738 | $sth->execute | ||
| 739 | || return $self->error ("Could not execute '$sql': " | ||
| 740 | . $self->{_dbh}->errstr); | ||
| 741 | $self->{_error} = undef; | ||
| 742 | |||
| 743 | return 1; | ||
| 744 | } | ||
| 745 | |||
| 746 | =pod | ||
| 747 | |||
| 748 | =head2 delete | ||
| 749 | |||
| 750 | $db->delete (Table => 'users', | ||
| 751 | Where => "username='jowaxman'"); | ||
| 752 | |||
| 753 | This method deletes an existing entry from a database table. See | ||
| 754 | _prepare_sql for the named parameters used. | ||
| 755 | |||
| 756 | =cut | ||
| 757 | |||
| 758 | sub delete { | ||
| 759 | my $self = shift; | ||
| 760 | my %params = @_; | ||
| 761 | |||
| 762 | my $sql = $self->_prepare_sql ('delete', \%params) | ||
| 763 | || return undef; | ||
| 764 | |||
| 765 | my $sth = $self->{_dbh}->prepare ($sql); | ||
| 766 | $sth->execute | ||
| 767 | || return $self->error ("Could not execute '$sql': " | ||
| 768 | . $self->{_dbh}->errstr); | ||
| 769 | $self->{_error} = undef; | ||
| 770 | |||
| 771 | return 1; | ||
| 772 | } | ||
| 773 | |||
| 774 | =pod | ||
| 775 | |||
| 776 | =head2 show_tables | ||
| 777 | |||
| 778 | my @tables = $db->show_tables (); | ||
| 779 | |||
| 780 | This method returns an array containg the table names. | ||
| 781 | |||
| 782 | =cut | ||
| 783 | |||
| 784 | sub show_tables { | ||
| 785 | my $self = shift; | ||
| 786 | |||
| 787 | my $sth = $self->{_dbh}->prepare ('show tables'); | ||
| 788 | $sth->execute | ||
| 789 | || return $self->error ("Could not execute 'SHOW TABLES': " | ||
| 790 | . $self->{_dbh}->errstr); | ||
| 791 | $self->{_error} = undef; | ||
| 792 | |||
| 793 | my @tables; | ||
| 794 | while (my @row = $sth->fetchrow_array) { | ||
| 795 | push (@tables, @row); | ||
| 796 | } | ||
| 797 | |||
| 798 | return (@tables); | ||
| 799 | } | ||
| 800 | |||
| 801 | =pod | ||
| 802 | |||
| 803 | =head2 describe | ||
| 804 | |||
| 805 | my $table_info = $db->describe (Table => 'users'); | ||
| 806 | |||
| 807 | This method returns a reference to a hash containing information about | ||
| 808 | fields. | ||
| 809 | |||
| 810 | =cut | ||
| 811 | |||
| 812 | sub describe { | ||
| 813 | my $self = shift; | ||
| 814 | my %params = @_; | ||
| 815 | |||
| 816 | my $sql = $self->_prepare_sql ('describe', \%params) | ||
| 817 | || return undef; | ||
| 818 | |||
| 819 | my $sth = $self->{_dbh}->prepare ($sql); | ||
| 820 | $sth->execute | ||
| 821 | || return $self->error ("Could not execute '$sql': " | ||
| 822 | . $self->{_dbh}->errstr); | ||
| 823 | $self->{_error} = undef; | ||
| 824 | |||
| 825 | my (%table_info, @table_info); | ||
| 826 | while (my @row = $sth->fetchrow_array) { | ||
| 827 | my %field_info = (); | ||
| 828 | my $field = $row[0]; | ||
| 829 | my $type = $row[1]; | ||
| 830 | my $key = $row[3]; | ||
| 831 | |||
| 832 | $field_info{field} = $field if wantarray; | ||
| 833 | $field_info{key} = $key; | ||
| 834 | |||
| 835 | # INT | ||
| 836 | if ($type =~ /^int(\(([^)]*)\))?( unsigned)?( zerofill)?/i) { | ||
| 837 | $field_info{type} = 'int'; | ||
| 838 | $field_info{size} = $2 if defined $2 && $2 ne ''; | ||
| 839 | $field_info{unsigned} = 1 if defined $3 && $3 ne ''; | ||
| 840 | $field_info{zerofill} = 1 if defined $4 && $4 ne ''; | ||
| 841 | |||
| 842 | # DATETIME | ||
| 843 | } elsif ($type =~ /^datetime/) { | ||
| 844 | $field_info{type} = 'datetime'; | ||
| 845 | |||
| 846 | # CHAR | ||
| 847 | } elsif ($type =~ /^(national )?char\(([^)]*)\)( binary)?/i) { | ||
| 848 | $field_info{type} = 'char'; | ||
| 849 | $field_info{national} = 1 if defined $1 && $1 ne ''; | ||
| 850 | $field_info{size} = $2; | ||
| 851 | $field_info{binary} = 1 if defined $3 && $3 ne ''; | ||
| 852 | |||
| 853 | # VARCHAR | ||
| 854 | } elsif ($type =~ /^(national )?varchar\(([^)]*)\)( binary)?/i) { | ||
| 855 | $field_info{type} = 'varchar'; | ||
| 856 | $field_info{national} = 1 if defined $1 && $1 ne ''; | ||
| 857 | $field_info{size} = $2; | ||
| 858 | $field_info{binary} = 1 if defined $3 && $3 ne ''; | ||
| 859 | |||
| 860 | # BLOB, TEXT | ||
| 861 | } elsif ($type =~ /^blob/i) { | ||
| 862 | $field_info{type} = 'blob'; | ||
| 863 | } elsif ($type =~ /^text/i) { | ||
| 864 | $field_info{type} = 'text'; | ||
| 865 | |||
| 866 | # MEDIUMBLOB, MEDIUMTEXT | ||
| 867 | } elsif ($type =~ /^mediumblob/i) { | ||
| 868 | $field_info{type} = 'mediumblob'; | ||
| 869 | } elsif ($type =~ /^mediumtext/i) { | ||
| 870 | $field_info{type} = 'mediumtext'; | ||
| 871 | |||
| 872 | # ENUM | ||
| 873 | } elsif ($type =~ /^enum\(\'([^)]*)\'\)/i) { | ||
| 874 | $field_info{type} = 'enum'; | ||
| 875 | my @values = split ("','", $1); | ||
| 876 | $field_info{values} = \@values; | ||
| 877 | } | ||
| 878 | |||
| 879 | if (wantarray) { | ||
| 880 | push (@table_info, \%field_info); | ||
| 881 | } else { | ||
| 882 | $table_info{$field} = \%field_info; | ||
| 883 | } | ||
| 884 | } | ||
| 885 | |||
| 886 | if (wantarray) { | ||
| 887 | return @table_info; | ||
| 888 | } else { | ||
| 889 | return \%table_info; | ||
| 890 | } | ||
| 891 | } | ||
| 892 | |||
| 893 | sub alter { | ||
| 894 | my $self = shift; | ||
| 895 | my %params = @_; | ||
| 896 | |||
| 897 | my $sql = $self->_prepare_sql ('alter', \%params) | ||
| 898 | || return undef; | ||
| 899 | #print "$sql\n"; | ||
| 900 | |||
| 901 | my $sth = $self->{_dbh}->prepare ($sql); | ||
| 902 | $sth->execute | ||
| 903 | || return $self->error ("Could not execute '$sql': " | ||
| 904 | . $self->{_dbh}->errstr); | ||
| 905 | $self->{_error} = undef; | ||
| 906 | |||
| 907 | return 1; | ||
| 908 | } | ||
| 909 | |||
| 910 | sub show { | ||
| 911 | my $self = shift; | ||
| 912 | my %params = @_; | ||
| 913 | |||
| 914 | my $sql = $self->_prepare_sql ('show', \%params) | ||
| 915 | || return undef; | ||
| 916 | |||
| 917 | my $sth = $self->{_dbh}->prepare ($sql); | ||
| 918 | $sth->execute | ||
| 919 | || return $self->error ("Could not execute '$sql': " | ||
| 920 | . $self->{_dbh}->errstr); | ||
| 921 | $self->{_error} = undef; | ||
| 922 | |||
| 923 | my (%table_status, @table_status); | ||
| 924 | while (my $row = $sth->fetchrow_hashref) { | ||
| 925 | if (defined $params{Format}) { | ||
| 926 | if ($params{Format} eq 'unix') { | ||
| 927 | $row->{Update_time} = $self->date2secs ($row->{Update_time}); | ||
| 928 | } | ||
| 929 | } | ||
| 930 | if (wantarray) { | ||
| 931 | push (@table_status, $row); | ||
| 932 | } else { | ||
| 933 | $table_status{$row->{Name}} = $row; | ||
| 934 | } | ||
| 935 | } | ||
| 936 | |||
| 937 | return wantarray ? @table_status : \%table_status; | ||
| 938 | } | ||
| 939 | |||
| 940 | sub date2secs { | ||
| 941 | my $self = shift; | ||
| 942 | my $date = shift; | ||
| 943 | |||
| 944 | my ($year, $mon, $mday, $hour, $min, $sec, $secs); | ||
| 945 | |||
| 946 | # Convert database date (0000-00-00 00:00). | ||
| 947 | if ($date =~ /^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$/) { | ||
| 948 | $year = $1; | ||
| 949 | $mon = $2; | ||
| 950 | $mon--; | ||
| 951 | $mday = $3; | ||
| 952 | $hour = $4; | ||
| 953 | $min = $5; | ||
| 954 | $sec = $6; | ||
| 955 | |||
| 956 | $secs = timelocal ($sec, $min, $hour, $mday, $mon, $year - 1900); | ||
| 957 | } | ||
| 958 | |||
| 959 | return $secs; | ||
| 960 | } | ||
| 961 | |||
| 962 | sub DESTROY { | ||
| 963 | my $self = shift; | ||
| 964 | |||
| 965 | # Finish any unfinished statement handles from calls to each. | ||
| 966 | foreach (keys %{$self->{_sth}}) { | ||
| 967 | $self->{_sth}->{$_}->finish; | ||
| 968 | } | ||
| 969 | |||
| 970 | # Disconnect from the database. | ||
| 971 | $self->{_dbh}->disconnect () if defined $self->{_dbh}; | ||
| 972 | } | ||
| 973 | |||
| 974 | |||
| 975 | package DBIx::Wrap::Iterator; | ||
| 976 | |||
| 977 | |||
| 978 | sub new { | ||
| 979 | # Create myself. | ||
| 980 | my $proto = shift; | ||
| 981 | |||
| 982 | my $class = ref ($proto) || $proto; | ||
| 983 | my $self = {}; | ||
| 984 | bless ($self, $class); | ||
| 985 | |||
| 986 | $self->{_sth} = shift; | ||
| 987 | |||
| 988 | return $self; | ||
| 989 | } | ||
| 990 | |||
| 991 | sub next { | ||
| 992 | my $self = shift; | ||
| 993 | |||
| 994 | if (wantarray) { | ||
| 995 | my @row = $self->{_sth}->fetchrow; | ||
| 996 | $self->{_sth}->finish if ! @row; | ||
| 997 | return @row; | ||
| 998 | } else { | ||
| 999 | my $hashref = $self->{_sth}->fetchrow_hashref; | ||
| 1000 | $self->{_sth}->finish if ! $hashref; | ||
| 1001 | return $hashref; | ||
| 1002 | } | ||
| 1003 | } | ||
| 1004 | |||
| 1005 | |||
| 1006 | 1; | ||
| 1007 | |||
| 1008 | |||
| 1009 | __END__ |