.\" Automatically generated by Pod::Man 4.07 (Pod::Simple 3.32) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .if !\nF .nr F 0 .if \nF>0 \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} .\} .\" ======================================================================== .\" .IX Title "Mojo::Pg 3pm" .TH Mojo::Pg 3pm "2017-01-14" "perl v5.24.1" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Mojo::Pg \- Mojolicious ♥ PostgreSQL .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use Mojo::Pg; \& \& # Select the server version \& my $pg = Mojo::Pg\->new(\*(Aqpostgresql://postgres@/test\*(Aq); \& say $pg\->db\->query(\*(Aqselect version() as version\*(Aq)\->hash\->{version}; \& \& # Use migrations to create a table \& $pg\->migrations\->name(\*(Aqmy_names_app\*(Aq)\->from_string(<migrate; \& \-\- 1 up \& create table names (id serial primary key, name text); \& \-\- 1 down \& drop table names; \& EOF \& \& # Use migrations to drop and recreate the table \& $pg\->migrations\->migrate(0)\->migrate; \& \& # Insert a few rows \& my $db = $pg\->db; \& $db\->query(\*(Aqinsert into names (name) values (?)\*(Aq, \*(AqSara\*(Aq); \& $db\->query(\*(Aqinsert into names (name) values (?)\*(Aq, \*(AqStefan\*(Aq); \& \& # Insert more rows in a transaction \& eval { \& my $tx = $db\->begin; \& $db\->query(\*(Aqinsert into names (name) values (?)\*(Aq, \*(AqBaerbel\*(Aq); \& $db\->query(\*(Aqinsert into names (name) values (?)\*(Aq, \*(AqWolfgang\*(Aq); \& $tx\->commit; \& }; \& say $@ if $@; \& \& # Insert another row and return the generated id \& say $db\->query(\*(Aqinsert into names (name) values (?) returning id\*(Aq, \*(AqDaniel\*(Aq) \& \->hash\->{id}; \& \& # JSON roundtrip \& say $db\->query(\*(Aqselect ?::json as foo\*(Aq, {json => {bar => \*(Aqbaz\*(Aq}}) \& \->expand\->hash\->{foo}{bar}; \& \& # Select one row at a time \& my $results = $db\->query(\*(Aqselect * from names\*(Aq); \& while (my $next = $results\->hash) { \& say $next\->{name}; \& } \& \& # Select all rows blocking \& say $_\->{name} for $db\->query(\*(Aqselect * from names\*(Aq)\->hashes\->each; \& \& # Select all rows non\-blocking \& $db\->query(\*(Aqselect * from names\*(Aq => 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 a delay) \& Mojo::IOLoop\->delay( \& sub { \& my $delay = shift; \& $pg\->db\->query(\*(Aqselect now() as now\*(Aq => $delay\->begin); \& $pg\->db\->query(\*(Aqselect * from names\*(Aq => $delay\->begin); \& }, \& sub { \& my ($delay, $time_err, $time, $names_err, $names) = @_; \& if (my $err = $time_err || $names_err) { die $err } \& say $time\->hash\->{now}; \& say $_\->{name} for $names\->hashes\->each; \& } \& )\->wait; \& \& # 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 => \*(AqPostgreSQL rocks!\*(Aq); \& Mojo::IOLoop\->start unless Mojo::IOLoop\->is_running; .Ve .SH "DESCRIPTION" .IX Header "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. .PP 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. .PP .Vb 2 \& use Mojolicious::Lite; \& use Mojo::Pg; \& \& helper pg => sub { state $pg = Mojo::Pg\->new(\*(Aqpostgresql://postgres@/test\*(Aq) }; \& \& get \*(Aq/\*(Aq => sub { \& my $c = shift; \& my $db = $c\->pg\->db; \& $c\->render(json => $db\->query(\*(Aqselect now() as now\*(Aq)\->hash); \& }; \& \& app\->start; .Ve .PP In this example application, we create a \f(CW\*(C`pg\*(C'\fR helper to store a Mojo::Pg object. Our action calls that helper and uses the method \*(L"db\*(R" in Mojo::Pg to dequeue a Mojo::Pg::Database object from the connection pool. Then we use the method \*(L"query\*(R" in Mojo::Pg::Database to execute an \&\s-1SQL\s0 statement, which returns a Mojo::Pg::Results object. And finally we call the method \&\*(L"hash\*(R" in Mojo::Pg::Results to retrieve the first row as a hash reference. .PP 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. .PP 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. .PP .Vb 3 \& # Performed concurrently (5 seconds) \& $pg\->db\->query(\*(Aqselect pg_sleep(5)\*(Aq => sub {...}); \& $pg\->db\->query(\*(Aqselect pg_sleep(5)\*(Aq => sub {...}); .Ve .PP 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. .SH "GROWING" .IX Header "GROWING" And as your application grows, you can move queries into model classes. .PP .Vb 2 \& package MyApp::Model::Time; \& use Mojo::Base \-base; \& \& has \*(Aqpg\*(Aq; \& \& sub now { shift\->pg\->db\->query(\*(Aqselect now() as now\*(Aq)\->hash } \& \& 1; .Ve .PP Which get integrated into your application with helpers. .PP .Vb 3 \& use Mojolicious::Lite; \& use Mojo::Pg; \& use MyApp::Model::Time; \& \& helper pg => sub { state $pg = Mojo::Pg\->new(\*(Aqpostgresql://postgres@/test\*(Aq) }; \& helper time => sub { state $time = MyApp::Model::Time\->new(pg => shift\->pg) }; \& \& get \*(Aq/\*(Aq => sub { \& my $c = shift; \& $c\->render(json => $c\->time\->now); \& }; \& \& app\->start; .Ve .SH "EVENTS" .IX Header "EVENTS" Mojo::Pg inherits all events from Mojo::EventEmitter and can emit the following new ones. .SS "connection" .IX Subsection "connection" .Vb 4 \& $pg\->on(connection => sub { \& my ($pg, $dbh) = @_; \& ... \& }); .Ve .PP Emitted when a new database connection has been established. .PP .Vb 4 \& $pg\->on(connection => sub { \& my ($pg, $dbh) = @_; \& $dbh\->do(\*(Aqset search_path to my_schema\*(Aq); \& }); .Ve .SH "ATTRIBUTES" .IX Header "ATTRIBUTES" Mojo::Pg implements the following attributes. .SS "auto_migrate" .IX Subsection "auto_migrate" .Vb 2 \& my $bool = $pg\->auto_migrate; \& $pg = $pg\->auto_migrate($bool); .Ve .PP Automatically migrate to the latest database schema with \*(L"migrations\*(R", as soon as the first database connection has been established. .SS "database_class" .IX Subsection "database_class" .Vb 2 \& my $class = $pg\->database_class; \& $pg = $pg\->database_class(\*(AqMyApp::Database\*(Aq); .Ve .PP Class to be used by \*(L"db\*(R", defaults to Mojo::Pg::Database. Note that this class needs to have already been loaded before \*(L"db\*(R" is called. .SS "dsn" .IX Subsection "dsn" .Vb 2 \& my $dsn = $pg\->dsn; \& $pg = $pg\->dsn(\*(Aqdbi:Pg:dbname=foo\*(Aq); .Ve .PP Data source name, defaults to \f(CW\*(C`dbi:Pg:\*(C'\fR. .SS "max_connections" .IX Subsection "max_connections" .Vb 2 \& my $max = $pg\->max_connections; \& $pg = $pg\->max_connections(3); .Ve .PP Maximum number of idle database handles to cache for future use, defaults to \&\f(CW5\fR. .SS "migrations" .IX Subsection "migrations" .Vb 2 \& my $migrations = $pg\->migrations; \& $pg = $pg\->migrations(Mojo::Pg::Migrations\->new); .Ve .PP Mojo::Pg::Migrations object you can use to change your database schema more easily. .PP .Vb 2 \& # Load migrations from file and migrate to latest version \& $pg\->migrations\->from_file(\*(Aq/home/sri/migrations.sql\*(Aq)\->migrate; .Ve .SS "options" .IX Subsection "options" .Vb 2 \& my $options = $pg\->options; \& $pg = $pg\->options({AutoCommit => 1, RaiseError => 1}); .Ve .PP Options for database handles, defaults to activating \f(CW\*(C`AutoCommit\*(C'\fR, \&\f(CW\*(C`AutoInactiveDestroy\*(C'\fR as well as \f(CW\*(C`RaiseError\*(C'\fR and deactivating \f(CW\*(C`PrintError\*(C'\fR. Note that \f(CW\*(C`AutoCommit\*(C'\fR and \f(CW\*(C`RaiseError\*(C'\fR are considered mandatory, so deactivating them would be very dangerous. .SS "password" .IX Subsection "password" .Vb 2 \& my $password = $pg\->password; \& $pg = $pg\->password(\*(Aqs3cret\*(Aq); .Ve .PP Database password, defaults to an empty string. .SS "pubsub" .IX Subsection "pubsub" .Vb 2 \& my $pubsub = $pg\->pubsub; \& $pg = $pg\->pubsub(Mojo::Pg::PubSub\->new); .Ve .PP Mojo::Pg::PubSub object you can use to send and receive notifications very efficiently, by sharing a single database connection with many consumers. .PP .Vb 5 \& # Subscribe to a channel \& $pg\->pubsub\->listen(news => sub { \& my ($pubsub, $payload) = @_; \& say "Received: $payload"; \& }); \& \& # Notify a channel \& $pg\->pubsub\->notify(news => \*(AqPostgreSQL rocks!\*(Aq); .Ve .SS "search_path" .IX Subsection "search_path" .Vb 2 \& my $path = $pg\->search_path; \& $pg = $pg\->search_path([\*(Aq$user\*(Aq, \*(Aqfoo\*(Aq, \*(Aqpublic\*(Aq]); .Ve .PP Schema search path assigned to all new connections. .PP .Vb 6 \& # Isolate tests and avoid race conditions when running them in parallel \& my $pg = Mojo::Pg\->new(\*(Aqpostgresql:///test\*(Aq)\->search_path([\*(Aqtest_one\*(Aq]); \& $pg\->db\->query(\*(Aqdrop schema if exists test_one cascade\*(Aq); \& $pg\->db\->query(\*(Aqcreate schema test_one\*(Aq); \& ... \& $pg\->db\->query(\*(Aqdrop schema test_one cascade\*(Aq); .Ve .SS "username" .IX Subsection "username" .Vb 2 \& my $username = $pg\->username; \& $pg = $pg\->username(\*(Aqsri\*(Aq); .Ve .PP Database username, defaults to an empty string. .SH "METHODS" .IX Header "METHODS" Mojo::Pg inherits all methods from Mojo::EventEmitter and implements the following new ones. .SS "db" .IX Subsection "db" .Vb 1 \& my $db = $pg\->db; .Ve .PP Get a database object based on \*(L"database_class\*(R" 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. .PP .Vb 3 \& # Add up all the money \& say $pg\->db\->query(\*(Aqselect * from accounts\*(Aq) \& \->hashes\->reduce(sub { $a\->{money} + $b\->{money} }); .Ve .SS "from_string" .IX Subsection "from_string" .Vb 1 \& $pg = $pg\->from_string(\*(Aqpostgresql://postgres@/test\*(Aq); .Ve .PP Parse configuration from connection string. .PP .Vb 2 \& # Just a database \& $pg\->from_string(\*(Aqpostgresql:///db1\*(Aq); \& \& # Just a service \& $pg\->from_string(\*(Aqpostgresql://?service=foo\*(Aq); \& \& # Username and database \& $pg\->from_string(\*(Aqpostgresql://sri@/db2\*(Aq); \& \& # Short scheme, username, password, host and database \& $pg\->from_string(\*(Aqpostgres://sri:s3cret@localhost/db3\*(Aq); \& \& # Username, domain socket and database \& $pg\->from_string(\*(Aqpostgresql://sri@%2ftmp%2fpg.sock/db4\*(Aq); \& \& # Username, database and additional options \& $pg\->from_string(\*(Aqpostgresql://sri@/db5?PrintError=1&pg_server_prepare=0\*(Aq); \& \& # Service and additional options \& $pg\->from_string(\*(Aqpostgresql://?service=foo&PrintError=1&RaiseError=0\*(Aq); .Ve .SS "new" .IX Subsection "new" .Vb 2 \& my $pg = Mojo::Pg\->new; \& my $pg = Mojo::Pg\->new(\*(Aqpostgresql://postgres@/test\*(Aq); .Ve .PP Construct a new Mojo::Pg object and parse connection string with \&\*(L"from_string\*(R" if necessary. .PP .Vb 2 \& # Customize configuration further \& my $pg = Mojo::Pg\->new\->dsn(\*(Aqdbi:Pg:service=foo\*(Aq); .Ve .SH "REFERENCE" .IX Header "REFERENCE" This is the class hierarchy of the Mojo::Pg distribution. .IP "\(bu" 2 Mojo::Pg .IP "\(bu" 2 Mojo::Pg::Database .IP "\(bu" 2 Mojo::Pg::Migrations .IP "\(bu" 2 Mojo::Pg::PubSub .IP "\(bu" 2 Mojo::Pg::Results .IP "\(bu" 2 Mojo::Pg::Transaction .SH "AUTHOR" .IX Header "AUTHOR" Sebastian Riedel, \f(CW\*(C`sri@cpan.org\*(C'\fR. .SH "CREDITS" .IX Header "CREDITS" In alphabetical order: .Sp .RS 2 Dan Book .Sp Flavio Poletti .Sp Hernan Lopes .Sp William Lindley .RE .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" Copyright (C) 2014\-2017, Sebastian Riedel and others. .PP This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0. .SH "SEE ALSO" .IX Header "SEE ALSO" , Mojolicious::Guides, .