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