1Mojo::Pg::Database(3) User Contributed Perl DocumentationMojo::Pg::Database(3)
2
3
4

NAME

6       Mojo::Pg::Database - Database
7

SYNOPSIS

9         use Mojo::Pg::Database;
10
11         my $db = Mojo::Pg::Database->new(pg => $pg, dbh => $dbh);
12         $db->query('select * from foo')
13           ->hashes->map(sub { $_->{bar} })->join("\n")->say;
14

DESCRIPTION

16       Mojo::Pg::Database is a container for DBD::Pg database handles used by
17       Mojo::Pg.
18

EVENTS

20       Mojo::Pg::Database inherits all events from Mojo::EventEmitter and can
21       emit the following new ones.
22
23   close
24         $db->on(close => sub {
25           my $db = shift;
26           ...
27         });
28
29       Emitted when the database connection gets closed while waiting for
30       notifications.
31
32   notification
33         $db->on(notification => sub {
34           my ($db, $name, $pid, $payload) = @_;
35           ...
36         });
37
38       Emitted when a notification has been received.
39

ATTRIBUTES

41       Mojo::Pg::Database implements the following attributes.
42
43   dbh
44         my $dbh = $db->dbh;
45         $db     = $db->dbh($dbh);
46
47       DBD::Pg database handle used for all queries.
48
49         # Use DBI utility methods
50         my $quoted = $db->dbh->quote_identifier('foo.bar');
51
52   pg
53         my $pg = $db->pg;
54         $db    = $db->pg(Mojo::Pg->new);
55
56       Mojo::Pg object this database belongs to. Note that this attribute is
57       weakened.
58
59   results_class
60         my $class = $db->results_class;
61         $db       = $db->results_class('MyApp::Results');
62
63       Class to be used by "query", defaults to Mojo::Pg::Results. Note that
64       this class needs to have already been loaded before "query" is called.
65

METHODS

