Skip to content

rwx-zwx-awx/mojo-mysql

 
 

Repository files navigation

NAME

Mojo::mysql - Mojolicious and Async MySQL

SYNOPSIS

use Mojo::mysql;

# Create a table
my $mysql = Mojo::mysql->new('mysql://username@/test');
$mysql->db->query(
  'create table names (id integer auto_increment primary key, name text)');

# Insert a few rows
my $db = $mysql->db;
$db->query('insert into names (name) values (?)', 'Sara');
$db->query('insert into names (name) values (?)', 'Stefan');

# Insert more rows in a transaction
eval {
  my $tx = $db->begin;
  $db->query('insert into names (name) values (?)', 'Baerbel');
  $db->query('insert into names (name) values (?)', 'Wolfgang');
  $tx->commit;
};
say $@ if $@;

# Insert another row and return the generated id
say $db->query('insert into names (name) values (?)', 'Daniel')
  ->last_insert_id;

# Select one row at a time
my $results = $db->query('select * from names');
while (my $next = $results->hash) {
  say $next->{name};
}

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

# Send and receive notifications non-blocking
$mysql->pubsub->listen(foo => sub {
  my ($pubsub, $payload) = @_;
  say "foo: $payload";
  $pubsub->notify(bar => $payload);
});
$mysql->pubsub->listen(bar => sub {
  my ($pubsub, $payload) = @_;
  say "bar: $payload";
});
$mysql->pubsub->notify(foo => 'MySQL rocks!');

Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

DESCRIPTION

Mojo::mysql is a tiny wrapper around DBD::mysql that makes MySQL a lot of fun to use with the Mojolicious real-time web framework.

Database and 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::mysql;

helper mysql =>
  sub { state $pg = Mojo::mysql->new('mysql://sri:s3cret@localhost/db') };

get '/' => sub {
  my $c  = shift;
  my $db = $c->mysql->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 = $mysql->db;
$db->query('select sleep(5)' => sub {...});
$db->query('select sleep(5)' => sub {...});

# Performed concurrently (5 seconds)
$mysql->db->query('select sleep(5)' => sub {...});
$mysql->db->query('select 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::mysql object safely.

Note that this whole distribution is EXPERIMENTAL and will change without warning!

EVENTS

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

connection

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

Emitted when a new database connection has been established.

ATTRIBUTES

Mojo::mysql implements the following attributes.

dsn

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

Data Source Name, defaults to dbi:mysql:dbname=test.

max_connections

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

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

migrations

my $migrations = $mysql->migrations;
$mysql         = $mysql->migrations(Mojo::mysql::Migrations->new);

Mojo::mysql::Migrations object you can use to change your database schema more easily.

# Load migrations from file and migrate to latest version
$mysql->migrations->from_file('/Users/sri/migrations.sql')->migrate;

MySQL does not support nested transactions and DDL transactions. DDL statements cause implicit COMMIT. ROLLBACK will be called if any step of migration script fails, but only DML statements after the last implicit or explicit COMMIT can be reverted. Not all MySQL storage engines (like MYISAM) support transactions.

This means database will most likely be left in unknown state if migration script fails. Use this feature with caution and remember to always backup your database.

options

my $options = $mysql->options;
$mysql      = $mysql->options({mysql_use_result => 1});

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

mysql_auto_reconnect is never enabled, Mojo::mysql takes care of dead connections.

AutoCommit cannot not be disabled, use $db->begin to manage transactions.

RaiseError is enabled for blocking and disabled in event loop for non-blocking queries.

password

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

Database password, defaults to an empty string.

pubsub

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

Mojo::mysql::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
$mysql->pubsub->listen(news => sub {
  my ($pubsub, $payload) = @_;
  say "Received: $payload";
});

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

username

my $username = $mysql->username;
$mysql       = $mysql->username('batman');

Database username, defaults to an empty string.

METHODS

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

db

my $db = $mysql->db;

Get Mojo::mysql::Database object for a cached or newly created database handle. The 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.

from_string

$mysql = $mysql->from_string('mysql://user@/test');

Parse configuration from connection string.

# Just a database
$mysql->from_string('mysql:///db1');

# Username and database
$mysql->from_string('mysql://batman@/db2');

# Username, password, host and database
$mysql->from_string('mysql://batman:s3cret@localhost/db3');

# Username, domain socket and database
$mysql->from_string('mysql://batman@%2ftmp%2fmysql.sock/db4');

# Username, database and additional options
$mysql->from_string('mysql://batman@/db5?PrintError=1&RaiseError=0');

new

my $mysql = Mojo::mysql->new;
my $mysql = Mojo::mysql->new('mysql://user@/test');

Construct a new Mojo::mysql object and parse connection string with "from_string" if necessary.

REFERENCE

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

AUTHOR

Curt Hochwender, [email protected].

Jan Henning Thorsen, [email protected].

This code is mostly a rip-off from Sebastian Riedel's Mojo::Pg.

COPYRIGHT AND LICENSE

Copyright (C) 2014-2015, Jan Henning Thorsen.

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/jhthorsen/mojo-mysql,

Mojo::Pg Async Connector for PostgreSQL using DBD::Pg, https://github.com/kraih/mojo-pg,

Mojo::MySQL5 Pure-Perl non-blocking I/O MySQL Connector, https://github.com/harry-bix/mojo-mysql5,

Mojolicious::Guides, http://mojolicio.us.

About

Mojolicious and Async MySQL

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Perl 90.1%
  • Other 9.9%