Vorkommen von "LxOffice" (und andere Schreibweisen) durch "kivitendo" ersetzen
[kivitendo-erp.git] / SL / DB.pm
1 package SL::DB;
2
3 use strict;
4
5 use Carp;
6 use Data::Dumper;
7 use SL::DBConnect;
8 use English qw(-no_match_vars);
9 use Rose::DB;
10 use Rose::DBx::Cache::Anywhere;
11
12 use base qw(Rose::DB);
13
14 __PACKAGE__->db_cache_class('Rose::DBx::Cache::Anywhere');
15 __PACKAGE__->use_private_registry;
16
17 my (%_db_registered, %_initial_sql_executed);
18
19 sub dbi_connect {
20   shift;
21
22   return SL::DBConnect->connect(@_);
23 }
24
25 sub create {
26   my $domain = shift || SL::DB->default_domain;
27   my $type   = shift || SL::DB->default_type;
28
29   ($domain, $type) = _register_db($domain, $type);
30
31   my $db = __PACKAGE__->new_or_cached(domain => $domain, type => $type);
32
33   _execute_initial_sql($db);
34
35   return $db;
36 }
37
38 my %_dateformats = ( 'yy-mm-dd'   => 'ISO',
39                      'yyyy-mm-dd' => 'ISO',
40                      'mm/dd/yy'   => 'SQL, US',
41                      'dd/mm/yy'   => 'SQL, EUROPEAN',
42                      'dd.mm.yy'   => 'GERMAN'
43                    );
44
45 sub _register_db {
46   my $domain = shift;
47   my $type   = shift;
48
49   my %connect_settings;
50   my $initial_sql;
51
52   if (!%::myconfig) {
53     $type = 'KIVITENDO_EMPTY';
54     %connect_settings = ( driver => 'Pg' );
55
56   } elsif ($type eq 'KIVITENDO_AUTH') {
57     %connect_settings = ( driver          => $::myconfig{dbdriver} || 'Pg',
58                           database        => $::auth->{DB_config}->{db},
59                           host            => $::auth->{DB_config}->{host} || 'localhost',
60                           port            => $::auth->{DB_config}->{port} || 5432,
61                           username        => $::auth->{DB_config}->{user},
62                           password        => $::auth->{DB_config}->{password},
63                           connect_options => { pg_enable_utf8 => $::locale && $::locale->is_utf8,
64                                              });
65   } else {
66     my $european_dates = 0;
67     if ($::myconfig{dateformat}) {
68       $european_dates = 1 if $_dateformats{ $::myconfig{dateformat} }
69                           && $_dateformats{ $::myconfig{dateformat} } =~ m/european/i;
70     }
71
72     %connect_settings = ( driver          => $::myconfig{dbdriver} || 'Pg',
73                           database        => $::myconfig{dbname},
74                           host            => $::myconfig{dbhost} || 'localhost',
75                           port            => $::myconfig{dbport} || 5432,
76                           username        => $::myconfig{dbuser},
77                           password        => $::myconfig{dbpasswd},
78                           connect_options => { pg_enable_utf8 => $::locale && $::locale->is_utf8,
79                                              },
80                           european_dates  => $european_dates);
81   }
82
83   my %flattened_settings = _flatten_settings(%connect_settings);
84
85   $domain = 'KIVITENDO' if $type =~ m/^KIVITENDO/;
86   $type  .= join($SUBSCRIPT_SEPARATOR, map { ($_, $flattened_settings{$_} || '') } sort grep { $_ ne 'dbpasswd' } keys %flattened_settings);
87   my $idx = "${domain}::${type}";
88
89   if (!$_db_registered{$idx}) {
90     $_db_registered{$idx} = 1;
91
92     __PACKAGE__->register_db(domain => $domain,
93                              type   => $type,
94                              %connect_settings,
95                             );
96   }
97
98   return ($domain, $type);
99 }
100
101 sub _execute_initial_sql {
102   my ($db) = @_;
103
104   return if $_initial_sql_executed{$db} || !%::myconfig || !$::myconfig{dateformat};
105
106   $_initial_sql_executed{$db} = 1;
107
108   # Don't rely on dboptions being set properly. Chose them from
109   # dateformat instead.
110   my $pg_dateformat = $_dateformats{ $::myconfig{dateformat} };
111   $db->dbh->do("set DateStyle to '${pg_dateformat}'") if $pg_dateformat;
112 }
113
114 sub _flatten_settings {
115   my %settings  = @_;
116   my %flattened = ();
117
118   while (my ($key, $value) = each %settings) {
119     if ('HASH' eq ref $value) {
120       %flattened = ( %flattened, _flatten_settings(%{ $value }) );
121     } else {
122       $flattened{$key} = $value;
123     }
124   }
125
126   return %flattened;
127 }
128
129 sub with_transaction {
130   my ($self, $code, @args) = @_;
131
132   return $code->(@args) if $self->in_transaction;
133   if (wantarray) {
134     my @result;
135     return $self->do_transaction(sub { @result = $code->(@args) }) ? @result : ();
136
137   } else {
138     my $result;
139     return $self->do_transaction(sub { $result = $code->(@args) }) ? $result : undef;
140   }
141 }
142
143 1;
144 __END__
145
146 =pod
147
148 =encoding utf8
149
150 =head1 NAME
151
152 SL::DB - Database access class for all RDB objects
153
154 =head1 FUNCTIONS
155
156 =over 4
157
158 =item C<create $domain, $type>
159
160 Registers the database information with Rose, creates a cached
161 connection and executes initial SQL statements. Those can include
162 setting the time & date format to the user's preferences.
163
164 =item C<dbi_connect $dsn, $login, $password, $options>
165
166 Forwards the call to L<SL::DBConnect/connect> which connects to the
167 database. This indirection allows L<SL::DBConnect/connect> to route
168 the calls through L<DBIx::Log4Perl> if this is enabled in the
169 configuration.
170
171 =item C<with_transaction $code_ref, @args>
172
173 Executes C<$code_ref> with parameters C<@args> within a transaction,
174 starting one if none is currently active. Example:
175
176   return $self->db->with_transaction(sub {
177     # do stuff with $self
178   });
179
180 One big difference to L<Rose::DB/do_transaction> is the return code
181 handling. If a transaction is already active then C<with_transcation>
182 simply returns the result of calling C<$code_ref> as-is.
183
184 Otherwise the return value depends on the result of the underlying
185 transaction. If the transaction fails then C<undef> is returned in
186 scalar context and an empty list in list context. If the transaction
187 succeeds then the return value of C<$code_ref> is returned preserving
188 context.
189
190 So if you want to differentiate between "transaction failed" and
191 "succeeded" then your C<$code_ref> should never return C<undef>
192 itself.
193
194 =back
195
196 =head1 BUGS
197
198 Nothing here yet.
199
200 =head1 AUTHOR
201
202 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
203
204 =cut