67       Mojo::Pg::Database inherits all methods from Mojo::EventEmitter and
68       implements the following new ones.
69
70   begin
71         my $tx = $db->begin;
72
73       Begin transaction and return Mojo::Pg::Transaction object, which will
74       automatically roll back the transaction unless "commit" in
75       Mojo::Pg::Transaction has been called before it is destroyed.
76
77         # Insert rows in a transaction
78         eval {
79           my $tx = $db->begin;
80           $db->insert('frameworks', {name => 'Catalyst'});
81           $db->insert('frameworks', {name => 'Mojolicious'});
82           $tx->commit;
83         };
84         say $@ if $@;
85
86   delete
87         my $results = $db->delete($table, \%where, \%options);
88
89       Generate a "DELETE" statement with "abstract" in Mojo::Pg (usually an
90       SQL::Abstract::Pg object) and execute it with "query". You can also
91       append a callback to perform operations non-blocking.
92
93         $db->delete(some_table => sub {
94           my ($db, $err, $results) = @_;
95           ...
96         });
97         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
98
99       Use all the same argument variations you would pass to the "delete"
100       method of SQL::Abstract.
101
102         # "delete from some_table"
103         $db->delete('some_table');
104
105         # "delete from some_table where foo = 'bar'"
106         $db->delete('some_table', {foo => 'bar'});
107
108         # "delete from some_table where foo like '%test%'"
109         $db->delete('some_table', {foo => {-like => '%test%'}});
110
111         # "delete from some_table where foo = 'bar' returning id"
112         $db->delete('some_table', {foo => 'bar'}, {returning => 'id'});
113
114   delete_p
115         my $promise = $db->delete_p($table, \%where, \%options);
116
117       Same as "delete", but performs all operations non-blocking and returns
118       a Mojo::Promise object instead of accepting a callback.
119
120         $db->delete_p('some_table')->then(sub {
121           my $results = shift;
122           ...
123         })->catch(sub {
124           my $err = shift;
125           ...
126         })->wait;
127
128   disconnect
129         $db->disconnect;
130
131       Disconnect "dbh" and prevent it from getting reused.
132
133   dollar_only
134         $db = $db->dollar_only;
135
136       Activate "pg_placeholder_dollaronly" for next "query" call and allow
137       "?"  to be used as an operator.
138
139         # Check for a key in a JSON document
140         $db->dollar_only->query('select * from foo where bar ? $1', 'baz')
141           ->expand->hashes->map(sub { $_->{bar}{baz} })->join("\n")->say;
142
143   insert
144         my $results = $db->insert($table, \@values || \%fieldvals, \%options);
145
146       Generate an "INSERT" statement with "abstract" in Mojo::Pg (usually an
147       SQL::Abstract::Pg object) and execute it with "query". You can also
148       append a callback to perform operations non-blocking.
149
150         $db->insert(some_table => {foo => 'bar'} => sub {
151           my ($db, $err, $results) = @_;
152           ...
153         });
154         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
155
156       Use all the same argument variations you would pass to the "insert"
157       method of SQL::Abstract.
158
159         # "insert into some_table (foo, baz) values ('bar', 'yada')"
160         $db->insert('some_table', {foo => 'bar', baz => 'yada'});
161
162         # "insert into some_table (foo) values ({1,2,3})"
163         $db->insert('some_table', {foo => [1, 2, 3]});
164
165         # "insert into some_table (foo) values ('bar') returning id"
166         $db->insert('some_table', {foo => 'bar'}, {returning => 'id'});
167
168         # "insert into some_table (foo) values ('bar') returning id, foo"
169         $db->insert('some_table', {foo => 'bar'}, {returning => ['id', 'foo']});
170
171       As well as some PostgreSQL specific extensions added by
172       SQL::Abstract::Pg.
173
174         # "insert into some_table (foo) values ('{"test":23}')"
175         $db->insert('some_table', {foo => {-json => {test => 23}}});
176
177         # "insert into some_table (foo) values ('bar') on conflict do nothing"
178         $db->insert('some_table', {foo => 'bar'}, {on_conflict => undef});
179
180       Including operations commonly referred to as "upsert".
181
182         # "insert into t (a) values ('b') on conflict (a) do update set a = 'c'"
183         $db->insert('t', {a => 'b'}, {on_conflict => [a => {a => 'c'}]});
184
185         # "insert into t (a, b) values ('c', 'd')
186         #  on conflict (a, b) do update set a = 'e'"
187         $db->insert(
188           't', {a => 'c', b => 'd'}, {on_conflict => [['a', 'b'] => {a => 'e'}]});
189
190   insert_p
191         my $promise = $db->insert_p($table, \@values || \%fieldvals, \%options);
192
193       Same as "insert", but performs all operations non-blocking and returns
194       a Mojo::Promise object instead of accepting a callback.
195
196         $db->insert_p(some_table => {foo => 'bar'})->then(sub {
197           my $results = shift;
198           ...
199         })->catch(sub {
200           my $err = shift;
201           ...
202         })->wait;
203
204   is_listening
205         my $bool = $db->is_listening;
206
207       Check if "dbh" is listening for notifications.
208
209   listen
210         $db = $db->listen('foo');
211
212       Subscribe to a channel and receive "notification" events when the
213       Mojo::IOLoop event loop is running.
214
215   notify
216         $db = $db->notify('foo');
217         $db = $db->notify(foo => 'bar');
218
219       Notify a channel.
220
221   pid
222         my $pid = $db->pid;
223
224       Return the process id of the backend server process.
225
226   ping
227         my $bool = $db->ping;
228
229       Check database connection.
230
231   query
232         my $results = $db->query('select * from foo');
233         my $results = $db->query('insert into foo values (?, ?, ?)', @values);
234         my $results = $db->query('select ?::json as foo', {-json => {bar => 'baz'}});
235
236       Execute a blocking SQL
237       <http://www.postgresql.org/docs/current/static/sql.html> statement and
238       return a results object based on "results_class" (which is usually
239       Mojo::Pg::Results) with the query results. The DBD::Pg statement handle
240       will be automatically reused when it is not active anymore, to increase
241       the performance of future queries. You can also append a callback to
242       perform operations non-blocking.
243
244         $db->query('insert into foo values (?, ?, ?)' => @values => sub {
245           my ($db, $err, $results) = @_;
246           ...
247         });
248         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
249
250       Hash reference arguments containing a value named "-json" or "json"
251       will be encoded to JSON text with "to_json" in Mojo::JSON. To
252       accomplish the reverse, you can use the method "expand" in
253       Mojo::Pg::Results, which automatically decodes all fields of the types
254       "json" and "jsonb" with "from_json" in Mojo::JSON to Perl values.
255
256         # "I ♥ Mojolicious!"
257         $db->query('select ?::jsonb as foo', {-json => {bar => 'I ♥ Mojolicious!'}})
258           ->expand->hash->{foo}{bar};
259
260       Hash reference arguments containing values named "type" and "value" can
261       be used to bind specific DBD::Pg data types to placeholders.
262
263         # Insert binary data
264         use DBD::Pg ':pg_types';
265         $db->query('insert into bar values (?)', {type => PG_BYTEA, value => $bytes});
266
267   query_p
268         my $promise = $db->query_p('select * from foo');
269
270       Same as "query", but performs all operations non-blocking and returns a
271       Mojo::Promise object instead of accepting a callback.
272
273         $db->query_p('insert into foo values (?, ?, ?)' => @values)->then(sub {
274           my $results = shift;
275           ...
276         })->catch(sub {
277           my $err = shift;
278           ...
279         })->wait;
280
281   select
282         my $results = $db->select($source, $fields, $where, \%options);
283
284       Generate a "SELECT" statement with "abstract" in Mojo::Pg (usually an
285       SQL::Abstract::Pg object) and execute it with "query". You can also
286       append a callback to perform operations non-blocking.
287
288         $db->select(some_table => ['foo'] => {bar => 'yada'} => sub {
289           my ($db, $err, $results) = @_;
290           ...
291         });
292         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
293
294       Use all the same argument variations you would pass to the "select"
295       method of SQL::Abstract.
296
297         # "select * from some_table"
298         $db->select('some_table');
299
300         # "select id, foo from some_table"
301         $db->select('some_table', ['id', 'foo']);
302
303         # "select * from some_table where foo = 'bar'"
304         $db->select('some_table', undef, {foo => 'bar'});
305
306         # "select * from some_table where foo like '%test%'"
307         $db->select('some_table', undef, {foo => {-like => '%test%'}});
308
309       As well as some PostgreSQL specific extensions added by
310       SQL::Abstract::Pg.
311
312         # "select * from foo join bar on (bar.foo_id = foo.id)"
313         $db->select(['foo', ['bar', foo_id => 'id']]);
314
315         # "select * from foo left join bar on (bar.foo_id = foo.id)"
316         $db->select(['foo', [-left => 'bar', foo_id => 'id']]);
317
318         # "select foo as bar from some_table"
319         $db->select('some_table', [[foo => 'bar']]);
320
321         # "select * from some_table where foo = '[1,2,3]'"
322         $db->select('some_table', '*', {foo => {'=' => {-json => [1, 2, 3]}}});
323
324         # "select extract(epoch from foo) as foo, bar from some_table"
325         $db->select('some_table', [\'extract(epoch from foo) as foo', 'bar']);
326
327         # "select 'test' as foo, bar from some_table"
328         $db->select('some_table', [\['? as foo', 'test'], 'bar']);
329
330       Including a new last argument to pass many new options.
331
332         # "select * from some_table where foo = 'bar' order by id desc"
333         $db->select('some_table', '*', {foo => 'bar'}, {order_by => {-desc => 'id'}});
334
335         # "select * from some_table limit 10 offset 20"
336         $db->select('some_table', '*', undef, {limit => 10, offset => 20});
337
338         # "select * from some_table where foo = 23 group by foo, bar"
339         $db->select('some_table', '*', {foo => 23}, {group_by => ['foo', 'bar']});
340
341         # "select * from t where a = 'b' group by c having d = 'e'"
342         $db->select('t', '*', {a => 'b'}, {group_by => ['c'], having => {d => 'e'}});
343
344         # "select * from some_table where id = 1 for update"
345         $db->select('some_table', '*', {id => 1}, {for => 'update'});
346
347         # "select * from some_table where id = 1 for update skip locked"
348         $db->select('some_table', '*', {id => 1}, {for => \'update skip locked'});
349
350   select_p
351         my $promise = $db->select_p($source, $fields, $where, \%options);
352
353       Same as "select", but performs all operations non-blocking and returns
354       a Mojo::Promise object instead of accepting a callback.
355
356         $db->select_p(some_table => ['foo'] => {bar => 'yada'})->then(sub {
357           my $results = shift;
358           ...
359         })->catch(sub {
360           my $err = shift;
361           ...
362         })->wait;
363
364   tables
365         my $tables = $db->tables;
366
367       Return table and view names for this database, that are visible to the
368       current user and not internal, as an array reference.
369
370         # Names of all tables
371         say for @{$db->tables};
372
373   unlisten
374         $db = $db->unlisten('foo');
375         $db = $db->unlisten('*');
376
377       Unsubscribe from a channel, "*" can be used to unsubscribe from all
378       channels.
379
380   update
381         my $results = $db->update($table, \%fieldvals, \%where, \%options);
382
383       Generate an "UPDATE" statement with "abstract" in Mojo::Pg (usually an
384       SQL::Abstract::Pg object) and execute it with "query". You can also
385       append a callback to perform operations non-blocking.
386
387         $db->update(some_table => {foo => 'baz'} => {foo => 'bar'} => sub {
388           my ($db, $err, $results) = @_;
389           ...
390         });
391         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
392
393       Use all the same argument variations you would pass to the "update"
394       method of SQL::Abstract.
395
396         # "update some_table set foo = 'bar' where id = 23"
397         $db->update('some_table', {foo => 'bar'}, {id => 23});
398
399         # "update some_table set foo = {1,2,3} where id = 23"
400         $db->update('some_table', {foo => [1, 2, 3]}, {id => 23});
401
402         # "update some_table set foo = 'bar' where foo like '%test%'"
403         $db->update('some_table', {foo => 'bar'}, {foo => {-like => '%test%'}});
404
405         # "update some_table set foo = 'bar' where id = 23 returning id"
406         $db->update('some_table', {foo => 'bar'}, {id => 23}, {returning => 'id'});
407
408         # "update some_table set foo = '[1,2,3]' where bar = 23"
409         $db->update('some_table', {foo => {-json => [1, 2, 3]}}, {bar => 23});
410
411   update_p
412         my $promise = $db->update_p($table, \%fieldvals, \%where, \%options);
413
414       Same as "update", but performs all operations non-blocking and returns
415       a Mojo::Promise object instead of accepting a callback.
416
417         $db->update_p(some_table => {foo => 'baz'} => {foo => 'bar'})->then(sub {
418           my $results = shift;
419           ...
420         })->catch(sub {
421           my $err = shift;
422           ...
423         })->wait;
424

SEE ALSO

426       Mojo::Pg, Mojolicious::Guides, <https://mojolicious.org>.
427
428
429
430perl v5.30.1                      2020-02-02             Mojo::Pg::Database(3)
Impressum