Dancer...tabase(3pm)
β¨ Dancer::Plugin::Database π (that's the Dancer...tabase(3pm) page bestie)
okay so. <rainbow>Dancer::Plugin::Database</rainbow> β easy database connections for Dancer applications. yes. that's the whole vibe. let's go π«Ά
πΈ NAME πΈ
Dancer::Plugin::Database β easy database connections for Dancer applications π
β¨ SYNOPSIS β¨
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 = ?',
);
$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 Dancer application config β see below π
π DESCRIPTION π
So. This plugin gives you a super easy way to get a connected DBI database handle β you literally just call the database keyword inside your Dancer app and boom, you're connected β¨
What you get back is 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, plus it adds a few convenience methods on top. full deets on those live in the Dancer::Plugin::Database::Core::Handle docs, go read 'em π
It also takes care of making sure your database handle is still connected and valid. here's the tea: if the handle was last asked for more than connection_check_threshold seconds ago, it'll check the connection is still alive β using the $dbh->ping method if the DBD driver supports it, or just doing a lil simple no-op query against the database if it doesn't. and if the connection has gone away? a fresh connection gets obtained and returned. no drama π
this saves you from the whole long-running-script situation where your connection to the database just... dips π
and listen β care is taken so handles are not shared across processes/threads, so this should be thread-safe with no issues with transactions etc. (shoutout to Matt S Trout for pointing out the previous lack of thread safety. inspiration was drawn from DBIx::Connector.) π«Ά
π CONFIGURATION π
Connection details get pulled from your Dancer application config file, and should look like, 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'
okay let's break down the settings one by one because there's a lot happening here bestie π
connection_check_thresholdβ optional! if you don't provide it, it defaults to30seconds. if thedatabasekeyword was last called more than this many seconds ago, a quick check gets performed to make sure we still have a connection, and it'll reconnect if not. this is what handles the case where the handle hasn't been used for a while and the underlying connection has gone away π¦dbi_paramsβ also optional. if you specify it, these should be settings that can be passed toDBI->connectas its fourth argument; go look at the DBI documentation for those β¨on_connect_doβ optional, and it's an array of queries that should be performed when a connection is established. if given, each query gets performed using$dbh->do. (if you're on MySQL, you might wanna use this to setSQL_MODEto 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.) π
log_queriesβ optional, and it enables logging of queries generated by the helper functionsquick_insertet al inDancer::Plugin::Database::Core::Handle. if you enable it, generated queries get 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. fr fr. don't do it. π
dsnβ if you prefer, you can also supply a pre-crafted DSN using this setting. in that case it gets 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 πhandle_classβ optional, and it defines your own class into which database handles should be blessed. this should be a subclass ofDancer::Plugin::Database::Core::Handle(orDBI::dbdirectly, if you just want to skip the extra features) π
You'll 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 you 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
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
π DEFINING MULTIPLE CONNECTIONS π
If you need to connect to multiple databases β bestie, it's 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');
slay. two databases. one plugin. π β¨
π 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. simple as that π
π GETTING A DATABASE HANDLE π
Calling database will return a connected database handle. the first time it's called, the plugin establishes a connection to the database and returns a reference to the DBI object. on subsequent calls, the same DBI connection object gets returned β unless it's been found to be no longer usable (the connection has gone away), in which case a fresh connection gets obtained. no cap πΈ
If you've 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 π
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 π«Ά
There's 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. go read it, it's giving organized π
π HOOKS π
This plugin uses Dancer'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 anyon_connect_dostatements, 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 byDBI. 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, "<davidp@preshweb.co.uk>" π
part 1 done bestie, more coming π
π CONTRIBUTING π
okay so this module lives on Github, bestie, at:
http://github.com/bigpresh/Dancer-Plugin-Database
fr fr go fork the repo and send pull requests, that's literally the whole vibe. also it lowkey makes sense to watch the repo over on GitHub so you catch updates as they drop:
https://github.com/bigpresh/Dancer-Plugin-Database/toggle_watch
Feedback and bug reports are always appreciated, no cap. And honestly? Even just a quick mail to let the author know the module is useful to you would be super nice β it's nice to know if code is being actively used. π₯Ήπ That's it. That's the ask.
π ACKNOWLEDGEMENTS π
the way these absolute icons contributed, we have to stan. every single one:
- 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
periodt. π
π BUGS π
found a bug? got a feature request? don't suffer in silence, bestie. report it to bug-dancer-plugin-database at rt.cpan.org, or just slide into the web interface at:
http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Dancer-Plugin-Database
how it works: I get notified, and then you automatically get notified of progress on your bug as changes get made. it's giving teamwork. it's giving communication. π«Ά
π SUPPORT π
you can find the docs for this module with the perldoc command, like so:
perldoc Dancer::Plugin::Database
and you can also go looking for info at these spots:
- RT: CPAN's request tracker β
http://rt.cpan.org/NoAuth/Bugs.html?Dist=Dancer-Plugin-Database - AnnoCPAN: Annotated CPAN documentation β
http://annocpan.org/dist/Dancer-Plugin-Database - CPAN Ratings β
http://cpanratings.perl.org/d/Dancer-Plugin-Database - Search CPAN β
http://search.cpan.org/dist/Dancer-Plugin-Database/
also!! you can find the author on IRC hanging out in the channel #dancer on irc.perl.org. come say hi, iykyk. β¨
π LICENSE AND COPYRIGHT π
Copyright 2010-2016 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.
two licenses, pick your fave, both iconic. π
πΈ SEE ALSO πΈ
- Dancer
- DBI
- Dancer::Plugin::SimpleCRUD
and that's the whole page, bestie!! π¦ you made it to the end, main character behaviour honestly. this was perl v5.34.0, dated 2022-06-12, and the page itself is Dancer...tabase(3pm) β go build something cute with it. mwah. πππΈ
π¦ where this page comes from
- debian bookworm: libdancer-plugin-database-perl 2.13-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libdancer-plugin-database-perl 2.13-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libdancer-plugin-database-perl 2.13-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libdancer-plugin-database-perl 2.13-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libdancer-plugin-database-perl 2.13-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms