Dancer::Plugin::Database - easy database support for Dancer applications
Clone or download
Pull request Compare This branch is 2 commits ahead, 332 commits behind bigpresh:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.


    Dancer::Plugin::Database - easy database connections for Dancer

        use Dancer;
        use Dancer::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 = ?',
            template 'display_widget', { widget => $sth->fetchrow_hashref };

        # The handle is a Dancer::Plugin::Database::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} }),


    Database connection details are read from your Dancer application config
    - see below.

    Provides an easy way to obtain a connected DBI database handle by simply
    calling the database keyword within your Dancer application

    Returns a Dancer::Plugin::Database::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::Handle for full details of

    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.

    Connection details will be taken from your Dancer application config
    file, and should be specified as, for example:

                driver: 'mysql'
                database: 'test'
                host: 'localhost'
                username: 'myusername'
                password: 'mypassword'
                connection_check_threshold: 10
                    RaiseError: 1
                    AutoCommit: 1
                on_connect_do: ["SET NAMES 'utf8'", "SET CHARACTER SET 'utf8'" ]

    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 third 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 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.

    If you need to connect to multiple databases, this is easy - just list
    them in your config under `connections' as shown below:

                        driver: "SQLite"
                        database: "foo.sqlite"
                        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');

    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.)

    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::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::Handle.


      # 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 });

    David Precious, `<>'

    This module is developed on Github at:

    Feel free to fork the repo and submit pull requests!

    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.

    Igor Bujna

    Franck Cuny

    Alan Haggai

    Christian Sánchez

    Michael Stiller

    Please report any bugs or feature requests to
    `bug-dancer-plugin-database at', or through the web
    interface at I
    will be notified, and then you'll automatically be notified of progress
    on your bug as I make changes.

    You can find documentation for this module with the perldoc command.

        perldoc Dancer::Plugin::Database

    You can also look for information at:

    * RT: CPAN's request tracker

    * AnnoCPAN: Annotated CPAN documentation

    * CPAN Ratings

    * Search CPAN

    You can find the author on IRC in the channel `#dancer' on

    Copyright 2010-11 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 for more information.