.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.40) .\" .\" 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 .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Mojo::Pg 3pm" .TH Mojo::Pg 3pm "2021-02-18" "perl v5.32.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; \& \& # Use a PostgreSQL connection string for configuration \& my $pg = Mojo::Pg\->new(\*(Aqpostgresql://postgres@/test\*(Aq); \& \& # Select the server version \& 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; \& \& # 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(\*(Aqnames\*(Aq, {name => \*(AqIsabell\*(Aq}); \& my $id = $db\->select(\*(Aqnames\*(Aq, [\*(Aqid\*(Aq], {name => \*(AqIsabell\*(Aq})\->hash\->{id}; \& $db\->update(\*(Aqnames\*(Aq, {name => \*(AqBelle\*(Aq}, {id => $id}); \& $db\->delete(\*(Aqnames\*(Aq, {name => \*(AqBelle\*(Aq}); \& \& # Insert a few rows in a transaction with SQL and placeholders \& eval { \& my $tx = $db\->begin; \& $db\->query(\*(AqINSERT INTO names (name) VALUES (?)\*(Aq, \*(AqSara\*(Aq); \& $db\->query(\*(AqINSERT INTO names (name) VALUES (?)\*(Aq, \*(AqStefan\*(Aq); \& $tx\->commit; \& }; \& say $@ if $@; \& \& # Insert another row with SQL::Abstract and return the generated id \& say $db\->insert(\*(Aqnames\*(Aq, {name => \*(AqDaniel\*(Aq}, {returning => \*(Aqid\*(Aq})\->hash\->{id}; \& \& # JSON roundtrip \& say $db\->query(\*(AqSELECT ?::JSON AS foo\*(Aq, {json => {bar => \*(Aqbaz\*(Aq}}) \& \->expand\->hash\->{foo}{bar}; \& \& # Select all rows blocking with SQL::Abstract \& say $_\->{name} for $db\->select(\*(Aqnames\*(Aq)\->hashes\->each; \& \& # Select all rows non\-blocking with SQL::Abstract \& $db\->select(\*(Aqnames\*(Aq => sub ($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(\*(AqSELECT NOW() AS now\*(Aq); \& my $names = $pg\->db\->query_p(\*(AqSELECT * FROM names\*(Aq); \& Mojo::Promise\->all($now, $names)\->then(sub ($now, $names) { \& say $now\->[0]\->hash\->{now}; \& say $_\->{name} for $names\->[0]\->hashes\->each; \& })\->catch(sub ($err) { \& warn "Something went wrong: $err"; \& })\->wait; \& \& # Send and receive notifications non\-blocking \& $pg\->pubsub\->listen(foo => sub ($pubsub, $payload) { \& say "foo: $payload"; \& $pubsub\->notify(bar => $payload); \& }); \& $pg\->pubsub\->listen(bar => sub ($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. Perform queries blocking and non-blocking, use all \s-1SQL\s0 features PostgreSQL has to offer, generate \s-1CRUD\s0 queries from data structures, manage your database schema with migrations and build scalable real-time web applications with the publish/subscribe pattern. .SH "BASICS" .IX Header "BASICS" 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 \-signatures; \& use Mojo::Pg; \& \& helper pg => sub { state $pg = Mojo::Pg\->new(\*(Aqpostgresql://postgres@/test\*(Aq) }; \& \& get \*(Aq/\*(Aq => sub ($c) { \& 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 ($db, $err, $results) {...}); \& $pg\->db\->query(\*(AqSELECT PG_SLEEP(5)\*(Aq => sub ($db, $err, $results) {...}); .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, \-signatures; \& \& has \*(Aqpg\*(Aq; \& \& sub now ($self) { \& return $self\->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 \-signatures; \& 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 ($c) { \& $c\->render(json => $c\->time\->now); \& }; \& \& app\->start; .Ve .SH "EXAMPLES" .IX Header "EXAMPLES" 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 \s-1MVC\s0 design pattern in practice. .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 3 \& $pg\->on(connection => sub ($pg, $dbh) { \& ... \& }); .Ve .PP Emitted when a new database connection has been established. .PP .Vb 3 \& $pg\->on(connection => sub ($pg, $dbh) { \& $dbh\->do(\*(AqSET search_path TO my_schema\*(Aq); \& }); .Ve .SH "ATTRIBUTES" .IX Header "ATTRIBUTES" Mojo::Pg implements the following attributes. .SS "abstract" .IX Subsection "abstract" .Vb 2 \& my $abstract = $pg\->abstract; \& $pg = $pg\->abstract(SQL::Abstract::Pg\->new); .Ve .PP SQL::Abstract::Pg object used to generate \s-1CRUD\s0 queries for Mojo::Pg::Database, defaults to enabling \&\f(CW\*(C`array_datatypes\*(C'\fR and setting \f(CW\*(C`name_sep\*(C'\fR to \f(CW\*(C`.\*(C'\fR and \f(CW\*(C`quote_char\*(C'\fR to \f(CW\*(C`"\*(C'\fR. .PP .Vb 2 \& # Generate WHERE clause and bind values \& my($stmt, @bind) = $pg\->abstract\->where({foo => \*(Aqbar\*(Aq, baz => \*(Aqyada\*(Aq}); .Ve .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 \*(L"db\*(R" has been called for the first time. .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(CW1\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 as well as \f(CW\*(C`PrintWarn\*(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 "parent" .IX Subsection "parent" .Vb 2 \& my $parent = $pg\->parent; \& $pg = $pg\->parent(Mojo::Pg\->new); .Ve .PP Another Mojo::Pg object to use for connection management, instead of establishing and caching our own database connections. .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 4 \& # Subscribe to a channel \& $pg\->pubsub\->listen(news => sub ($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" (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. .PP .Vb 2 \& # Add up all the money \& say $pg\->db\->select(\*(Aqaccounts\*(Aq)\->hashes\->reduce(sub { $a\->{money} + $b\->{money} }); .Ve .SS "from_string" .IX Subsection "from_string" .Vb 2 \& $pg = $pg\->from_string(\*(Aqpostgresql://postgres@/test\*(Aq); \& $pg = $pg\->from_string(Mojo::Pg\->new); .Ve .PP Parse configuration from connection string or use another Mojo::Pg object as \*(L"parent\*(R". .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); \& \& # Username, database, an option and search_path \& $pg\->from_string(\*(Aqpostgres://sri@/db6?&PrintError=1&search_path=test_schema\*(Aq); .Ve .SS "new" .IX Subsection "new" .Vb 3 \& my $pg = Mojo::Pg\->new; \& my $pg = Mojo::Pg\->new(\*(Aqpostgresql://postgres@/test\*(Aq); \& my $pg = Mojo::Pg\->new(Mojo::Pg\->new); .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 .SS "reset" .IX Subsection "reset" .Vb 1 \& $pg = $pg\->reset; .Ve .PP Reset connection cache. .SH "DEBUGGING" .IX Header "DEBUGGING" You can set the \f(CW\*(C`DBI_TRACE\*(C'\fR environment variable to get some advanced diagnostics information printed by \s-1DBI\s0. .PP .Vb 3 \& DBI_TRACE=1 \& DBI_TRACE=15 \& DBI_TRACE=SQL .Ve .SH "API" .IX Header "API" 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 .IP "\(bu" 2 SQL::Abstract::Pg .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 Christopher Eveland .Sp Dan Book .Sp Flavio Poletti .Sp Hernan Lopes .Sp Joel Berger .Sp Matt S Trout .Sp Peter Rabbitson .Sp William Lindley .RE .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" Copyright (C) 2014\-2021, 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, .