Admin: Teile von admin.pl in neuen Controller Admin verschoben; Mandanten anzeigen
[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 (($type eq 'KIVITENDO_AUTH') && $::auth && $::auth->{DB_config} && $::auth->session_tables_present) {
53     %connect_settings = ( driver          => 'Pg',
54                           database        => $::auth->{DB_config}->{db},
55                           host            => $::auth->{DB_config}->{host} || 'localhost',
56                           port            => $::auth->{DB_config}->{port} || 5432,
57                           username        => $::auth->{DB_config}->{user},
58                           password        => $::auth->{DB_config}->{password},
59                           connect_options => { pg_enable_utf8 => $::locale && $::locale->is_utf8,
60                                              });
61   }
62
63   if (!%connect_settings && %::myconfig) {
64     my $european_dates = 0;
65     if ($::myconfig{dateformat}) {
66       $european_dates = 1 if $_dateformats{ $::myconfig{dateformat} }
67                           && $_dateformats{ $::myconfig{dateformat} } =~ m/european/i;
68     }
69
70     %connect_settings = ( driver          => $::myconfig{dbdriver} || 'Pg',
71                           database        => $::myconfig{dbname},
72                           host            => $::myconfig{dbhost} || 'localhost',
73                           port            => $::myconfig{dbport} || 5432,
74                           username        => $::myconfig{dbuser},
75                           password        => $::myconfig{dbpasswd},
76                           connect_options => { pg_enable_utf8 => $::locale && $::locale->is_utf8,
77                                              },
78                           european_dates  => $european_dates);
79   }
80
81   if (!%connect_settings) {
82     $type = 'KIVITENDO_EMPTY';
83     %connect_settings = ( driver => 'Pg' );
84   }
85
86   my %flattened_settings = _flatten_settings(%connect_settings);
87
88   $domain = 'KIVITENDO' if $type =~ m/^KIVITENDO/;
89   $type  .= join($SUBSCRIPT_SEPARATOR, map { ($_, $flattened_settings{$_} || '') } sort grep { $_ ne 'dbpasswd' } keys %flattened_settings);
90   my $idx = "${domain}::${type}";
91
92   if (!$_db_registered{$idx}) {
93     $_db_registered{$idx} = 1;
94
95     __PACKAGE__->register_db(domain => $domain,
96                              type   => $type,
97                              %connect_settings,
98                             );
99   }
100
101   return ($domain, $type);
102 }
103
104 sub _execute_initial_sql {
105   my ($db) = @_;
106
107   return if $_initial_sql_executed{$db} || !%::myconfig || !$::myconfig{dateformat};
108
109   $_initial_sql_executed{$db} = 1;
110
111   # Don't rely on dboptions being set properly. Chose them from
112   # dateformat instead.
113   my $pg_dateformat = $_dateformats{ $::myconfig{dateformat} };
114   $db->dbh->do("set DateStyle to '${pg_dateformat}'") if $pg_dateformat;
115 }
116
117 sub _flatten_settings {
118   my %settings  = @_;
119   my %flattened = ();
120
121   while (my ($key, $value) = each %settings) {
122     if ('HASH' eq ref $value) {
123       %flattened = ( %flattened, _flatten_settings(%{ $value }) );
124     } else {
125       $flattened{$key} = $value;
126     }
127   }
128
129   return %flattened;
130 }
131
132 sub with_transaction {
133   my ($self, $code, @args) = @_;
134
135   return $code->(@args) if $self->in_transaction;
136   if (wantarray) {
137     my @result;
138     return $self->do_transaction(sub { @result = $code->(@args) }) ? @result : ();
139
140   } else {
141     my $result;
142     return $self->do_transaction(sub { $result = $code->(@args) }) ? $result : undef;
143   }
144 }
145
146 1;
147 __END__
148
149 =pod
150
151 =encoding utf8
152
153 =head1 NAME
154
155 SL::DB - Database access class for all RDB objects
156
157 =head1 FUNCTIONS
158
159 =over 4
160
161 =item C<create $domain, $type>
162
163 Registers the database information with Rose, creates a cached
164 connection and executes initial SQL statements. Those can include
165 setting the time & date format to the user's preferences.
166
167 =item C<dbi_connect $dsn, $login, $password, $options>
168
169 Forwards the call to L<SL::DBConnect/connect> which connects to the
170 database. This indirection allows L<SL::DBConnect/connect> to route
171 the calls through L<DBIx::Log4Perl> if this is enabled in the
172 configuration.
173
174 =item C<with_transaction $code_ref, @args>
175
176 Executes C<$code_ref> with parameters C<@args> within a transaction,
177 starting one if none is currently active. Example:
178
179   return $self->db->with_transaction(sub {
180     # do stuff with $self
181   });
182
183 One big difference to L<Rose::DB/do_transaction> is the return code
184 handling. If a transaction is already active then C<with_transcation>
185 simply returns the result of calling C<$code_ref> as-is.
186
187 Otherwise the return value depends on the result of the underlying
188 transaction. If the transaction fails then C<undef> is returned in
189 scalar context and an empty list in list context. If the transaction
190 succeeds then the return value of C<$code_ref> is returned preserving
191 context.
192
193 So if you want to differentiate between "transaction failed" and
194 "succeeded" then your C<$code_ref> should never return C<undef>
195 itself.
196
197 =back
198
199 =head1 BUGS
200
201 Nothing here yet.
202
203 =head1 AUTHOR
204
205 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
206
207 =cut