blib/lib/DBIx/Class/Schema/Config.pm

filter: Statementstmt 100% 54 / 54 Branchbran 100% 22 / 22 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 13 / 13 Podpod 60.0% 3 / 5 totaltotal 97.8% 92 / 94 CC 15 SCAR 11.7
CC
15
Cov
100%
_make_connect_attrs
6.0
_find_credentials
5.0
connection
2.0
CRAP 3.2
↑ Summary
1 package DBIx::Class::Schema::Config;
2 9 ▶use 5.005;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 9 ▶use base 'DBIx::Class::Schema';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 ▶use File::HomeDir;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 9 our $VERSION = '0.001010'; # 0.1.10
9 9 $VERSION = eval $VERSION;
10  
11 sub connection {
12 13 ▶ my ( $class, @info ) = @_;
Subroutine connection: called CC=2 SCAR=6.9
Pod documented
13  
14 13 my $attrs = $class->_make_connect_attrs(@info);
15  
16 # Take responsibility for passing through normal-looking
17 # credentials.
18 $attrs = $class->load_credentials($attrs)
19 13 ▶ unless $attrs->{dsn} =~ /dbi:/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $attrs->{"dsn"} =~ /dbi:/i 5 8 13
20  
21 13 return $class->next::method( $attrs );
22 }
23  
24 # Normalize arguments into a single hash. If we get a single hashref,
25 # return it.
26 # Check if $user and $pass are hashes to support things like
27 # ->connect( 'CONFIG_FILE', { hostname => 'db.foo.com' } );
28  
29 sub _make_connect_attrs {
30 26 ▶ my ( $class, $dsn, $user, $pass, $dbi_attr, $extra_attr ) = @_;
Subroutine _make_connect_attrs: called CC=6 SCAR=17.9
31 26 ▶ return $dsn if ref $dsn eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $dsn eq "HASH" 8 18 26
32  
33 return {
34 dsn => $dsn,
35 18 ▶ %{ref $user eq 'HASH' ? $user : { user => $user }},
Branch: 1 branch
BranchTrueFalseTotal
ref $user eq 'HASH' ? : 1 17 18
36 18 ▶ %{ref $pass eq 'HASH' ? $pass : { password => $pass }},
Branch: 1 branch
BranchTrueFalseTotal
ref $pass eq 'HASH' ? : 1 17 18
37 18 ▶ %{$dbi_attr || {} },
Branch: 1 branch
BranchTrueFalseTotal
$dbi_attr or {} 15 3 18
38 18 ▶ %{ $extra_attr || {} }
Branch: 1 branch
BranchTrueFalseTotal
$extra_attr or {} 17 1 18
39 };
40 }
41  
42 # simple wrapped getter for lazyload
43 sub config {
44 10 ▶ my ( $class ) = @_;
Subroutine config: called CC=2 SCAR=6.9
Pod undocumented
45  
46 10 ▶ $class->_config || $class->_load_config;
Branch: 1 branch
BranchTrueFalseTotal
$class->_config or $class->_load_config 6 4 10
47 }
48  
49  
50 sub _load_config {
51 6 ▶ my ( $class ) = @_;
Subroutine _load_config: called CC=2 SCAR=6.9
52 6 require Config::Any; # Only loaded if we need to load credentials.
53  
54 # If we have ->config_files, we'll use those and load_files
55 # instead of the default load_stems.
56 6 my %cf_opts = ( use_ext => 1 );
57 6 ▶ my $ConfigAny = @{$class->config_files}
Branch: 1 branch
BranchTrueFalseTotal
@{$class->config_files;} ? : 1 5 6
58 ? Config::Any->load_files({ files => $class->config_files, %cf_opts })
59 : Config::Any->load_stems({ stems => $class->config_paths, %cf_opts });
60  
61 # stuff the schema config for leveraging elsewhere in userland
62 6 $class->_config($ConfigAny);
63 }
64  
65  
66 sub load_credentials {
67 11 ▶ my ( $class, $connect_args ) = @_;
Subroutine load_credentials: called CC=2 SCAR=6.9
Pod documented
68 # While ->connect is responsible for returning normal-looking
69 # credential information, we do it here as well so that it can be
70 # independently unit tested.
71 11 ▶ return $connect_args if $connect_args->{dsn} =~ /^dbi:/i;
Branch: 1 branch
BranchTrueFalseTotal
if $connect_args->{"dsn"} =~ /^dbi:/i 2 9 11
72  
73 9 return $class->filter_loaded_credentials(
74 $class->_find_credentials( $connect_args, $class->config ),
75 $connect_args
76 );
77  
78 }
79  
80 # This will look through the data structure returned by Config::Any
81 # and return the first instance of the database credentials it can
82 # find.
83 sub _find_credentials {
84 9 ▶ my ( $class, $connect_args, $ConfigAny ) = @_;
Subroutine _find_credentials: called CC=5 SCAR=16.1
85  
86 9 for my $cfile ( @$ConfigAny ) {
87 9 for my $filename ( keys %$cfile ) {
88 9 for my $database ( keys %{$cfile->{$filename}} ) {
89 15 ▶ if ( $database eq $connect_args->{dsn} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($database eq $connect_args->{"dsn"}) 9 6 15
90 9 return $cfile->{$filename}->{$database};
91 }
92 }
93 }
94 }
95 }
96  
97 sub get_env_vars {
98 9 ▶ return $ENV{DBIX_CONFIG_DIR} . "/dbic" if exists $ENV{DBIX_CONFIG_DIR};
Subroutine get_env_vars: called CC=2 SCAR=6.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
if exists $ENV{"DBIX_CONFIG_DIR"} 1 8 9
99 8 return ();
100 }
101  
102 # Intended to be sub-classed, we'll just return the
103 # credentials we used in the first place.
104 7 ▶sub filter_loaded_credentials { $_[1] };
Subroutine filter_loaded_credentials: called CC=1 SCAR=0.0
Pod documented
105  
106 9 __PACKAGE__->mk_classaccessor('config_paths');
107 9 __PACKAGE__->mk_classaccessor('config_files');
108 9 __PACKAGE__->mk_classaccessor('_config');
109 9 __PACKAGE__->config_paths([( get_env_vars(), './dbic', File::HomeDir->my_home . '/.dbic', '/etc/dbic')]);
110 9 __PACKAGE__->config_files([ ] );
111  
112 9 1;
113  
114 =encoding UTF-8
115  
116 =head1 NAME
117  
118 DBIx::Class::Schema::Config - Credential Management for DBIx::Class
119  
120 =head1 DESCRIPTION
121  
122 DBIx::Class::Schema::Config is a subclass of DBIx::Class::Schema that allows
123 the loading of credentials & configuration from a file. The actual code itself
124 would only need to know about the name used in the configuration file. This
125 aims to make it simpler for operations teams to manage database credentials.
126  
127 A simple tutorial that compliments this documentation and explains converting
128 an existing DBIx::Class Schema to use this software to manage credentials can
129 be found at L<http://www.symkat.com/credential-management-in-dbix-class>
130  
131 =head1 SYNOPSIS
132  
133 /etc/dbic.yaml
134 MY_DATABASE:
135 dsn: "dbi:Pg:host=localhost;database=blog"
136 user: "TheDoctor"
137 password: "dnoPydoleM"
138 TraceLevel: 1
139  
140 package My::Schema
141 use warnings;
142 use strict;
143  
144 use base 'DBIx::Class::Schema::Config';
145 __PACKAGE__->load_namespaces;
146  
147 package My::Code;
148 use warnings;
149 use strict;
150 use My::Schema;
151  
152 my $schema = My::Schema->connect('MY_DATABASE');
153  
154 # arbitrary config access from anywhere in your $app
155 my $level = My::Schema->config->{TraceLevel};
156  
157 =head1 CONFIG FILES
158  
159 This module will load the files in the following order if they exist:
160  
161 =over 4
162  
163 =item * C<$ENV{DBIX_CONFIG_DIR}> . '/dbic',
164  
165 C<$ENV{DBIX_CONFIG_DIR}> can be configured at run-time, for instance:
166  
167 DBIX_CONFIG_DIR="/var/local/" ./my_program.pl
168  
169 =item * ./dbic.*
170  
171 =item * ~/.dbic.*
172  
173 =item * /etc/dbic.*
174  
175 =back
176  
177 The files should have an extension that L<Config::Any> recognizes,
178 for example /etc/dbic.B<yaml>.
179  
180 NOTE: The first available credential will be used. Therefore I<DATABASE>
181 in ~/.dbic.yaml will only be looked at if it was not found in ./dbic.yaml.
182 If there are duplicates in one file (such that DATABASE is listed twice in
183 ~/.dbic.yaml,) the first configuration will be used.
184  
185 =head1 CHANGE CONFIG PATH
186  
187 Use C<__PACKAGE__-E<gt>config_paths([( '/file/stub', '/var/www/etc/dbic')]);>
188 to change the paths that are searched. For example:
189  
190 package My::Schema
191 use warnings;
192 use strict;
193  
194 use base 'DBIx::Class::Schema::Config';
195 __PACKAGE__->config_paths([( '/var/www/secret/dbic', '/opt/database' )]);
196  
197 The above code would have I</var/www/secret/dbic.*> and I</opt/database.*>
198 searched, in that order. As above, the first credentials found would be used.
199 This will replace the files originally searched for, not add to them.
200  
201 =head1 USE SPECIFIC CONFIG FILES
202  
203 If you would rather explicitly state the configuration files you
204 want loaded, you can use the class accessor C<config_files>
205 instead.
206  
207 package My::Schema
208 use warnings;
209 use strict;
210  
211 use base 'DBIx::Class::Schema::Config';
212 __PACKAGE__->config_files([( '/var/www/secret/dbic.yaml', '/opt/database.yaml' )]);
213  
214 This will check the files, C</var/www/secret/dbic.yaml>,
215 and C</opt/database.yaml> in the same way as C<config_paths>,
216 however it will only check the specific files, instead of checking
217 for each extension that L<Config::Any> supports. You MUST use the
218 extension that corresponds to the file type you are loading.
219 See L<Config::Any> for information on supported file types and
220 extension mapping.
221  
222 =head1 ACCESSING THE CONFIG FILE
223  
224 The config file is stored via the C<__PACKAGE__-E<gt>config> accessor, which can be
225 called as both a class and instance method:
226  
227 package My::Schema
228 use warnings;
229 use strict;
230  
231 use base 'DBIx::Class::Schema::Config';
232 __PACKAGE__->config_paths([( '/var/www/secret/dbic', '/opt/database' )]);
233  
234 The above code would have I</var/www/secret/dbic.*> and I</opt/database.*>
235 searched, in that order. As above, the first credentials found would be used.
236 This will replace the files origionally searched for, not add to them.
237  
238  
239 =head1 OVERRIDING
240  
241 The API has been designed to be simple to override if you have additional
242 needs in loading DBIC configurations.
243  
244 =head2 filter_loaded_credentials
245  
246 Override this function if you want to change the loaded credentials before
247 they are passed to DBIC. This is useful for use-cases that include decrypting
248 encrypted passwords or making programmatic changes to the configuration before
249 using it.
250  
251 sub filter_loaded_credentials {
252 my ( $class, $loaded_credentials, $connect_args ) = @_;
253 ...
254 return $loaded_credentials;
255 }
256  
257 C<$loaded_credentials> is the structure after it has been loaded from the
258 configuration file. In this case, C<$loaded_credentials-E<gt>{user}> eq
259 B<WalterWhite> and C<$loaded_credentials-E<gt>{dsn}> eq
260 B<DBI:mysql:database=students;host=%s;port=3306>.
261  
262 C<$connect_args> is the structure originally passed on C<-E<gt>connect()>
263 after it has been turned into a hash. For instance,
264 C<-E<gt>connect('DATABASE', 'USERNAME')> will result in
265 C<$connect_args-E<gt>{dsn}> eq B<DATABASE> and C<$connect_args-E<gt>{user}>
266 eq B<USERNAME>.
267  
268 Additional parameters can be added by appending a hashref,
269 to the connection call, as an example, C<-E<gt>connect( 'CONFIG',
270 { hostname =E<gt> "db.foo.com" } );> will give C<$connect_args> a
271 structure like C<{ dsn =E<gt> 'CONFIG', hostname =E<gt> "db.foo.com" }>.
272  
273 For instance, if you want to use hostnames when you make the
274 initial connection to DBIC and are using the configuration primarily
275 for usernames, passwords and other configuration data, you can create
276 a config like the following:
277  
278 DATABASE:
279 dsn: "DBI:mysql:database=students;host=%s;port=3306"
280 user: "WalterWhite"
281 password: "relykS"
282  
283 In your Schema class, you could include the following:
284  
285 package My::Schema
286 use warnings;
287 use strict;
288 use base 'DBIx::Class::Schema::Config';
289  
290 sub filter_loaded_credentials {
291 my ( $class, $loaded_credentials, $connect_args ) = @_;
292 if ( $loaded_credentials->{dsn} =~ /\%s/ ) {
293 $loaded_credentials->{dsn} = sprintf( $loaded_credentials->{dsn},
294 $connect_args->{hostname});
295 }
296 }
297  
298 __PACKAGE__->load_classes;
299 1;
300  
301 Then the connection could be done with
302 C<$Schema-E<gt>connect('DATABASE', { hostname => 'my.hostname.com' });>
303  
304 See L</load_credentials> for more complex changes that require changing
305 how the configuration itself is loaded.
306  
307 =head2 load_credentials
308  
309 Override this function to change the way that L<DBIx::Class::Schema::Config>
310 loads credentials. The function takes the class name, as well as a hashref.
311  
312 If you take the route of having C<-E<gt>connect('DATABASE')> used as a key for
313 whatever configuration you are loading, I<DATABASE> would be
314 C<$config-E<gt>{dsn}>
315  
316 Some::Schema->connect(
317 "SomeTarget",
318 "Yuri",
319 "Yawny",
320 {
321 TraceLevel => 1
322 }
323 );
324  
325 Would result in the following data structure as $config in
326 C<load_credentials($class, $config)>:
327  
328 {
329 dsn => "SomeTarget",
330 user => "Yuri",
331 password => "Yawny",
332 TraceLevel => 1,
333 }
334  
335 Currently, load_credentials will NOT be called if the first argument to
336 C<-E<gt>connect()> looks like a valid DSN. This is determined by match
337 the DSN with C</^dbi:/i>.
338  
339 The function should return the same structure. For instance:
340  
341 package My::Schema
342 use warnings;
343 use strict;
344 use base 'DBIx::Class::Schema::Config';
345 use LWP::Simple;
346 use JSON
347  
348 # Load credentials from internal web server.
349 sub load_credentials {
350 my ( $class, $config ) = @_;
351  
352 return decode_json(
353 get( "http://someserver.com/v1.0/database?key=somesecret&db=" .
354 $config->{dsn} ));
355 }
356  
357 __PACKAGE__->load_classes;
358  
359 =head1 AUTHOR
360  
361 Kaitlyn Parkhurst (SymKat) I<E<lt>symkat@symkat.comE<gt>> ( Blog: L<http://symkat.com/> )
362  
363 =head1 CONTRIBUTORS
364  
365 =over 4
366  
367 =item * Matt S. Trout (mst) I<E<lt>mst@shadowcat.co.ukE<gt>>
368  
369 =item * Peter Rabbitson (ribasushi) I<E<lt>ribasushi@cpan.orgE<gt>>
370  
371 =item * Christian Walde (Mihtaldu) I<E<lt>walde.christian@googlemail.comE<gt>>
372  
373 =item * Dagfinn Ilmari Mannsåker (ilmari) I<E<lt>ilmari@ilmari.orgE<gt>>
374  
375 =item * Matthew Phillips (mattp) I<E<lt>mattp@cpan.orgE<gt>>
376  
377 =back
378  
379 =head1 COPYRIGHT AND LICENSE
380  
381 This library is free software and may be distributed under the same terms
382 as perl itself.
383  
384 =head1 AVAILABILITY
385  
386 The latest version of this software is available at
387 L<https://github.com/symkat/DBIx-Class-Schema-Config>
388  
389 =cut
↑ Summary