File Coverage

lib/Dancer/Plugin/Database.pm
Criterion Covered Total %
statement 15 23 65.2
branch 0 2 0.0
condition 0 3 0.0
subroutine 5 9 55.5
pod n/a
total 20 37 54.0


line stmt bran cond sub pod time code
1             package Dancer::Plugin::Database;
2              
3 2     2   426497 use strict;
  2         4  
  2         46  
4              
5 2     2   914 use Dancer::Plugin::Database::Core;
  2         2265  
  2         49  
6 2     2   968 use Dancer::Plugin::Database::Core::Handle;
  2         29822  
  2         54  
7              
8 2     2   18 use Dancer ':syntax';
  2         2  
  2         15  
9 2     2   1594 use Dancer::Plugin;
  2         1910  
  2         487  
10              
11             =encoding utf8
12              
13             =head1 NAME
14              
15             Dancer::Plugin::Database - easy database connections for Dancer applications
16              
17             =cut
18              
19             our $VERSION = '2.13';
20              
21             my $settings = undef;
22              
23             sub _load_db_settings {
24 0     0     $settings = plugin_setting();
25 0   0       $settings->{charset} ||= setting('charset');
26             }
27              
28 0     0     sub _logger { Dancer::Logger->can( $_[0] )->( $_[1] ) }
29              
30 0     0     sub _execute_hook { execute_hook(@_) }
31              
32             register database => sub {
33 0 0   0     _load_db_settings() unless $settings;
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             };
41              
42             register_hook(qw(database_connected
43             database_connection_lost
44             database_connection_failed
45             database_error));
46              
47             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 application
85              
86             Returns a L object, which is a subclass of
87             L's C 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 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 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 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 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
134             documentation for these.
135              
136             The optional C 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 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 for
149             just one illustration. In hindsight, I wish I'd made a sensible C a
150             default setting, but I don't want to change that now.)
151              
152             The optional C setting enables logging of queries generated by the
153             helper functions C et al in L.
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 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 defines your own class into which database handles
165             should be blessed. This should be a subclass of
166             L (or L 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, C etc, but will need to supply C 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 (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 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 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 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 setting in your app config as C) 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 to a false value when
241             providing the connection details.
242              
243              
244              
245             =head1 GETTING A DATABASE HANDLE
246              
247             Calling C 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 keyword is a
265             L object, which subclasses the C 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, including using the C, C,
271             C 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
288              
289             Called when a new database connection has been established, after performing any
290             C 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
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
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
306              
307             Called when a database error is raised by C. 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<< >>
319              
320              
321              
322             =head1 CONTRIBUTING
323              
324             This module is developed on Github at:
325              
326             L
327              
328             Feel free to fork the repo and submit pull requests! Also, it makes sense to
329             L
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, or through
379             the web interface at L. 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
399              
400             =item * AnnoCPAN: Annotated CPAN documentation
401              
402             L
403              
404             =item * CPAN Ratings
405              
406             L
407              
408             =item * Search CPAN
409              
410             L
411              
412             =back
413              
414             You can find the author on IRC in the channel C<#dancer> on .
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
431              
432             L
433              
434             L
435              
436             =cut
437              
438             1; # End of Dancer::Plugin::Database