Pg.pm

filter: Statementstmt 83.3% 10 / 12 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 87.5% 14 / 16 CC 1 SCAR 0.7
CC
1
Cov
83%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Pg/Database.pm ↑ Summary
1 package Mojo::Pg;
2 6 ▶use Mojo::Base 'Mojo::EventEmitter';
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 6 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 6 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 0 ▶use Mojo::Pg::Database;
Subroutine BEGIN: called CC=1 SCAR=2.6
7 use Mojo::Pg::Migrations;
8 use Mojo::Pg::PubSub;
9 use Mojo::URL;
10 use Scalar::Util qw(blessed);
11 use SQL::Abstract::Pg;
12  
13 has abstract => sub { SQL::Abstract::Pg->new(array_datatypes => 1, name_sep => '.', quote_char => '"') };
14 has [qw(auto_migrate parent search_path)];
15 has database_class => 'Mojo::Pg::Database';
16 has dsn => 'dbi:Pg:';
17 has max_connections => 1;
18 has migrations => sub { Mojo::Pg::Migrations->new(pg => shift) };
19 has options => sub {
20 {AutoCommit => 1, AutoInactiveDestroy => 1, PrintError => 0, PrintWarn => 0, RaiseError => 1};
21 };
22 has [qw(password username)] => '';
23 has pubsub => sub { Mojo::Pg::PubSub->new(pg => shift) };
24  
25 our $VERSION = '5.01';
26  
27 sub db { $_[0]->database_class->new(dbh => $_[0]->_prepare, pg => $_[0]) }
28  
29 sub from_string {
30 my ($self, $str) = @_;
31  
32 # Parent
33 return $self unless $str;
34 return $self->parent($str) if blessed $str && $str->isa('Mojo::Pg');
35  
36 # Protocol
37 my $url = Mojo::URL->new($str);
38 croak qq{Invalid PostgreSQL connection string "$str"} unless $url->protocol =~ /^postgres(?:ql)?$/;
39  
40 # Connection information
41 my $db = $url->path->parts->[0];
42 my $dsn = defined $db ? "dbi:Pg:dbname=$db" : 'dbi:Pg:';
43 if (my $host = $url->host) { $dsn .= ";host=$host" }
44 if (my $port = $url->port) { $dsn .= ";port=$port" }
45 if (defined(my $username = $url->username)) { $self->username($username) }
46 if (defined(my $password = $url->password)) { $self->password($password) }
47  
48 # Service and search_path
49 my $hash = $url->query->to_hash;
50 if (my $service = delete $hash->{service}) { $dsn .= "service=$service" }
51 if (my $path = delete $hash->{search_path}) {
52 $self->search_path(ref $path ? $path : [$path]);
53 }
54  
55 # Options
56 @{$self->options}{keys %$hash} = values %$hash;
57  
58 return $self->dsn($dsn);
59 }
60  
61 sub new { @_ > 1 ? shift->SUPER::new->from_string(@_) : shift->SUPER::new }
62  
63 sub reset { ($_[0]->{queue} = []) and return $_[0] }
64  
65 sub _dequeue {
66 my $self = shift;
67  
68 # Fork-safety
69 delete @$self{qw(pid queue)} if $self->{pid} && $self->{pid} ne $$;
70 $self->{pid} //= $$;
71  
72 while (my $dbh = shift @{$self->{queue} || []}) { return $dbh if $dbh->ping }
73 my $dbh = DBI->connect(map { $self->$_ } qw(dsn username password options));
74  
75 # Search path
76 if (my $path = $self->search_path) {
77 my $search_path = join ', ', map { $dbh->quote_identifier($_) } @$path;
78 $dbh->do("SET search_path TO $search_path");
79 }
80  
81 $self->emit(connection => $dbh);
82  
83 return $dbh;
84 }
85  
86 sub _enqueue {
87 my ($self, $dbh) = @_;
88  
89 if (my $parent = $self->parent) { return $parent->_enqueue($dbh) }
90  
91 my $queue = $self->{queue} ||= [];
92 push @$queue, $dbh if $dbh->{Active};
93 shift @$queue while @$queue > $self->max_connections;
94 }
95  
96 sub _prepare {
97 my $self = shift;
98  
99 # Automatic migrations
100 ++$self->{migrated} and $self->migrations->migrate if !$self->{migrated} && $self->auto_migrate;
101  
102 my $parent = $self->parent;
103 return $parent ? $parent->_prepare : $self->_dequeue;
104 }
105  
106 1;
107  
108 =encoding utf8
109  
110 =head1 NAME
111  
112 Mojo::Pg - Mojolicious ♥ PostgreSQL
113  
114 =head1 SYNOPSIS
115  
116 use Mojo::Pg;
117  
118 # Use a PostgreSQL connection string for configuration
119 my $pg = Mojo::Pg->new('postgresql://postgres@/test');
120  
121 # Select the server version
122 say $pg->db->query('SELECT VERSION() AS version')->hash->{version};
123  
124 # Use migrations to create a table
125 $pg->migrations->name('my_names_app')->from_string(<<EOF)->migrate;
126 -- 1 up
127 CREATE TABLE names (id SERIAL PRIMARY KEY, name TEXT);
128 -- 1 down
129 DROP TABLE names;
130 EOF
131  
132 # Use migrations to drop and recreate the table
133 $pg->migrations->migrate(0)->migrate;
134  
135 # Get a database handle from the cache for multiple queries
136 my $db = $pg->db;
137  
138 # Use SQL::Abstract to generate simple CRUD queries for you
139 $db->insert('names', {name => 'Isabell'});
140 my $id = $db->select('names', ['id'], {name => 'Isabell'})->hash->{id};
141 $db->update('names', {name => 'Belle'}, {id => $id});
142 $db->delete('names', {name => 'Belle'});
143  
144 # Insert a few rows in a transaction with SQL and placeholders
145 eval {
146 my $tx = $db->begin;
147 $db->query('INSERT INTO names (name) VALUES (?)', 'Sara');
148 $db->query('INSERT INTO names (name) VALUES (?)', 'Stefan');
149 $tx->commit;
150 };
151 say $@ if $@;
152  
153 # Insert another row with SQL::Abstract and return the generated id
154 say $db->insert('names', {name => 'Daniel'}, {returning => 'id'})->hash->{id};
155  
156 # JSON roundtrip
157 say $db->query('SELECT ?::JSON AS foo', {json => {bar => 'baz'}})
158 ->expand->hash->{foo}{bar};
159  
160 # Select all rows blocking with SQL::Abstract
161 say $_->{name} for $db->select('names')->hashes->each;
162  
163 # Select all rows non-blocking with SQL::Abstract
164 $db->select('names' => sub ($db, $err, $results) {
165 die $err if $err;
166 say $_->{name} for $results->hashes->each;
167 });
168 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
169  
170 # Concurrent non-blocking queries (synchronized with promises)
171 my $now = $pg->db->query_p('SELECT NOW() AS now');
172 my $names = $pg->db->query_p('SELECT * FROM names');
173 Mojo::Promise->all($now, $names)->then(sub ($now, $names) {
174 say $now->[0]->hash->{now};
175 say $_->{name} for $names->[0]->hashes->each;
176 })->catch(sub ($err) {
177 warn "Something went wrong: $err";
178 })->wait;
179  
180 # Send and receive notifications non-blocking
181 $pg->pubsub->listen(foo => sub ($pubsub, $payload) {
182 say "foo: $payload";
183 $pubsub->notify(bar => $payload);
184 });
185 $pg->pubsub->listen(bar => sub ($pubsub, $payload) {
186 say "bar: $payload";
187 });
188 $pg->pubsub->notify(foo => 'PostgreSQL rocks!');
189 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
190  
191 =head1 DESCRIPTION
192  
193 L<Mojo::Pg> is a tiny wrapper around L<DBD::Pg> that makes L<PostgreSQL|http://www.postgresql.org> a lot of fun to use
194 with the L<Mojolicious|https://mojolicious.org> real-time web framework. Perform queries blocking and non-blocking, use
195 all L<SQL features|https://www.postgresql.org/docs/current/static/sql.html> PostgreSQL has to offer, generate CRUD
196 queries from data structures, manage your database schema with migrations and build scalable real-time web applications
197 with the publish/subscribe pattern.
198  
199 =head1 BASICS
200  
201 Database and statement handles are cached automatically, and will be reused transparently to increase performance. You
202 can handle connection timeouts gracefully by holding on to them only for short amounts of time.
203  
204 use Mojolicious::Lite -signatures;
205 use Mojo::Pg;
206  
207 helper pg => sub { state $pg = Mojo::Pg->new('postgresql://postgres@/test') };
208  
209 get '/' => sub ($c) {
210 my $db = $c->pg->db;
211 $c->render(json => $db->query('SELECT NOW() AS now')->hash);
212 };
213  
214 app->start;
215  
216 In this example application, we create a C<pg> helper to store a L<Mojo::Pg> object. Our action calls that helper and
217 uses the method L<Mojo::Pg/"db"> to dequeue a L<Mojo::Pg::Database> object from the connection pool. Then we use the
218 method L<Mojo::Pg::Database/"query"> to execute an L<SQL|http://www.postgresql.org/docs/current/static/sql.html>
219 statement, which returns a L<Mojo::Pg::Results> object. And finally we call the method L<Mojo::Pg::Results/"hash"> to
220 retrieve the first row as a hash reference.
221  
222 While all I/O operations are performed blocking, you can wait for long running queries asynchronously, allowing the
223 L<Mojo::IOLoop> event loop to perform other tasks in the meantime. Since database connections usually have a very low
224 latency, this often results in very good performance.
225  
226 Every database connection can only handle one active query at a time, this includes asynchronous ones. To perform
227 multiple queries concurrently, you have to use multiple connections.
228  
229 # Performed concurrently (5 seconds)
230 $pg->db->query('SELECT PG_SLEEP(5)' => sub ($db, $err, $results) {...});
231 $pg->db->query('SELECT PG_SLEEP(5)' => sub ($db, $err, $results) {...});
232  
233 All cached database handles will be reset automatically if a new process has been forked, this allows multiple
234 processes to share the same L<Mojo::Pg> object safely.
235  
236 =head1 GROWING
237  
238 And as your application grows, you can move queries into model classes.
239  
240 package MyApp::Model::Time;
241 use Mojo::Base -base, -signatures;
242  
243 has 'pg';
244  
245 sub now ($self) {
246 return $self->pg->db->query('SELECT NOW() AS now')->hash;
247 }
248  
249 1;
250  
251 Which get integrated into your application with helpers.
252  
253 use Mojolicious::Lite -signatures;
254 use Mojo::Pg;
255 use MyApp::Model::Time;
256  
257 helper pg => sub { state $pg = Mojo::Pg->new('postgresql://postgres@/test') };
258 helper time => sub { state $time = MyApp::Model::Time->new(pg => shift->pg) };
259  
260 get '/' => sub ($c) {
261 $c->render(json => $c->time->now);
262 };
263  
264 app->start;
265  
266 =head1 EXAMPLES
267  
268 This distribution also contains two great L<example
269 applications|https://github.com/mojolicious/mojo-pg/tree/main/examples/> you can use for inspiration. The minimal
270 L<chat|https://github.com/mojolicious/mojo-pg/tree/main/examples/chat.pl> application will show you how to scale
271 WebSockets to multiple servers, and the well-structured
272 L<blog|https://github.com/mojolicious/mojo-pg/tree/main/examples/blog> application how to apply the MVC design pattern
273 in practice.
274  
275 =head1 EVENTS
276  
277 L<Mojo::Pg> inherits all events from L<Mojo::EventEmitter> and can emit the following new ones.
278  
279 =head2 connection
280  
281 $pg->on(connection => sub ($pg, $dbh) {
282 ...
283 });
284  
285 Emitted when a new database connection has been established.
286  
287 $pg->on(connection => sub ($pg, $dbh) {
288 $dbh->do('SET search_path TO my_schema');
289 });
290  
291 =head1 ATTRIBUTES
292  
293 L<Mojo::Pg> implements the following attributes.
294  
295 =head2 abstract
296  
297 my $abstract = $pg->abstract;
298 $pg = $pg->abstract(SQL::Abstract::Pg->new);
299  
300 L<SQL::Abstract::Pg> object used to generate CRUD queries for L<Mojo::Pg::Database>, defaults to enabling
301 C<array_datatypes> and setting C<name_sep> to C<.> and C<quote_char> to C<">.
302  
303 # Generate WHERE clause and bind values
304 my($stmt, @bind) = $pg->abstract->where({foo => 'bar', baz => 'yada'});
305  
306 =head2 auto_migrate
307  
308 my $bool = $pg->auto_migrate;
309 $pg = $pg->auto_migrate($bool);
310  
311 Automatically migrate to the latest database schema with L</"migrations">, as soon as L</"db"> has been called for the
312 first time.
313  
314 =head2 database_class
315  
316 my $class = $pg->database_class;
317 $pg = $pg->database_class('MyApp::Database');
318  
319 Class to be used by L</"db">, defaults to L<Mojo::Pg::Database>. Note that this class needs to have already been loaded
320 before L</"db"> is called.
321  
322 =head2 dsn
323  
324 my $dsn = $pg->dsn;
325 $pg = $pg->dsn('dbi:Pg:dbname=foo');
326  
327 Data source name, defaults to C<dbi:Pg:>.
328  
329 =head2 max_connections
330  
331 my $max = $pg->max_connections;
332 $pg = $pg->max_connections(3);
333  
334 Maximum number of idle database handles to cache for future use, defaults to C<1>.
335  
336 =head2 migrations
337  
338 my $migrations = $pg->migrations;
339 $pg = $pg->migrations(Mojo::Pg::Migrations->new);
340  
341 L<Mojo::Pg::Migrations> object you can use to change your database schema more easily.
342  
343 # Load migrations from file and migrate to latest version
344 $pg->migrations->from_file('/home/sri/migrations.sql')->migrate;
345  
346 =head2 options
347  
348 my $options = $pg->options;
349 $pg = $pg->options({AutoCommit => 1, RaiseError => 1});
350  
351 Options for database handles, defaults to activating C<AutoCommit>, C<AutoInactiveDestroy> as well as C<RaiseError> and
352 deactivating C<PrintError> as well as C<PrintWarn>. Note that C<AutoCommit> and C<RaiseError> are considered mandatory,
353 so deactivating them would be very dangerous.
354  
355 =head2 parent
356  
357 my $parent = $pg->parent;
358 $pg = $pg->parent(Mojo::Pg->new);
359  
360 Another L<Mojo::Pg> object to use for connection management, instead of establishing and caching our own database
361 connections.
362  
363 =head2 password
364  
365 my $password = $pg->password;
366 $pg = $pg->password('s3cret');
367  
368 Database password, defaults to an empty string.
369  
370 =head2 pubsub
371  
372 my $pubsub = $pg->pubsub;
373 $pg = $pg->pubsub(Mojo::Pg::PubSub->new);
374  
375 L<Mojo::Pg::PubSub> object you can use to send and receive notifications very efficiently, by sharing a single database
376 connection with many consumers.
377  
378 # Subscribe to a channel
379 $pg->pubsub->listen(news => sub ($pubsub, $payload) {
380 say "Received: $payload";
381 });
382  
383 # Notify a channel
384 $pg->pubsub->notify(news => 'PostgreSQL rocks!');
385  
386 =head2 search_path
387  
388 my $path = $pg->search_path;
389 $pg = $pg->search_path(['$user', 'foo', 'public']);
390  
391 Schema search path assigned to all new connections.
392  
393 # Isolate tests and avoid race conditions when running them in parallel
394 my $pg = Mojo::Pg->new('postgresql:///test')->search_path(['test_one']);
395 $pg->db->query('DROP SCHEMA IF EXISTS test_one CASCADE');
396 $pg->db->query('CREATE SCHEMA test_one');
397 ...
398 $pg->db->query('DROP SCHEMA test_one CASCADE');
399  
400 =head2 username
401  
402 my $username = $pg->username;
403 $pg = $pg->username('sri');
404  
405 Database username, defaults to an empty string.
406  
407 =head1 METHODS
408  
409 L<Mojo::Pg> inherits all methods from L<Mojo::EventEmitter> and implements the following new ones.
410  
411 =head2 db
412  
413 my $db = $pg->db;
414  
415 Get a database object based on L</"database_class"> (which is usually L<Mojo::Pg::Database>) for a cached or newly
416 established database connection. The L<DBD::Pg> database handle will be automatically cached again when that object is
417 destroyed, so you can handle problems like connection timeouts gracefully by holding on to it only for short amounts of
418 time.
419  
420 # Add up all the money
421 say $pg->db->select('accounts')->hashes->reduce(sub { $a->{money} + $b->{money} });
422  
423 =head2 from_string
424  
425 $pg = $pg->from_string('postgresql://postgres@/test');
426 $pg = $pg->from_string(Mojo::Pg->new);
427  
428 Parse configuration from connection string or use another L<Mojo::Pg> object as L</"parent">.
429  
430 # Just a database
431 $pg->from_string('postgresql:///db1');
432  
433 # Just a service
434 $pg->from_string('postgresql://?service=foo');
435  
436 # Username and database
437 $pg->from_string('postgresql://sri@/db2');
438  
439 # Short scheme, username, password, host and database
440 $pg->from_string('postgres://sri:s3cret@localhost/db3');
441  
442 # Username, domain socket and database
443 $pg->from_string('postgresql://sri@%2ftmp%2fpg.sock/db4');
444  
445 # Username, database and additional options
446 $pg->from_string('postgresql://sri@/db5?PrintError=1&pg_server_prepare=0');
447  
448 # Service and additional options
449 $pg->from_string('postgresql://?service=foo&PrintError=1&RaiseError=0');
450  
451 # Username, database, an option and search_path
452 $pg->from_string('postgres://sri@/db6?&PrintError=1&search_path=test_schema');
453  
454 =head2 new
455  
456 my $pg = Mojo::Pg->new;
457 my $pg = Mojo::Pg->new('postgresql://postgres@/test');
458 my $pg = Mojo::Pg->new(Mojo::Pg->new);
459  
460 Construct a new L<Mojo::Pg> object and parse connection string with L</"from_string"> if necessary.
461  
462 # Customize configuration further
463 my $pg = Mojo::Pg->new->dsn('dbi:Pg:service=foo');
464  
465 =head2 reset
466  
467 $pg = $pg->reset;
468  
469 Reset connection cache.
470  
471 =head1 DEBUGGING
472  
473 You can set the C<DBI_TRACE> environment variable to get some advanced diagnostics information printed by L<DBI>.
474  
475 DBI_TRACE=1
476 DBI_TRACE=15
477 DBI_TRACE=SQL
478  
479 =head1 API
480  
481 This is the class hierarchy of the L<Mojo::Pg> distribution.
482  
483 =over 2
484  
485 =item * L<Mojo::Pg>
486  
487 =item * L<Mojo::Pg::Database>
488  
489 =item * L<Mojo::Pg::Migrations>
490  
491 =item * L<Mojo::Pg::PubSub>
492  
493 =item * L<Mojo::Pg::Results>
494  
495 =item * L<Mojo::Pg::Transaction>
496  
497 =back
498  
499 =head1 AUTHOR
500  
501 Sebastian Riedel, C<sri@cpan.org>.
502  
503 =head1 CREDITS
504  
505 In alphabetical order:
506  
507 =over 2
508  
509 Brett Watson
510  
511 Christopher Eveland
512  
513 Dan Book
514  
515 Flavio Poletti
516  
517 Hernan Lopes
518  
519 Joel Berger
520  
521 Matt S Trout
522  
523 Peter Rabbitson
524  
525 William Lindley
526  
527 =back
528  
529 =head1 COPYRIGHT AND LICENSE
530  
531 Copyright (C) 2014-2026, Sebastian Riedel and others.
532  
533 This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version
534 2.0.
535  
536 =head1 SEE ALSO
537  
538 L<https://github.com/mojolicious/mojo-pg>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
539  
540 =cut
« Pg/Database.pm ↑ Summary