Mojo::Pg - Mojolicious ♥ PostgreSQL


use Mojo::Pg;

# Use a PostgreSQL connection string for configuration
my $pg = Mojo::Pg->new('postgresql://postgres@/test');

# Select the server version
say $pg->db->query('select version() as version')->hash->{version};

# Use migrations to create a table
-- 1 up
create table names (id serial primary key, name text);
-- 1 down
drop table names;

# Use migrations to drop and recreate the table

# Get a database handle from the cache for multiple queries
my $db = $pg->db;

# Use SQL::Abstract to generate simple CRUD queries for you
$db->insert('names', {name => 'Isabell'});
my $id = $db->select('names', ['id'], {name => 'Isabell'})->hash->{id};
$db->update('names', {name => 'Belle'}, {id => $id});
$db->delete('names', {name => 'Belle'});

# Insert a few rows in a transaction with SQL and placeholders
eval {
  my $tx = $db->begin;
  $db->query('insert into names (name) values (?)', 'Sara');
  $db->query('insert into names (name) values (?)', 'Stefan');
say $@ if $@;

# Insert another row with SQL::Abstract and return the generated id
say $db->insert('names', {name => 'Daniel'}, {returning => 'id'})->hash->{id};

# JSON roundtrip
say $db->query('select ?::json as foo', {json => {bar => 'baz'}})

# Select all rows blocking with SQL::Abstract
say $_->{name} for $db->select('names')->hashes->each;

# Select all rows non-blocking with SQL::Abstract
$db->select('names' => sub {
  my ($db, $err, $results) = @_;
  die $err if $err;
  say $_->{name} for $results->hashes->each;
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

# Concurrent non-blocking queries (synchronized with promises)
my $now   = $pg->db->query_p('select now() as now');
my $names = $pg->db->query_p('select * from names');
Mojo::Promise->all($now, $names)->then(sub {
  my ($now, $names) = @_;
  say $now->[0]->hash->{now};
  say $_->{name} for $names->[0]->hashes->each;
})->catch(sub {
  my $err = shift;
  warn "Something went wrong: $err";

# Send and receive notifications non-blocking
$pg->pubsub->listen(foo => sub {
  my ($pubsub, $payload) = @_;
  say "foo: $payload";
  $pubsub->notify(bar => $payload);
$pg->pubsub->listen(bar => sub {
  my ($pubsub, $payload) = @_;
  say "bar: $payload";
$pg->pubsub->notify(foo => 'PostgreSQL rocks!');
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;


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. Perform queries blocking and non-blocking, use all SQL features PostgreSQL has to offer, generate CRUD queries from data structures, manage your database schema with migrations and build scalable real-time web applications with the publish/subscribe pattern.


Database and statement handles are cached automatically, and will be reused transparently to increase performance. 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://postgres@/test') };

get '/' => sub {
  my $c  = shift;
  my $db = $c->pg->db;
  $c->render(json => $db->query('select now() as now')->hash);


In this example application, we create a pg helper to store a Mojo::Pg object. Our action calls that helper and uses the method "db" in Mojo::Pg to dequeue a Mojo::Pg::Database object from the connection pool. Then we use the method "query" in Mojo::Pg::Database to execute an SQL statement, which returns a Mojo::Pg::Results object. And finally we call the method "hash" in Mojo::Pg::Results to retrieve the first row as a hash reference.

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. To perform multiple queries concurrently, you have to use multiple connections.

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


And as your application grows, you can move queries into model classes.

package MyApp::Model::Time;
use Mojo::Base -base;

has 'pg';

sub now { shift->pg->db->query('select now() as now')->hash }


Which get integrated into your application with helpers.

use Mojolicious::Lite;
use Mojo::Pg;
use MyApp::Model::Time;

helper pg => sub { state $pg = Mojo::Pg->new('postgresql://postgres@/test') };
helper time => sub { state $time = MyApp::Model::Time->new(pg => shift->pg) };

get '/' => sub {
  my $c = shift;
  $c->render(json => $c->time->now);



This distribution also contains two great example applications you can use for inspiration. The minimal chat application will show you how to scale WebSockets to multiple servers, and the well-structured blog application how to apply the MVC design pattern in practice.


Mojo::Pg inherits all events from Mojo::EventEmitter and can emit the following new ones.


$pg->on(connection => sub {
  my ($pg, $dbh) = @_;

Emitted when a new database connection has been established.

$pg->on(connection => sub {
  my ($pg, $dbh) = @_;
  $dbh->do('set search_path to my_schema');


Mojo::Pg implements the following attributes.


my $abstract = $pg->abstract;
$pg          = $pg->abstract(SQL::Abstract::Pg->new);

SQL::Abstract::Pg object used to generate CRUD queries for Mojo::Pg::Database, defaults to enabling array_datatypes and setting name_sep to . and quote_char to ".

# Generate WHERE clause and bind values
my($stmt, @bind) = $pg->abstract->where({foo => 'bar', baz => 'yada'});


my $bool = $pg->auto_migrate;
$pg      = $pg->auto_migrate($bool);

Automatically migrate to the latest database schema with "migrations", as soon as "db" has been called for the first time.


my $class = $pg->database_class;
$pg       = $pg->database_class('MyApp::Database');

Class to be used by "db", defaults to Mojo::Pg::Database. Note that this class needs to have already been loaded before "db" is called.


my $dsn = $pg->dsn;
$pg     = $pg->dsn('dbi:Pg:dbname=foo');

Data source name, defaults to dbi:Pg:.


my $max = $pg->max_connections;
$pg     = $pg->max_connections(3);

Maximum number of idle database handles to cache for future use, defaults to 1.


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


my $options = $pg->options;
$pg         = $pg->options({AutoCommit => 1, RaiseError => 1});

Options for database handles, defaults to activating AutoCommit, AutoInactiveDestroy as well as RaiseError and deactivating PrintError as well as PrintWarn. Note that AutoCommit and RaiseError are considered mandatory, so deactivating them would be very dangerous.


my $parent = $pg->parent;
$pg        = $pg->parent(Mojo::Pg->new);

Another Mojo::Pg object to use for connection management, instead of establishing and caching our own database connections.


my $password = $pg->password;
$pg          = $pg->password('s3cret');

Database password, defaults to an empty string.


my $pubsub = $pg->pubsub;
$pg        = $pg->pubsub(Mojo::Pg::PubSub->new);

Mojo::Pg::PubSub object you can use to send and receive notifications very efficiently, by sharing a single database connection with many consumers.

# Subscribe to a channel
$pg->pubsub->listen(news => sub {
  my ($pubsub, $payload) = @_;
  say "Received: $payload";

# Notify a channel
$pg->pubsub->notify(news => 'PostgreSQL rocks!');


my $path = $pg->search_path;
$pg      = $pg->search_path(['$user', 'foo', 'public']);

Schema search path assigned to all new connections.

# Isolate tests and avoid race conditions when running them in parallel
my $pg = Mojo::Pg->new('postgresql:///test')->search_path(['test_one']);
$pg->db->query('drop schema if exists test_one cascade');
$pg->db->query('create schema test_one');
$pg->db->query('drop schema test_one cascade');


my $username = $pg->username;
$pg          = $pg->username('sri');

Database username, defaults to an empty string.


Mojo::Pg inherits all methods from Mojo::EventEmitter and implements the following new ones.


my $db = $pg->db;

Get a database object based on "database_class" (which is usually Mojo::Pg::Database) 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 problems like connection timeouts gracefully by holding on to it only for short amounts of time.

# Add up all the money
say $pg->db->select('accounts')
  ->hashes->reduce(sub { $a->{money} + $b->{money} });


$pg = $pg->from_string('postgresql://postgres@/test');
$pg = $pg->from_string(Mojo::Pg->new);

Parse configuration from connection string or use another Mojo::Pg object as "parent".

# Just a database

# Just a service

# Username and database

# Short scheme, username, password, host and database

# Username, domain socket and database

# Username, database and additional options

# Service and additional options

# Username, database, an option and search_path


my $pg = Mojo::Pg->new;
my $pg = Mojo::Pg->new('postgresql://postgres@/test');
my $pg = Mojo::Pg->new(Mojo::Pg->new);

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');


You can set the DBI_TRACE environment variable to get some advanced diagnostics information printed by DBI.



This is the class hierarchy of the Mojo::Pg distribution.


Sebastian Riedel,


In alphabetical order:


Copyright (C) 2014-2018, Sebastian Riedel and others.

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, Mojolicious::Guides,