DBHandler.pm 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. use strict;
  2. use DBI;
  3. use Carp;
  4. package DBHandler;
  5. #our $dbh = undef;
  6. use vars qw ($DB_CONNECTION);
  7. sub getConnection {
  8. my ($dsn, $user, $pass) = @_;
  9. #return $DB_CONNECTION if ($DB_CONNECTION);
  10. $DB_CONNECTION = DBI->connect($dsn, $user, $pass);
  11. $DB_CONNECTION->{AutoCommit} = 1;
  12. $DB_CONNECTION->{RaiseError} = 1;
  13. return $DB_CONNECTION;
  14. }
  15. # #############
  16. # Simple statement
  17. package Statement;
  18. sub new {
  19. my ( $this, $dbh, $sql, $is_trans ) = @_;
  20. # @@@ sql should be tested OK, so here just die
  21. my $sth = $dbh->prepare($sql) || Carp::croak( $dbh->errstr );
  22. my %fields = (
  23. dbh => $dbh,
  24. sql => $sql,
  25. sth => $sth,
  26. is_trans => $is_trans,
  27. );
  28. return bless \%fields, $this;
  29. }
  30. sub exec {
  31. my ( $this, @param ) = @_;
  32. my $dbh = $this->{dbh};
  33. my $sth = $this->{sth};
  34. my $sql = $this->{sql};
  35. if ( !$sth->execute(@param) ) {
  36. if ( $this->{is_trans} ) {
  37. $dbh->rollback();
  38. }
  39. Carp::croak( $dbh->errstr );
  40. }
  41. my @ret = ();
  42. if ( $sql =~ /^select/i ) {
  43. # @@@ get result object
  44. while ( my $res = $sth->fetchrow_hashref() ) {
  45. push @ret, $res;
  46. }
  47. }
  48. # @@@ $sth->finish();
  49. return \@ret;
  50. }
  51. sub last_id {
  52. my $this = shift;
  53. my $dbh = $this->{dbh};
  54. return $dbh->last_insert_id(undef, undef, undef, undef);
  55. }
  56. sub DESTROY {
  57. my $this = shift;
  58. my $sth = $this->{sth};
  59. $sth->finish();
  60. }
  61. # #############
  62. # Transaction
  63. package Transaction;
  64. my $IS_TRANS = 1;
  65. sub new {
  66. my ( $this, $dbh ) = @_;
  67. # @@@ fatal error, just die
  68. $dbh->begin_work() || Carp::croak( $dbh->errstr );
  69. my %fields = (
  70. dbh => $dbh,
  71. Active => 1,
  72. );
  73. return bless \%fields, $this;
  74. }
  75. sub createStatement {
  76. my ( $this, $sql) = @_;
  77. # @@@ fatal error, just die
  78. Carp::croak("transaction not begin") if ( !$this->{Active} );
  79. my $dbh = $this->{dbh};
  80. return new Statement($dbh, $sql, $IS_TRANS);
  81. }
  82. sub commit {
  83. my $this = shift;
  84. my $dbh = $this->{dbh};
  85. if ( $this->{Active} && !$dbh->{AutoCommit} ) {
  86. $dbh->commit || Carp::croak( $dbh->errstr );
  87. }
  88. $this->{Active} = 0;
  89. }
  90. sub rollback {
  91. my $this = shift;
  92. my $dbh = $this->{dbh};
  93. if ( $this->{Active} && !$dbh->{AutoCommit} ) {
  94. $dbh->rollback || Carp::croak( $dbh->errstr );
  95. }
  96. $this->{Active} = 0;
  97. }
  98. sub DESTROY {
  99. my $this = shift;
  100. $this->rollback;
  101. }
  102. 1;