Dancer2-Plugin-Database-2.15/000755 000765 000024 00000000000 12651227765 015757 5ustar00ambsstaff000000 000000 Dancer2-Plugin-Database-2.15/Changes000644 000765 000024 00000003200 12651227427 017240 0ustar00ambsstaff000000 000000 Revision history for Dancer2-Plugin-Database 2.15 2016-01-24 [ ENHANCEMENTS ] - Bump required Dancer2 version to 0.166001 given some bug regressions. - skip author tests (thanks to Stefan Hornburg) 2.14 2016-01-20 [ ENHANCEMENTS ] - Add support for new Dancer2 plugin system. (Thanks to Peter Mottram) 2.13 2015-10-02 [ BUG FIXES ] - Require Dancer::Plugin::Database::Core v0.12, that fixes logging problems 2.12 2014-10-13 [ BUG FIXES ] - Fixed dependency for Plack::Test. 2.11 2014-10-13 [ BUG FIXES ] - Changed test process to Plack::Test. [ ENHANCEMENTS ] - Support dsn_extra option (Thanks to Michael J South) 2.10 Wed Sep 4 16:13:14 WEST 2013 [ BUG FIXES ] - Dancer2 v0.9 no longer includes 'lib' by default; 2.09 Sun Sep 1 13:56:18 WEST 2013 [ BUG FIXES ] - Remove ':syntax' on test case (Dancer2 0.08) [ ENHANCEMENTS ] - Add quick_count method (Thanks to Colin Ewen) 2.08 Tue Jul 30 18:59:30 WEST 2013 - Fix test with wrong base class (part 2) 2.07 Tue Jul 30 18:49:37 WEST 2013 - Fix test with wrong base class. 2.06 Tue Jul 30 16:14:28 WEST 2013 - Require recent Dancer2 0.06 as 0.05 was broken. 2.05 Mon Jul 29 12:08:21 WEST 2013 - Fix dependency with Dancer 2. 2.04 Sat Jul 27 18:21:48 WEST 2013 - First version, released together with Dancer::Plugin::Database::Core version 0.01 with same features as Dancer::Plugin::Database 2.04. Dancer2-Plugin-Database-2.15/lib/000755 000765 000024 00000000000 12651227763 016523 5ustar00ambsstaff000000 000000 Dancer2-Plugin-Database-2.15/Makefile.PL000644 000765 000024 00000002223 12651225323 017714 0ustar00ambsstaff000000 000000 use strict; use warnings; use ExtUtils::MakeMaker; WriteMakefile( NAME => 'Dancer2::Plugin::Database', AUTHOR => q{David Precious }, VERSION_FROM => 'lib/Dancer2/Plugin/Database.pm', ABSTRACT_FROM => 'lib/Dancer2/Plugin/Database.pm', ($ExtUtils::MakeMaker::VERSION >= 6.3002 ? ('LICENSE'=> 'perl') : ()), PL_FILES => {}, PREREQ_PM => { 'Dancer2' => '0.166001', 'Dancer::Plugin::Database::Core' => '0.12', }, TEST_REQUIRES => { 'Test::More' => 0, 'HTTP::Request::Common' => 0, 'Plack' => '1.0032', }, dist => { COMPRESS => 'gzip -9f', SUFFIX => 'gz', }, clean => { FILES => 'Dancer2-Plugin-Database-*' }, META_MERGE => { resources => { repository => 'https://github.com/bigpresh/Dancer-Plugin-Database', bugtracker => 'https://github.com/bigpresh/Dancer-Plugin-Database/issues', homepage => 'https://github.com/bigpresh/Dancer-Plugin-Database/', }, }, ); Dancer2-Plugin-Database-2.15/MANIFEST000644 000765 000024 00000000626 12651227765 017114 0ustar00ambsstaff000000 000000 Changes MANIFEST MANIFEST.SKIP Makefile.PL README lib/Dancer2/Plugin/Database.pm t/00-load.t t/01-basic.t t/manifest.t t/pod-coverage.t t/pod.t t/lib/TestApp.pm t/lib/TestHandleClass.pm t/lib/public/.placeholder t/lib/views/.placeholder META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) Dancer2-Plugin-Database-2.15/MANIFEST.SKIP000644 000765 000024 00000000266 12651227525 017653 0ustar00ambsstaff000000 000000 ^\.git\/ maint ^tags$ .last_cover_stats Makefile$ ^blib ^pm_to_blib ^.*.bak ^.*.old ^t.*sessions ^cover_db ^.*\.log ^run_perltidy.sh$ ^.*\.swp$ ^ignore.txt ^.gitignore ~$ \.tar\.gz$ Dancer2-Plugin-Database-2.15/META.json000644 000765 000024 00000002650 12651227765 017403 0ustar00ambsstaff000000 000000 { "abstract" : "easy database connections for Dancer2 applications", "author" : [ "David Precious " ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 7.1, CPAN::Meta::Converter version 2.150005", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Dancer2-Plugin-Database", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0", "HTTP::Request::Common" : "0", "Plack" : "1.0032", "Test::More" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Dancer2" : "0.166001", "Dancer::Plugin::Database::Core" : "0.12" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/bigpresh/Dancer-Plugin-Database/issues" }, "homepage" : "https://github.com/bigpresh/Dancer-Plugin-Database/", "repository" : { "url" : "https://github.com/bigpresh/Dancer-Plugin-Database" } }, "version" : "2.15", "x_serialization_backend" : "JSON::PP version 2.27300" } Dancer2-Plugin-Database-2.15/META.yml000644 000765 000024 00000001624 12651227763 017231 0ustar00ambsstaff000000 000000 --- abstract: 'easy database connections for Dancer2 applications' author: - 'David Precious ' build_requires: ExtUtils::MakeMaker: '0' HTTP::Request::Common: '0' Plack: '1.0032' Test::More: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 7.1, CPAN::Meta::Converter version 2.150005' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Dancer2-Plugin-Database no_index: directory: - t - inc requires: Dancer2: '0.166001' Dancer::Plugin::Database::Core: '0.12' resources: bugtracker: https://github.com/bigpresh/Dancer-Plugin-Database/issues homepage: https://github.com/bigpresh/Dancer-Plugin-Database/ repository: https://github.com/bigpresh/Dancer-Plugin-Database version: '2.15' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Dancer2-Plugin-Database-2.15/README000644 000765 000024 00000032632 12175515777 016651 0ustar00ambsstaff000000 000000 NAME Dancer2::Plugin::Database - easy database connections for Dancer applications SYNOPSIS use Dancer2; use Dancer2::Plugin::Database; # Calling the database keyword will get you a connected database handle: get '/widget/view/:id' => sub { my $sth = database->prepare( 'select * from widgets where id = ?', ); $sth->execute(params->{id}); template 'display_widget', { widget => $sth->fetchrow_hashref }; }; # The handle is a Dancer::Plugin::Database::Core::Handle object, which subclasses # DBI's DBI::db handle and adds a few convenience features, for example: get '/insert/:name' => sub { database->quick_insert('people', { name => params->{name} }); }; get '/users/:id' => sub { template 'display_user', { person => database->quick_select('users', { id => params->{id} }), }; }; dance; Database connection details are read from your Dancer2 application config - see below. DESCRIPTION Provides an easy way to obtain a connected DBI database handle by simply calling the database keyword within your Dancer2 application Returns a Dancer::Plugin::Database::Core::Handle object, which is a subclass of DBI's `DBI::db' connection handle object, so it does everything you'd expect to do with DBI, but also adds a few convenience methods. See the documentation for Dancer::Plugin::Database::Core::Handle for full details of those. Takes care of ensuring that the database handle is still connected and valid. If the handle was last asked for more than `connection_check_threshold' seconds ago, it will check that the connection is still alive, using either the `$dbh->ping' method if the DBD driver supports it, or performing a simple no-op query against the database if not. If the connection has gone away, a new connection will be obtained and returned. This avoids any problems for a long-running script where the connection to the database might go away. Care is taken that handles are not shared across processes/threads, so this should be thread-safe with no issues with transactions etc. (Thanks to Matt S Trout for pointing out the previous lack of thread safety. Inspiration was drawn from DBIx::Connector.) CONFIGURATION Connection details will be taken from your Dancer2 application config file, and should be specified as, for example: plugins: Database: driver: 'mysql' database: 'test' host: 'localhost' port: 3306 username: 'myusername' password: 'mypassword' connection_check_threshold: 10 dbi_params: RaiseError: 1 AutoCommit: 1 on_connect_do: ["SET NAMES 'utf8'", "SET CHARACTER SET 'utf8'" ] log_queries: 1 handle_class: 'My::Super::Sexy::Database::Handle' The `connection_check_threshold' setting is optional, if not provided, it will default to 30 seconds. If the database keyword was last called more than this number of seconds ago, a quick check will be performed to ensure that we still have a connection to the database, and will reconnect if not. This handles cases where the database handle hasn't been used for a while and the underlying connection has gone away. The `dbi_params' setting is also optional, and if specified, should be settings which can be passed to `DBI->connect' as its fourth argument; see the DBI documentation for these. The optional `on_connect_do' setting is an array of queries which should be performed when a connection is established; if given, each query will be performed using `$dbh->do'. (If using MySQL, you might want to use this to set `SQL_MODE' to a suitable value to disable MySQL's built-in free data loss 'features', for example: on_connect_do: "SET SQL_MODE='TRADITIONAL'" (If you're not familiar with what I mean, I'm talking about the insane default behaviour of "hmm, this bit of data won't fit the column you're trying to put it in.. hmm, I know, I'll just munge it to fit, and throw a warning afterwards - it's not like you're relying on me to, y'know, store what you ask me to store". See http://effectivemysql.com/presentation/mysql-idiosyncrasies-that-bite/ for just one illustration. In hindsight, I wish I'd made a sensible `sql_mode' a default setting, but I don't want to change that now.) The optional `log_queries' setting enables logging of queries generated by the helper functions `quick_insert' et al in Dancer::Plugin::Database::Core::Handle. If you enable it, generated queries will be logged at 'debug' level. Be aware that they will contain the data you're passing to/from the database, so be careful not to enable this option in production, where you could inadvertently log sensitive information. If you prefer, you can also supply a pre-crafted DSN using the `dsn' setting; in that case, it will be used as-is, and the driver/database/host settings will be ignored. This may be useful if you're using some DBI driver which requires a peculiar DSN. The optional `handle_class' defines your own class into which database handles should be blessed. This should be a subclass of Dancer::Plugin::Database::Core::Handle (or DBI::db directly, if you just want to skip the extra features). You will require slightly different options depending on the database engine you're talking to. For instance, for SQLite, you won't need to supply `hostname', `port' etc, but will need to supply `database' as the name of the SQLite database file: plugins: Database: driver: SQLite database: 'foo.sqlite' For Oracle, you may want to pass `sid' (system ID) to identify a particular database, e.g.: plugins: Database: driver: Oracle host: localhost sid: ABC12 DEFINING MULTIPLE CONNECTIONS If you need to connect to multiple databases, this is easy - just list them in your config under `connections' as shown below: plugins: Database: connections: foo: driver: "SQLite" database: "foo.sqlite" bar: driver: "mysql" host: "localhost" .... Then, you can call the `database' keyword with the name of the database connection you want, for example: my $foo_dbh = database('foo'); my $bar_dbh = database('bar'); RUNTIME CONFIGURATION You can pass a hashref to the `database()' keyword to provide configuration details to override any in the config file at runtime if desired, for instance: my $dbh = database({ driver => 'SQLite', database => $filename }); (Thanks to Alan Haggai for this feature.) AUTOMATIC UTF-8 SUPPORT As of version 1.20, if your application is configured to use UTF-8 (you've defined the `charset' setting in your app config as `UTF-8') then support for UTF-8 for the database connection will be enabled, if we know how to do so for the database driver in use. If you do not want this behaviour, set `auto_utf8' to a false value when providing the connection details. GETTING A DATABASE HANDLE Calling `database' will return a connected database handle; the first time it is called, the plugin will establish a connection to the database, and return a reference to the DBI object. On subsequent calls, the same DBI connection object will be returned, unless it has been found to be no longer usable (the connection has gone away), in which case a fresh connection will be obtained. If you have declared named connections as described above in 'DEFINING MULTIPLE CONNECTIONS', then calling the database() keyword with the name of the connection as specified in the config file will get you a database handle connected with those details. You can also pass a hashref of settings if you wish to provide settings at runtime. CONVENIENCE FEATURES (quick_select, quick_update, quick_insert, quick_delete) The handle returned by the `database' keyword is a Dancer::Plugin::Database::Core::Handle object, which subclasses the `DBI::db' DBI connection handle. This means you can use it just like you'd normally use a DBI handle, but extra convenience methods are provided, as documented in the POD for Dancer::Plugin::Database::Core::Handle. Examples: # Quickly fetch the (first) row whose ID is 42 as a hashref: my $row = database->quick_select($table_name, { id => 42 }); # Fetch all badgers as an array of hashrefs: my @badgers = database->quick_select('animals', { genus => 'Mellivora' }); # Update the row where the 'id' column is '42', setting the 'foo' column to # 'Bar': database->quick_update($table_name, { id => 42 }, { foo => 'Bar' }); # Insert a new row, using a named connection (see above) database('connectionname')->quick_insert($table_name, { foo => 'Bar' }); # Delete the row with id 42: database->quick_delete($table_name, { id => 42 }); # Fetch all rows from a table (since version 1.30): database->quick_select($table_name, {}); There's more extensive documentation on these features in Dancer::Plugin::Database::Core::Handle, including using the `order_by', `limit', `columns' options to sort / limit results and include only specific columns. HOOKS This plugin uses Dancer2's hooks support to allow you to register code that should execute at given times - for example: hook 'database_connected' => sub { my $dbh = shift; # do something with the new DB handle here }; Currrently defined hook positions are: `database_connected' Called when a new database connection has been established, after performing any `on_connect_do' statements, but before the handle is returned. Receives the new database handle as a parameter, so that you can do what you need with it. `database_connection_lost' Called when the plugin detects that the database connection has gone away. Receives the no-longer usable handle as a parameter, in case you need to extract some information from it (such as which server it was connected to). `database_connection_failed' Called when an attempt to connect to the database fails. Receives a hashref of connection settings as a parameter, containing the settings the plugin was using to connect (as obtained from the config file). `database_error' Called when a database error is raised by `DBI'. Receives two parameters: the error message being returned by DBI, and the database handle in question. If you need other hook positions which would be useful to you, please feel free to suggest them! AUTHOR David Precious, `' CONTRIBUTING This module is developed on Github at: http://github.com/bigpresh/Dancer-Plugin-Database Feel free to fork the repo and submit pull requests! Also, it makes sense to watch the repo on GitHub for updates. Feedback and bug reports are always appreciated. Even a quick mail to let me know the module is useful to you would be very nice - it's nice to know if code is being actively used. ACKNOWLEDGEMENTS Igor Bujna Franck Cuny Alan Haggai Christian Sánchez Michael Stiller Martin J Evans Carlos Sosa Matt S Trout Matthew Vickers Christian Walde Alberto Simões James Aitken (LoonyPandora) Mark Allen (mrallen1) Sergiy Borodych (bor) Mario Domgoergen (mdom) Andrey Inishev (inish777) Nick S. Knutov (knutov) Nicolas Franck (nicolasfranck) mscolly BUGS Please report any bugs or feature requests to `bug-dancer-plugin-database at rt.cpan.org', or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Dancer2-Plugin-Database. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. SUPPORT You can find documentation for this module with the perldoc command. perldoc Dancer2::Plugin::Database You can also look for information at: * RT: CPAN's request tracker http://rt.cpan.org/NoAuth/Bugs.html?Dist=Dancer2-Plugin-Database * AnnoCPAN: Annotated CPAN documentation http://annocpan.org/dist/Dancer2-Plugin-Database * CPAN Ratings http://cpanratings.perl.org/d/Dancer2-Plugin-Database * Search CPAN http://search.cpan.org/dist/Dancer2-Plugin-Database/ You can find the author on IRC in the channel `#dancer' on . LICENSE AND COPYRIGHT Copyright 2010-12 David Precious. This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License. See http://dev.perl.org/licenses/ for more information. SEE ALSO Dancer2 DBI Dancer2-Plugin-Database-2.15/t/000755 000765 000024 00000000000 12651227763 016220 5ustar00ambsstaff000000 000000 Dancer2-Plugin-Database-2.15/t/00-load.t000644 000765 000024 00000000434 12175515777 017550 0ustar00ambsstaff000000 000000 #!perl # had -T use Test::More import => ['!pass'], tests => 1; use Dancer2; BEGIN { use_ok( 'Dancer2::Plugin::Database' ) || print "Bail out! "; } diag( "Testing Dancer2::Plugin::Database $Dancer2::Plugin::Database::VERSION, with Dancer2 $Dancer2::VERSION in Perl $], $^X" ); Dancer2-Plugin-Database-2.15/t/01-basic.t000644 000765 000024 00000017216 12571601716 017706 0ustar00ambsstaff000000 000000 use strict; use warnings; use Test::More import => ['!pass']; use HTTP::Request::Common qw(GET HEAD PUT POST DELETE); use Plack::Test; eval { require DBD::SQLite }; if ($@) { plan skip_all => 'DBD::SQLite required to run these tests'; } my $dsn = "dbi:SQLite:dbname=:memory:"; my $conf = { Database => { dsn => $dsn, connection_check_threshold => 0.1, dbi_params => { RaiseError => 0, PrintError => 0, PrintWarn => 0, }, handle_class => 't::lib::TestHandleClass', } }; use t::lib::TestApp; { package t::lib::TestApp; set plugins => $conf; set logger => 'capture'; set log => 'debug'; } my $app = t::lib::TestApp->to_app; is(ref $app, "CODE", "Got a code ref"); test_psgi $app, sub { my $cb = shift; { my $res = $cb->(GET '/connecthookfired'); is $res->content, 1, 'database_connected hook fires'; } { my $res = $cb->(GET '/errorhookfired'); is $res->content, 1, 'database_error hook fires'; } { my $res = $cb->( GET '/isa/DBI::db'); is $res->content, 1, "handle isa('DBI::db')"; } { my $res = $cb->( GET '/isa/Dancer::Plugin::Database::Core::Handle'); is $res->content, 1, "handle isa('Dancer::Plugin::Database::Core::Handle')"; } { my $res = $cb->( GET '/isa/t::lib::TestHandleClass'); is $res->content, 1, "handle isa('t::lib::TestHandleClass')"; } { my $res = $cb->( GET '/isa/duck' ); is $res->content, 0, "handle is not a duck"; # reverse duck-typing ;) } { my $res = $cb->( GET '/prepare_db' ); is $res->code, 200, 'db is created'; } { my $res = $cb->( GET '/' ); is $res->code, 200, "GET / is found"; } { my $res = $cb->( GET '/' ); like $res->content, qr/7/, "content looks good for / (7 users afiter DB initialisation)"; } { my $res = $cb->(GET '/user/1'); is $res->code, 200,'GET /user/1 is found'; } { my $res = $cb->( GET '/user/1' ); like $res->content, qr/sukria/, 'content looks good for /user/1'; } { my $res = $cb->(GET '/user/2' ); like $res->content, qr/bigpresh/, "content looks good for /user/2"; } { my $res = $cb->( DELETE '/user/3' ); is $res->code, 200, 'DELETE /user/3 is ok'; } { my $res = $cb->( GET '/' ); like $res->content, qr/6/, 'content looks good for / (6 users after deleting one)'; } # Exercise the extended features (quick_update et al) { my $res = $cb->( GET '/quick_insert/42/Bob' ); is $res->code, 200, "quick_insert returned OK status"; } { my $res = $cb->( GET '/user/42' ); like $res->content, qr/Bob/, "quick_insert created a record successfully"; } { my $res = $cb->( GET '/quick_select/42' ); like $res->content, qr/Bob/, "quick_select returned the record created by quick_insert"; } { my $res = $cb->(GET '/quick_select/69' ); unlike $res->content, qr/Bob/, "quick_select doesn't return non-matching record"; } { my $res = $cb->(GET '/quick_select/1/category' ); like $res->content, qr/admin/, 'content looks good for /quick_select/1/category'; } { my $res = $cb->( GET '/quick_select/2/name' ); like $res->content, qr/bigpresh/, 'content looks good for /quick_select/2/name'; } { my $res = $cb->(GET '/quick_lookup/bigpresh' ); like $res->content, qr/2/, 'content looks good for /quick_lookup/bigpresh'; } # Test quick_count functions { my $res = $cb->( GET '/quick_count/admin'); is $res->content, 2, 'quick_count shows 2 admins'; } { my $res = $cb->( GET '/complex_where/4' ); like $res->content, qr/mousey/, "Complex where clause succeeded"; } { my $res = $cb->( GET '/complex_not/42' ); like $res->content, qr/sukria/, "Complex not where clause succeeded"; } { my $res = $cb->( GET '/set_op/2' ); like $res->content, qr/bigpresh/, "set operation where clause succeeded"; } { my $res = $cb->( GET '/quick_select_many' ); like $res->content, qr/\b bigpresh,sukria \b/x, "quick_select returns multiple records in list context"; } { my $res = $cb->( GET '/quick_update/42/Billy' ); is $res->code, 200, "quick_update returned OK status"; } { my $res = $cb->( GET '/user/42' ); like $res->content, qr/Billy/, "quick_update updated a record successfully"; } { my $res = $cb->( GET '/quick_delete/42' ); is $res->code, 200, "quick_delete returned OK status"; } { my $res = $cb->( GET '/user/42' ); like $res->content, qr/No such user/, "quick_delete deleted a record successfully"; } # Test that we can fetch only the columns we want { my $res = $cb->(GET '/quick_select_specific_cols/name'); like $res->content, qr/^bigpresh$/m, 'Fetched a single specified column OK'; } { my $res = $cb->( GET '/quick_select_specific_cols/name/category' ); like $res->content, qr/^bigpresh:admin$/m, 'Fetched multiple specified columns OK'; } # Test that we can limit the number of rows we get back: { my $res = $cb->( GET '/quick_select_with_limit/1' ); is $res->content, "1", "User-specified LIMIT works (1 row)"; } { my $res = $cb->( GET '/quick_select_with_limit/2'); is $res->content, "2", "User-specified LIMIT works (2 row)"; } # Test that order_by gives us rows in desired order { my $res = $cb->(GET '/quick_select_sorted' ); is $res->content, "bigpresh:bodger:mousey:mystery1:mystery2:sukria", "Records sorted properly"; } { my $res = $cb->(GET '/quick_select_sorted_rev' ); is $res->content, "sukria:mystery2:mystery1:mousey:bodger:bigpresh", "Records sorted properly in descending order"; } # Use where and order_by together # This didn't work as the WHERE and ORDER BY clauses were concatenated without # a space, as per https://github.com/bigpresh/Dancer-Plugin-Database/pull/27 { my $res = $cb->( GET '/quick_select_sorted_where' ); is $res->content, "mystery1:mystery2"; } # Test that runtime configuration gives us a handle, too: { my $res = $cb->( GET '/runtime_config' ); is $res->code, 200, "runtime_config returned OK status"; } { my $res = $cb->( GET '/runtime_config' ); like $res->content, qr/ok/, "runtime_config got a usable database handle"; } # Test that we get the same handle each time we call the database() keyword # (i.e., that handles are cached appropriately) { my $res = $cb->( GET '/handles_cached' ); like $res->content, qr/Same handle returned/; } # Test that the database_connection_lost hook fires when the connection goes # away { my $res = $cb->(GET '/database_connection_lost_fires' ); is $res->content, 1, 'database_connection_lost hook fires'; } # Test that the database_connection_failed hook fires when we can't connect { my $res = $cb->( GET '/database_connection_failed_fires' ); is $res->content, 1, 'database_connection_failed hook fires'; } }; done_testing(); __END__ Dancer2-Plugin-Database-2.15/t/lib/000755 000765 000024 00000000000 12651227763 016766 5ustar00ambsstaff000000 000000 Dancer2-Plugin-Database-2.15/t/manifest.t000644 000765 000024 00000000420 12175515777 020215 0ustar00ambsstaff000000 000000 #!perl -T use strict; use warnings; use Test::More; unless ( $ENV{RELEASE_TESTING} ) { plan( skip_all => "Author tests not required for installation" ); } eval "use Test::CheckManifest 0.9"; plan skip_all => "Test::CheckManifest 0.9 required" if $@; ok_manifest(); Dancer2-Plugin-Database-2.15/t/pod-coverage.t000644 000765 000024 00000001521 12647720576 020764 0ustar00ambsstaff000000 000000 use strict; use warnings; use Test::More; unless ( $ENV{RELEASE_TESTING} ) { plan( skip_all => "Author tests not required for installation" ); } # Ensure a recent version of Test::Pod::Coverage my $min_tpc = 1.08; eval "use Test::Pod::Coverage $min_tpc"; plan skip_all => "Test::Pod::Coverage $min_tpc required for testing POD coverage" if $@; # Test::Pod::Coverage doesn't require a minimum Pod::Coverage version, # but older versions don't recognize some common documentation styles my $min_pc = 0.18; eval "use Pod::Coverage $min_pc"; plan skip_all => "Pod::Coverage $min_pc required for testing POD coverage" if $@; all_pod_coverage_ok({ also_private => [qw/ClassHooks PluginKeyword dancer_app database execute_plugin_hook hook keywords on_plugin_import plugin_args plugin_setting register register_hook register_plugin var/]}); Dancer2-Plugin-Database-2.15/t/pod.t000644 000765 000024 00000000350 12175515777 017173 0ustar00ambsstaff000000 000000 #!perl -T use strict; use warnings; use Test::More; # Ensure a recent version of Test::Pod my $min_tp = 1.22; eval "use Test::Pod $min_tp"; plan skip_all => "Test::Pod $min_tp required for testing POD" if $@; all_pod_files_ok(); Dancer2-Plugin-Database-2.15/t/lib/public/000755 000765 000024 00000000000 12651227763 020244 5ustar00ambsstaff000000 000000 Dancer2-Plugin-Database-2.15/t/lib/TestApp.pm000644 000765 000024 00000014671 12637516121 020706 0ustar00ambsstaff000000 000000 package t::lib::TestApp; use Dancer2; use Dancer2::Plugin::Database; no warnings 'uninitialized'; hook database_connected => sub { my $dbh = shift; var(connecthookfired => $dbh); }; get '/connecthookfired' => sub { my $database = database(); # If the hook fired, it'll have squirreled away a reference to the DB handle # for us to look for. my $h = var('connecthookfired'); if (ref $h && $h->isa('DBI::db')) { return 1; } else { return 0; } }; my $last_db_error; hook 'database_error' => sub { $last_db_error = $_[0]; }; get '/errorhookfired' => sub { database->do('something silly'); return $last_db_error ? 1 : 0; }; get '/prepare_db' => sub { my @sql = ( q/create table users (id INTEGER, name VARCHAR, category VARCHAR)/, q/insert into users values (1, 'sukria', 'admin')/, q/insert into users values (2, 'bigpresh', 'admin')/, q/insert into users values (3, 'badger', 'animal')/, q/insert into users values (4, 'bodger', 'man')/, q/insert into users values (5, 'mousey', 'animal')/, q/insert into users values (6, 'mystery2', null)/, q/insert into users values (7, 'mystery1', null)/, ); database->do($_) for @sql; 'ok'; }; get '/' => sub { my $sth = database->prepare('select count(*) from users'); $sth->execute; my $total_users = $sth->fetch(); $total_users->[0]; }; get '/user/:id' => sub { my $sth = database->prepare('select * from users where id = ?'); $sth->execute( params->{id} ); my $user = $sth->fetch(); $user->[1] || "No such user"; }; del '/user/:id' => sub { my $sth = database->prepare('delete from users where id = ?'); $sth->execute( params->{id} ); 'ok'; }; # Routes to exercise some of the extended features: get '/quick_insert/:id/:name' => sub { database->quick_insert('users', { id => params->{id}, name => params->{name}, category => 'user' }, ); 'ok'; }; get '/quick_update/:id/:name' => sub { database->quick_update('users', { id => params->{id} }, { name => params->{name} }, ); 'ok'; }; get '/quick_delete/:id' => sub { database->quick_delete('users', { id => params->{id} }); 'ok'; }; get '/quick_select/:id' => sub { my $row = database->quick_select('users', { id => params->{id} }); return $row ? join(',', values %$row) : "No matching user"; }; get '/quick_select/:id/:parm' => sub { my $row = database->quick_select('users', { id => params->{id} }, [ 'id', params->{parm} ]); return $row ? join(',', values %$row) : "No matching user"; }; get '/quick_lookup/:name' => sub { my $id = database->quick_lookup('users', { name => params->{name} }, 'id'); return $id; }; get '/quick_count/:category' => sub { my $row = database->quick_count('users', { category => params->{category} }); return $row; }; get '/complex_where/:id' => sub { my $row = database->quick_select( 'users', { id => { 'gt' => params->{id} } } ); return $row ? join(',', values %$row) : "No matching user"; }; get '/complex_not/:id' => sub { my $row = database->quick_select('users', { category => { 'is' => undef, 'not' => 1 } }); return $row ? join(',', values %$row) : "No matching user"; }; get '/set_op/:id' => sub { my $row = database->quick_select('users', { id => [ params->{id} ] }); return $row ? join(',', values %$row) : "No matching user"; }; get '/quick_select_many' => sub { my @users = database->quick_select('users', { category => 'admin' }); return join ',', sort map { $_->{name} } @users; }; # e.g. /quick_select_specific_cols/foo should return col 'foo' # or /quick_select_specific_cols/foo/bar returns foo:bar get '/quick_select_specific_cols/**' => sub { my $out; my $cols = (splat)[0]; my @users = database->quick_select('users', {}, { columns => $cols }); for my $user (@users) { $out .= join(':', @$user{@$cols}) . "\n"; } return $out; }; get '/quick_select_with_limit/:limit' => sub { my $limit = params->{limit}; my @users = database->quick_select('users', {}, { limit => $limit }); return scalar @users; }; get '/quick_select_sorted' => sub { my @users = database->quick_select('users', {}, { order_by => 'name' }); return join ':', map { $_->{name} } @users; }; get '/quick_select_sorted_rev' => sub { my @users = database->quick_select( 'users', {}, { order_by => { desc => 'name' } } ); return join ':', map { $_->{name} } @users; }; get '/quick_select_sorted_where' => sub { my @users = database->quick_select( 'users', { category => undef }, { order_by => 'name' } ); return join ':', map { $_->{name} } @users; }; # Check we can get a handle by passing a hashref of settings, too: get '/runtime_config' => sub { my $dbh = database({ driver => 'SQLite', database => ':memory:'}); $dbh ? 'ok' : ''; }; # Check we get the same handle each time we call database() get '/handles_cached' => sub { database() eq database() and return "Same handle returned"; }; # Check that the database_connection_lost hook fires when we force a db handle # to go away: hook database_connection_lost => sub { var(lost_connection => 1); }; get '/database_connection_lost_fires' => sub { var(lost_connection => 0); database()->disconnect; # We set connection_check_threshold to 0.1 at the start, so wait a second # then check that the code detects the handle is no longer connected and # triggers the hook sleep 1; my $handle = database(); return var('lost_connection'); }; # Check that database_connection_failed hook fires if we can't connect - pass # bogus connection details to make that happen hook database_connection_failed => sub { var connection_failed => 1; }; get '/database_connection_failed_fires' => sub { # Give a ridiculous database filename which should never exist in order to # force a connection failure my $handle = database({ dsn => "dbi:SQLite:/Please/Tell/Me/This/File/Does/Not/Exist!", dbi_params => { HandleError => sub { return 0 }, # gobble connect failed message RaiseError => 0, PrintError => 0, }, }); return var 'connection_failed'; }; # Check that the handle isa() subclass of the named class get '/isa/:class' => sub { return database->isa(params->{class}) ? 1 : 0; }; 1; Dancer2-Plugin-Database-2.15/t/lib/TestHandleClass.pm000644 000765 000024 00000000127 12211645627 022340 0ustar00ambsstaff000000 000000 package t::lib::TestHandleClass; use base 'Dancer::Plugin::Database::Core::Handle'; 1; Dancer2-Plugin-Database-2.15/t/lib/views/000755 000765 000024 00000000000 12651227763 020123 5ustar00ambsstaff000000 000000 Dancer2-Plugin-Database-2.15/t/lib/views/.placeholder000644 000765 000024 00000000000 12175515777 022402 0ustar00ambsstaff000000 000000 Dancer2-Plugin-Database-2.15/t/lib/public/.placeholder000644 000765 000024 00000000000 12175515777 022523 0ustar00ambsstaff000000 000000 Dancer2-Plugin-Database-2.15/lib/Dancer2/000755 000765 000024 00000000000 12651227763 020001 5ustar00ambsstaff000000 000000 Dancer2-Plugin-Database-2.15/lib/Dancer2/Plugin/000755 000765 000024 00000000000 12651227763 021237 5ustar00ambsstaff000000 000000 Dancer2-Plugin-Database-2.15/lib/Dancer2/Plugin/Database.pm000644 000765 000024 00000035602 12651227304 023276 0ustar00ambsstaff000000 000000 package Dancer2::Plugin::Database; use strict; use Dancer::Plugin::Database::Core; use Dancer::Plugin::Database::Core::Handle; use Dancer2::Plugin; =encoding utf8 =head1 NAME Dancer2::Plugin::Database - easy database connections for Dancer2 applications =cut our $VERSION = '2.15'; register_hook qw(database_connected database_connection_lost database_connection_failed database_error); my $settings = {}; sub _load_settings { my $dsl = shift; $settings = plugin_setting(); $settings->{charset} ||= $dsl->setting('charset') || 'utf-8'; } register database => sub { my $dsl = shift; my $logger = sub { $dsl->log(@_); }; # wasn't working properly calling the Dancer2::Plugin execute_hook # directly my $hook_exec = sub { if ( $dsl->can('execute_plugin_hook') ) { # Plugin2 $dsl->execute_plugin_hook(@_); } else { # old behaviour $dsl->execute_hook(@_); } }; ## This is mostly for the case the user uses 'set plugins' and ## changes configuration during runtime. For example in our test suite. _load_settings($dsl); my ($dbh, $cfg) = Dancer::Plugin::Database::Core::database( arg => $_[0], logger => $logger, hook_exec => $hook_exec, settings => $settings ); $settings = $cfg; return $dbh; }; register_plugin; =head1 SYNOPSIS use Dancer2; use Dancer2::Plugin::Database; # Calling the database keyword will get you a connected database handle: get '/widget/view/:id' => sub { my $sth = database->prepare( 'select * from widgets where id = ?', ); $sth->execute(params->{id}); template 'display_widget', { widget => $sth->fetchrow_hashref }; }; # The handle is a Dancer::Plugin::Database::Core::Handle object, which subclasses # DBI's DBI::db handle and adds a few convenience features, for example: get '/insert/:name' => sub { database->quick_insert('people', { name => params->{name} }); }; get '/users/:id' => sub { template 'display_user', { person => database->quick_select('users', { id => params->{id} }), }; }; dance; Database connection details are read from your Dancer2 application config - see below. =head1 DESCRIPTION Provides an easy way to obtain a connected DBI database handle by simply calling the database keyword within your L application Returns a L object, which is a subclass of L's C connection handle object, so it does everything you'd expect to do with DBI, but also adds a few convenience methods. See the documentation for L for full details of those. Takes care of ensuring that the database handle is still connected and valid. If the handle was last asked for more than C seconds ago, it will check that the connection is still alive, using either the C<< $dbh->ping >> method if the DBD driver supports it, or performing a simple no-op query against the database if not. If the connection has gone away, a new connection will be obtained and returned. This avoids any problems for a long-running script where the connection to the database might go away. Care is taken that handles are not shared across processes/threads, so this should be thread-safe with no issues with transactions etc. (Thanks to Matt S Trout for pointing out the previous lack of thread safety. Inspiration was drawn from DBIx::Connector.) =head1 CONFIGURATION Connection details will be taken from your Dancer2 application config file, and should be specified as, for example: plugins: Database: driver: 'mysql' database: 'test' host: 'localhost' port: 3306 username: 'myusername' password: 'mypassword' connection_check_threshold: 10 dbi_params: RaiseError: 1 AutoCommit: 1 on_connect_do: ["SET NAMES 'utf8'", "SET CHARACTER SET 'utf8'" ] log_queries: 1 handle_class: 'My::Super::Sexy::Database::Handle' The C setting is optional, if not provided, it will default to 30 seconds. If the database keyword was last called more than this number of seconds ago, a quick check will be performed to ensure that we still have a connection to the database, and will reconnect if not. This handles cases where the database handle hasn't been used for a while and the underlying connection has gone away. The C setting is also optional, and if specified, should be settings which can be passed to C<< DBI->connect >> as its fourth argument; see the L documentation for these. The optional C setting is an array of queries which should be performed when a connection is established; if given, each query will be performed using C<< $dbh->do >>. (If using MySQL, you might want to use this to set C to a suitable value to disable MySQL's built-in free data loss 'features', for example: on_connect_do: "SET SQL_MODE='TRADITIONAL'" (If you're not familiar with what I mean, I'm talking about the insane default behaviour of "hmm, this bit of data won't fit the column you're trying to put it in.. hmm, I know, I'll just munge it to fit, and throw a warning afterwards - it's not like you're relying on me to, y'know, store what you ask me to store". See L for just one illustration. In hindsight, I wish I'd made a sensible C a default setting, but I don't want to change that now.) The optional C setting enables logging of queries generated by the helper functions C et al in L. If you enable it, generated queries will be logged at 'debug' level. Be aware that they will contain the data you're passing to/from the database, so be careful not to enable this option in production, where you could inadvertently log sensitive information. If you prefer, you can also supply a pre-crafted DSN using the C setting; in that case, it will be used as-is, and the driver/database/host settings will be ignored. This may be useful if you're using some DBI driver which requires a peculiar DSN. The optional C defines your own class into which database handles should be blessed. This should be a subclass of L (or L directly, if you just want to skip the extra features). You will require slightly different options depending on the database engine you're talking to. For instance, for SQLite, you won't need to supply C, C etc, but will need to supply C as the name of the SQLite database file: plugins: Database: driver: SQLite database: 'foo.sqlite' For Oracle, you may want to pass C (system ID) to identify a particular database, e.g.: plugins: Database: driver: Oracle host: localhost sid: ABC12 If you have any further connection parameters that need to be appended to the dsn, you can put them in as a hash called dsn_extra. For example, if you're running mysql on a non-standard socket, you could have plugins: Database: driver: mysql host: localhost dsn_extra: mysql_socket: /tmp/mysql_staging.sock =head2 DEFINING MULTIPLE CONNECTIONS If you need to connect to multiple databases, this is easy - just list them in your config under C as shown below: plugins: Database: connections: foo: driver: "SQLite" database: "foo.sqlite" bar: driver: "mysql" host: "localhost" .... Then, you can call the C keyword with the name of the database connection you want, for example: my $foo_dbh = database('foo'); my $bar_dbh = database('bar'); =head1 RUNTIME CONFIGURATION You can pass a hashref to the C keyword to provide configuration details to override any in the config file at runtime if desired, for instance: my $dbh = database({ driver => 'SQLite', database => $filename }); (Thanks to Alan Haggai for this feature.) =head1 AUTOMATIC UTF-8 SUPPORT As of version 1.20, if your application is configured to use UTF-8 (you've defined the C setting in your app config as C) then support for UTF-8 for the database connection will be enabled, if we know how to do so for the database driver in use. If you do not want this behaviour, set C to a false value when providing the connection details. =head1 GETTING A DATABASE HANDLE Calling C will return a connected database handle; the first time it is called, the plugin will establish a connection to the database, and return a reference to the DBI object. On subsequent calls, the same DBI connection object will be returned, unless it has been found to be no longer usable (the connection has gone away), in which case a fresh connection will be obtained. If you have declared named connections as described above in 'DEFINING MULTIPLE CONNECTIONS', then calling the database() keyword with the name of the connection as specified in the config file will get you a database handle connected with those details. You can also pass a hashref of settings if you wish to provide settings at runtime. =head1 CONVENIENCE FEATURES (quick_select, quick_update, quick_insert, quick_delete, quick_count) The handle returned by the C keyword is a L object, which subclasses the C DBI connection handle. This means you can use it just like you'd normally use a DBI handle, but extra convenience methods are provided, as documented in the POD for L. Examples: # Quickly fetch the (first) row whose ID is 42 as a hashref: my $row = database->quick_select($table_name, { id => 42 }); # Fetch all badgers as an array of hashrefs: my @badgers = database->quick_select('animals', { genus => 'Mellivora' }); # Update the row where the 'id' column is '42', setting the 'foo' column to # 'Bar': database->quick_update($table_name, { id => 42 }, { foo => 'Bar' }); # Insert a new row, using a named connection (see above) database('connectionname')->quick_insert($table_name, { foo => 'Bar' }); # Delete the row with id 42: database->quick_delete($table_name, { id => 42 }); # Fetch all rows from a table (since version 1.30): database->quick_select($table_name, {}); # Retrieve a count of rows matching the criteria: database->quick_count($table_name, {}); There's more extensive documentation on these features in L, including using the C, C, C options to sort / limit results and include only specific columns. =head1 HOOKS This plugin uses Dancer2's hooks support to allow you to register code that should execute at given times - for example: hook 'database_connected' => sub { my $dbh = shift; # do something with the new DB handle here }; Currrently defined hook positions are: =over 4 =item C Called when a new database connection has been established, after performing any C statements, but before the handle is returned. Receives the new database handle as a parameter, so that you can do what you need with it. =item C Called when the plugin detects that the database connection has gone away. Receives the no-longer usable handle as a parameter, in case you need to extract some information from it (such as which server it was connected to). =item C Called when an attempt to connect to the database fails. Receives a hashref of connection settings as a parameter, containing the settings the plugin was using to connect (as obtained from the config file). =item C Called when a database error is raised by C. Receives two parameters: the error message being returned by DBI, and the database handle in question. =back If you need other hook positions which would be useful to you, please feel free to suggest them! =head1 AUTHOR David Precious, C<< >> =head1 CONTRIBUTING This module is developed on Github at: L Feel free to fork the repo and submit pull requests! Also, it makes sense to L on GitHub for updates. Feedback and bug reports are always appreciated. Even a quick mail to let me know the module is useful to you would be very nice - it's nice to know if code is being actively used. =head1 ACKNOWLEDGEMENTS Igor Bujna Franck Cuny Alan Haggai Christian Sánchez Michael Stiller Martin J Evans Carlos Sosa Matt S Trout Matthew Vickers Christian Walde Alberto Simões James Aitken (LoonyPandora) Mark Allen (mrallen1) Sergiy Borodych (bor) Mario Domgoergen (mdom) Andrey Inishev (inish777) Nick S. Knutov (knutov) Nicolas Franck (nicolasfranck) mscolly =head1 BUGS Please report any bugs or feature requests to C, or through the web interface at L. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc Dancer2::Plugin::Database You can also look for information at: =over 4 =item * RT: CPAN's request tracker L =item * AnnoCPAN: Annotated CPAN documentation L =item * CPAN Ratings L =item * Search CPAN L =back You can find the author on IRC in the channel C<#dancer> on . =head1 LICENSE AND COPYRIGHT Copyright 2010-13 David Precious. This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License. See http://dev.perl.org/licenses/ for more information. =head1 SEE ALSO L and L L, L L L =cut 1; # End of Dancer2::Plugin::Database