lib/Dancer/Plugin/Database.pm

filter: Statementstmt 72.4% 21 / 29 Branchbran 0.0% 0 / 2 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 55.5% 5 / 9 Podpod n/a totaltotal 57.7% 26 / 45 CC 3 SCAR 11.0
CC
3
Cov
62%
_load_db_settings
6.0
__ANON__
6.0
_logger
2.0
CRAP 3.0
↑ Summary
1 package Dancer::Plugin::Database;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 2 ▶use Dancer::Plugin::Database::Core;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Dancer::Plugin::Database::Core::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 2 ▶use Dancer ':syntax';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use Dancer::Plugin;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 =encoding utf8
12  
13 =head1 NAME
14  
15 Dancer::Plugin::Database - easy database connections for Dancer applications
16  
17 =cut
18  
19 2 our $VERSION = '2.13';
20  
21 2 my $settings = undef;
22  
23 0 ▶sub _load_db_settings {
Subroutine _load_db_settings: not called CC=2 SCAR=17.9
24 0 $settings = plugin_setting();
25 0 ▶ $settings->{charset} ||= setting('charset');
Condition0%0/3
$settings->{"charset"} ||= setting("charset")
l!l&&r!l&&!r
000
MC/DC0%0/2
$settings->{"charset"} ||= setting("charset")
$settings->{"charset"} setting("charset")
Truth table0%0/3
A ||= B
A= $settings->{"charset"}B= setting("charset")
ABresult
1X1
011
000
26 }
27  
28 0 ▶sub _logger { Dancer::Logger->can( $_[0] )->( $_[1] ) }
Subroutine _logger: not called CC=1 SCAR=6.9
29  
30 0 ▶sub _execute_hook { execute_hook(@_) }
Subroutine _execute_hook: not called CC=1 SCAR=6.9
31  
32 0 ▶register database => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
33 0 ▶ _load_db_settings() unless $settings;
Branch: 1 branch
BranchTrueFalseTotal
unless $settings 0 0 0
34 0 my ($dbh, $cfg) = Dancer::Plugin::Database::Core::database( arg => $_[0],
35 logger => \&_logger,
36 hook_exec => \&_execute_hook,
37 settings => $settings );
38 0 $settings = $cfg;
39 0 return $dbh;
40 2 };
41  
42 2 register_hook(qw(database_connected
43 database_connection_lost
44 database_connection_failed
45 database_error));
46  
47 2 register_plugin;
48  
49 =head1 SYNOPSIS
50  
51 use Dancer;
52 use Dancer::Plugin::Database;
53  
54 # Calling the database keyword will get you a connected database handle:
55 get '/widget/view/:id' => sub {
56 my $sth = database->prepare(
57 'select * from widgets where id = ?',
58 );
59 $sth->execute(params->{id});
60 template 'display_widget', { widget => $sth->fetchrow_hashref };
61 };
62  
63 # The handle is a Dancer::Plugin::Database::Core::Handle object, which subclasses
64 # DBI's DBI::db handle and adds a few convenience features, for example:
65 get '/insert/:name' => sub {
66 database->quick_insert('people', { name => params->{name} });
67 };
68  
69 get '/users/:id' => sub {
70 template 'display_user', {
71 person => database->quick_select('users', { id => params->{id} }),
72 };
73 };
74  
75 dance;
76  
77 Database connection details are read from your Dancer application config - see
78 below.
79  
80  
81 =head1 DESCRIPTION
82  
83 Provides an easy way to obtain a connected DBI database handle by simply calling
84 the database keyword within your L<Dancer> application
85  
86 Returns a L<Dancer::Plugin::Database::Core::Handle> object, which is a subclass of
87 L<DBI>'s C<DBI::db> connection handle object, so it does everything you'd expect
88 to do with DBI, but also adds a few convenience methods. See the documentation
89 for L<Dancer::Plugin::Database::Core::Handle> for full details of those.
90  
91 Takes care of ensuring that the database handle is still connected and valid.
92 If the handle was last asked for more than C<connection_check_threshold> seconds
93 ago, it will check that the connection is still alive, using either the
94 C<< $dbh->ping >> method if the DBD driver supports it, or performing a simple
95 no-op query against the database if not. If the connection has gone away, a new
96 connection will be obtained and returned. This avoids any problems for
97 a long-running script where the connection to the database might go away.
98  
99 Care is taken that handles are not shared across processes/threads, so this
100 should be thread-safe with no issues with transactions etc. (Thanks to Matt S
101 Trout for pointing out the previous lack of thread safety. Inspiration was
102 drawn from DBIx::Connector.)
103  
104 =head1 CONFIGURATION
105  
106 Connection details will be taken from your Dancer application config file, and
107 should be specified as, for example:
108  
109 plugins:
110 Database:
111 driver: 'mysql'
112 database: 'test'
113 host: 'localhost'
114 port: 3306
115 username: 'myusername'
116 password: 'mypassword'
117 connection_check_threshold: 10
118 dbi_params:
119 RaiseError: 1
120 AutoCommit: 1
121 on_connect_do: ["SET NAMES 'utf8'", "SET CHARACTER SET 'utf8'" ]
122 log_queries: 1
123 handle_class: 'My::Super::Sexy::Database::Handle'
124  
125 The C<connection_check_threshold> setting is optional, if not provided, it
126 will default to 30 seconds. If the database keyword was last called more than
127 this number of seconds ago, a quick check will be performed to ensure that we
128 still have a connection to the database, and will reconnect if not. This
129 handles cases where the database handle hasn't been used for a while and the
130 underlying connection has gone away.
131  
132 The C<dbi_params> setting is also optional, and if specified, should be settings
133 which can be passed to C<< DBI->connect >> as its fourth argument; see the L<DBI>
134 documentation for these.
135  
136 The optional C<on_connect_do> setting is an array of queries which should be
137 performed when a connection is established; if given, each query will be
138 performed using C<< $dbh->do >>. (If using MySQL, you might want to use this to
139 set C<SQL_MODE> to a suitable value to disable MySQL's built-in free data loss
140 'features', for example:
141  
142 on_connect_do: "SET SQL_MODE='TRADITIONAL'"
143  
144 (If you're not familiar with what I mean, I'm talking about the insane default
145 behaviour of "hmm, this bit of data won't fit the column you're trying to put it
146 in.. hmm, I know, I'll just munge it to fit, and throw a warning afterwards -
147 it's not like you're relying on me to, y'know, store what you ask me to store".
148 See L<http://effectivemysql.com/presentation/mysql-idiosyncrasies-that-bite/> for
149 just one illustration. In hindsight, I wish I'd made a sensible C<sql_mode> a
150 default setting, but I don't want to change that now.)
151  
152 The optional C<log_queries> setting enables logging of queries generated by the
153 helper functions C<quick_insert> et al in L<Dancer::Plugin::Database::Core::Handle>.
154 If you enable it, generated queries will be logged at 'debug' level. Be aware
155 that they will contain the data you're passing to/from the database, so be
156 careful not to enable this option in production, where you could inadvertently
157 log sensitive information.
158  
159 If you prefer, you can also supply a pre-crafted DSN using the C<dsn> setting;
160 in that case, it will be used as-is, and the driver/database/host settings will
161 be ignored. This may be useful if you're using some DBI driver which requires
162 a peculiar DSN.
163  
164 The optional C<handle_class> defines your own class into which database handles
165 should be blessed. This should be a subclass of
166 L<Dancer::Plugin::Database::Core::Handle> (or L<DBI::db> directly, if you just want to
167 skip the extra features).
168  
169 You will require slightly different options depending on the database engine
170 you're talking to. For instance, for SQLite, you won't need to supply
171 C<hostname>, C<port> etc, but will need to supply C<database> as the name of the
172 SQLite database file:
173  
174 plugins:
175 Database:
176 driver: SQLite
177 database: 'foo.sqlite'
178  
179 For Oracle, you may want to pass C<sid> (system ID) to identify a particular
180 database, e.g.:
181  
182 plugins:
183 Database:
184 driver: Oracle
185 host: localhost
186 sid: ABC12
187  
188 If you have any further connection parameters that need to be appended
189 to the dsn, you can put them in as a hash called dsn_extra. For
190 example, if you're running mysql on a non-standard socket, you could
191 have
192  
193 plugins:
194 Database:
195 driver: mysql
196 host: localhost
197 dsn_extra:
198 mysql_socket: /tmp/mysql_staging.sock
199  
200  
201 =head2 DEFINING MULTIPLE CONNECTIONS
202  
203 If you need to connect to multiple databases, this is easy - just list them in
204 your config under C<connections> as shown below:
205  
206 plugins:
207 Database:
208 connections:
209 foo:
210 driver: "SQLite"
211 database: "foo.sqlite"
212 bar:
213 driver: "mysql"
214 host: "localhost"
215 ....
216  
217 Then, you can call the C<database> keyword with the name of the database
218 connection you want, for example:
219  
220 my $foo_dbh = database('foo');
221 my $bar_dbh = database('bar');
222  
223  
224 =head1 RUNTIME CONFIGURATION
225  
226 You can pass a hashref to the C<database()> keyword to provide configuration
227 details to override any in the config file at runtime if desired, for instance:
228  
229 my $dbh = database({ driver => 'SQLite', database => $filename });
230  
231 (Thanks to Alan Haggai for this feature.)
232  
233 =head1 AUTOMATIC UTF-8 SUPPORT
234  
235 As of version 1.20, if your application is configured to use UTF-8 (you've
236 defined the C<charset> setting in your app config as C<UTF-8>) then support for
237 UTF-8 for the database connection will be enabled, if we know how to do so for
238 the database driver in use.
239  
240 If you do not want this behaviour, set C<auto_utf8> to a false value when
241 providing the connection details.
242  
243  
244  
245 =head1 GETTING A DATABASE HANDLE
246  
247 Calling C<database> will return a connected database handle; the first time it is
248 called, the plugin will establish a connection to the database, and return a
249 reference to the DBI object. On subsequent calls, the same DBI connection
250 object will be returned, unless it has been found to be no longer usable (the
251 connection has gone away), in which case a fresh connection will be obtained.
252  
253 If you have declared named connections as described above in 'DEFINING MULTIPLE
254 CONNECTIONS', then calling the database() keyword with the name of the
255 connection as specified in the config file will get you a database handle
256 connected with those details.
257  
258 You can also pass a hashref of settings if you wish to provide settings at
259 runtime.
260  
261  
262 =head1 CONVENIENCE FEATURES
263  
264 The handle returned by the C<database> keyword is a
265 L<Dancer::Plugin::Database::Core::Handle> object, which subclasses the C<DBI::db> DBI
266 connection handle. This means you can use it just like you'd normally use a DBI
267 handle, but extra convenience methods are provided.
268  
269 There's extensive documentation on these features in
270 L<Dancer::Plugin::Database::Core::Handle>, including using the C<order_by>, C<limit>,
271 C<columns> options to sort / limit results and include only specific columns.
272  
273 =head1 HOOKS
274  
275 This plugin uses Dancer's hooks support to allow you to register code that
276 should execute at given times - for example:
277  
278 hook 'database_connected' => sub {
279 my $dbh = shift;
280 # do something with the new DB handle here
281 };
282  
283 Currrently defined hook positions are:
284  
285 =over 4
286  
287 =item C<database_connected>
288  
289 Called when a new database connection has been established, after performing any
290 C<on_connect_do> statements, but before the handle is returned. Receives the
291 new database handle as a parameter, so that you can do what you need with it.
292  
293 =item C<database_connection_lost>
294  
295 Called when the plugin detects that the database connection has gone away.
296 Receives the no-longer usable handle as a parameter, in case you need to extract
297 some information from it (such as which server it was connected to).
298  
299 =item C<database_connection_failed>
300  
301 Called when an attempt to connect to the database fails. Receives a hashref of
302 connection settings as a parameter, containing the settings the plugin was using
303 to connect (as obtained from the config file).
304  
305 =item C<database_error>
306  
307 Called when a database error is raised by C<DBI>. Receives two parameters: the
308 error message being returned by DBI, and the database handle in question.
309  
310 =back
311  
312 If you need other hook positions which would be useful to you, please feel free
313 to suggest them!
314  
315  
316 =head1 AUTHOR
317  
318 David Precious, C<< <davidp@preshweb.co.uk> >>
319  
320  
321  
322 =head1 CONTRIBUTING
323  
324 This module is developed on Github at:
325  
326 L<http://github.com/bigpresh/Dancer-Plugin-Database>
327  
328 Feel free to fork the repo and submit pull requests! Also, it makes sense to
329 L<watch the repo|https://github.com/bigpresh/Dancer-Plugin-Database/toggle_watch>
330 on GitHub for updates.
331  
332 Feedback and bug reports are always appreciated. Even a quick mail to let me
333 know the module is useful to you would be very nice - it's nice to know if code
334 is being actively used.
335  
336 =head1 ACKNOWLEDGEMENTS
337  
338 Igor Bujna
339  
340 Franck Cuny
341  
342 Alan Haggai
343  
344 Christian Sánchez
345  
346 Michael Stiller
347  
348 Martin J Evans
349  
350 Carlos Sosa
351  
352 Matt S Trout
353  
354 Matthew Vickers
355  
356 Christian Walde
357  
358 Alberto Simões
359  
360 James Aitken (LoonyPandora)
361  
362 Mark Allen (mrallen1)
363  
364 Sergiy Borodych (bor)
365  
366 Mario Domgoergen (mdom)
367  
368 Andrey Inishev (inish777)
369  
370 Nick S. Knutov (knutov)
371  
372 Nicolas Franck (nicolasfranck)
373  
374 mscolly
375  
376 =head1 BUGS
377  
378 Please report any bugs or feature requests to C<bug-dancer-plugin-database at rt.cpan.org>, or through
379 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Dancer-Plugin-Database>. I will be notified, and then you'll
380 automatically be notified of progress on your bug as I make changes.
381  
382  
383  
384  
385 =head1 SUPPORT
386  
387 You can find documentation for this module with the perldoc command.
388  
389 perldoc Dancer::Plugin::Database
390  
391  
392 You can also look for information at:
393  
394 =over 4
395  
396 =item * RT: CPAN's request tracker
397  
398 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Dancer-Plugin-Database>
399  
400 =item * AnnoCPAN: Annotated CPAN documentation
401  
402 L<http://annocpan.org/dist/Dancer-Plugin-Database>
403  
404 =item * CPAN Ratings
405  
406 L<http://cpanratings.perl.org/d/Dancer-Plugin-Database>
407  
408 =item * Search CPAN
409  
410 L<http://search.cpan.org/dist/Dancer-Plugin-Database/>
411  
412 =back
413  
414 You can find the author on IRC in the channel C<#dancer> on <irc.perl.org>.
415  
416  
417 =head1 LICENSE AND COPYRIGHT
418  
419 Copyright 2010-2016 David Precious.
420  
421 This program is free software; you can redistribute it and/or modify it
422 under the terms of either: the GNU General Public License as published
423 by the Free Software Foundation; or the Artistic License.
424  
425 See http://dev.perl.org/licenses/ for more information.
426  
427  
428 =head1 SEE ALSO
429  
430 L<Dancer>
431  
432 L<DBI>
433  
434 L<Dancer::Plugin::SimpleCRUD>
435  
436 =cut
437  
438 2 1; # End of Dancer::Plugin::Database
↑ Summary