NAME
Mojo::Pg - Mojolicious ♥ PostgreSQL
SYNOPSIS
use Mojo::Pg;
# Create a table
my $pg = Mojo::Pg->new('postgresql://postgres@/test');
$pg->db->query('create table if not exists names (name text)');
# Insert a few rows
my $db = $pg->db;
$db->query('insert into names values (?)', 'Sara');
$db->query('insert into names values (?)', 'Daniel');
# Insert more rows in a transaction
{
my $tx = $db->begin;
$db->query('insert into names values (?)', 'Baerbel');
$db->query('insert into names values (?)', 'Wolfgang');
$tx->commit;
};
# Select one row at a time
my $results = $db->query('select * from names');
while (my $next = $results->hash) {
say $next->{name};
}
# JSON roundtrip
say $db->query('select ?::json as foo', {json => {bar => 'baz'}})
->expand->hash->{foo}{bar};
# Select all rows blocking
$db->query('select * from names')
->hashes->map(sub { $_->{name} })->join("\n")->say;
# Select all rows non-blocking
Mojo::IOLoop->delay(
sub {
my $delay = shift;
$db->query('select * from names' => $delay->begin);
},
sub {
my ($delay, $err, $results) = @_;
$results->hashes->map(sub { $_->{name} })->join("\n")->say;
}
)->wait;
# Listen for notifications non-blocking
$db->on(notification => sub {
my ($db, $name, $pid, $payload) = @_;
say "$name: $payload";
$db->notify('bar', $payload) if $name eq 'foo';
});
$db->listen('foo');
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
DESCRIPTION
Mojo::Pg is a tiny wrapper around DBD::Pg that makes PostgreSQL a lot of fun to use with the Mojolicious real-time web framework.
Database handles are cached automatically, so they can be reused transparently to increase performance. And you can handle connection timeouts gracefully by holding on to them only for short amounts of time.
use Mojolicious::Lite;
use Mojo::Pg;
helper pg =>
sub { state $pg = Mojo::Pg->new('postgresql://sri:s3cret@localhost/db') };
get '/' => sub {
my $c = shift;
my $db = $c->pg->db;
$c->render(json => $db->query('select now() as time')->hash);
};
app->start;
While all I/O operations are performed blocking, you can wait for long running queries asynchronously, allowing the Mojo::IOLoop event loop to perform other tasks in the meantime. Since database connections usually have a very low latency, this often results in very good performance.
Every database connection can only handle one active query at a time, this includes asynchronous ones. So if you start more than one, they will be put on a waiting list and performed sequentially. To perform multiple queries concurrently, you have to use multiple connections.
# Performed sequentially (10 seconds)
my $db = $pg->db;
$db->query('select pg_sleep(5)' => sub {...});
$db->query('select pg_sleep(5)' => sub {...});
# Performed concurrently (5 seconds)
$pg->db->query('select pg_sleep(5)' => sub {...});
$pg->db->query('select pg_sleep(5)' => sub {...});
All cached database handles will be reset automatically if a new process has been forked, this allows multiple processes to share the same Mojo::Pg object safely.
EVENTS
Mojo::Pg inherits all events from Mojo::EventEmitter and can emit the following new ones.
connection
$pg->on(connection => sub {
my ($pg, $dbh) = @_;
...
});
Emitted when a new database connection has been established.
ATTRIBUTES
Mojo::Pg implements the following attributes.
dsn
my $dsn = $pg->dsn;
$pg = $pg->dsn('dbi:Pg:dbname=foo');
Data source name, defaults to dbi:Pg:
.
max_connections
my $max = $pg->max_connections;
$pg = $pg->max_connections(3);
Maximum number of idle database handles to cache for future use, defaults to 5
.
migrations
my $migrations = $pg->migrations;
$pg = $pg->migrations(Mojo::Pg::Migrations->new);
Mojo::Pg::Migrations object you can use to change your database schema more easily.
# Load migrations from file and migrate to latest version
$pg->migrations->from_file('/Users/sri/migrations.sql')->migrate;
options
my $options = $pg->options;
$pg = $pg->options({AutoCommit => 1});
Options for database handles, defaults to activating AutoCommit
as well as RaiseError
and deactivating PrintError
as well as pg_server_prepare
.
password
my $password = $pg->password;
$pg = $pg->password('s3cret');
Database password, defaults to an empty string.
username
my $username = $pg->username;
$pg = $pg->username('sri');
Database username, defaults to an empty string.
METHODS
Mojo::Pg inherits all methods from Mojo::EventEmitter and implements the following new ones.
db
my $db = $pg->db;
Get Mojo::Pg::Database object for a cached or newly established database connection. The DBD::Pg database handle will be automatically cached again when that object is destroyed, so you can handle connection timeouts gracefully by holding on to it only for short amounts of time.
# Add up all the money
say $pg->db->query('select * from accounts')
->hashes->reduce(sub { $a->{money} + $b->{money} });
from_string
$pg = $pg->from_string('postgresql://postgres@/test');
Parse configuration from connection string.
# Just a database
$pg->from_string('postgresql:///db1');
# Just a service
$pg->from_string('postgresql://?service=foo');
# Username and database
$pg->from_string('postgresql://sri@/db2');
# Username, password, host and database
$pg->from_string('postgresql://sri:s3cret@localhost/db3');
# Username, domain socket and database
$pg->from_string('postgresql://sri@%2ftmp%2fpg.sock/db4');
# Username, database and additional options
$pg->from_string('postgresql://sri@/db5?PrintError=1&pg_server_prepare=1');
# Service and additional options
$pg->from_string('postgresql://?service=foo&PrintError=1&RaiseError=0');
new
my $pg = Mojo::Pg->new;
my $pg = Mojo::Pg->new('postgresql://postgres@/test');
Construct a new Mojo::Pg object and parse connection string with "from_string" if necessary.
# Customize configuration further
my $pg = Mojo::Pg->new->dsn('dbi:Pg:service=foo');
AUTHOR
Sebastian Riedel, sri@cpan.org
.
COPYRIGHT AND LICENSE
Copyright (C) 2014-2015, Sebastian Riedel.
This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.
SEE ALSO
https://github.com/kraih/mojo-pg, Mojolicious::Guides, http://mojolicio.us.