1Mojo::Pg::Database(3) User Contributed Perl DocumentationMojo::Pg::Database(3)
2
3
4
6 Mojo::Pg::Database - Database
7
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
16 Mojo::Pg::Database is a container for DBD::Pg database handles used by
17 Mojo::Pg.
18
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
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
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 ('bar') on conflict do nothing"
175 $db->insert('some_table', {foo => 'bar'}, {on_conflict => undef});
176
177 Including operations commonly referred to as "upsert".
178
179 # "insert into t (a) values ('b') on conflict (a) do update set a = 'c'"
180 $db->insert('t', {a => 'b'}, {on_conflict => [a => {a => 'c'}]});
181
182 # "insert into t (a, b) values ('c', 'd')
183 # on conflict (a, b) do update set a = 'e'"
184 $db->insert(
185 't', {a => 'c', b => 'd'}, {on_conflict => [['a', 'b'] => {a => 'e'}]});
186
187 insert_p
188 my $promise = $db->insert_p($table, \@values || \%fieldvals, \%options);
189
190 Same as "insert", but performs all operations non-blocking and returns
191 a Mojo::Promise object instead of accepting a callback.
192
193 $db->insert_p(some_table => {foo => 'bar'})->then(sub {
194 my $results = shift;
195 ...
196 })->catch(sub {
197 my $err = shift;
198 ...
199 })->wait;
200
201 is_listening
202 my $bool = $db->is_listening;
203
204 Check if "dbh" is listening for notifications.
205
206 listen
207 $db = $db->listen('foo');
208
209 Subscribe to a channel and receive "notification" events when the
210 Mojo::IOLoop event loop is running.
211
212 notify
213 $db = $db->notify('foo');
214 $db = $db->notify(foo => 'bar');
215
216 Notify a channel.
217
218 pid
219 my $pid = $db->pid;
220
221 Return the process id of the backend server process.
222
223 ping
224 my $bool = $db->ping;
225
226 Check database connection.
227
228 query
229 my $results = $db->query('select * from foo');
230 my $results = $db->query('insert into foo values (?, ?, ?)', @values);
231 my $results = $db->query('select ?::json as foo', {json => {bar => 'baz'}});
232
233 Execute a blocking SQL
234 <http://www.postgresql.org/docs/current/static/sql.html> statement and
235 return a results object based on "results_class" (which is usually
236 Mojo::Pg::Results) with the query results. The DBD::Pg statement handle
237 will be automatically reused when it is not active anymore, to increase
238 the performance of future queries. You can also append a callback to
239 perform operations non-blocking.
240
241 $db->query('insert into foo values (?, ?, ?)' => @values => sub {
242 my ($db, $err, $results) = @_;
243 ...
244 });
245 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
246
247 Hash reference arguments containing a value named "json", will be
248 encoded to JSON text with "to_json" in Mojo::JSON. To accomplish the
249 reverse, you can use the method "expand" in Mojo::Pg::Results, which
250 automatically decodes all fields of the types "json" and "jsonb" with
251 "from_json" in Mojo::JSON to Perl values.
252
253 # "I ♥ Mojolicious!"
254 $db->query('select ?::jsonb as foo', {json => {bar => 'I ♥ Mojolicious!'}})
255 ->expand->hash->{foo}{bar};
256
257 Hash reference arguments containing values named "type" and "value",
258 can be used to bind specific DBD::Pg data types to placeholders.
259
260 # Insert binary data
261 use DBD::Pg ':pg_types';
262 $db->query('insert into bar values (?)', {type => PG_BYTEA, value => $bytes});
263
264 query_p
265 my $promise = $db->query_p('select * from foo');
266
267 Same as "query", but performs all operations non-blocking and returns a
268 Mojo::Promise object instead of accepting a callback.
269
270 $db->query_p('insert into foo values (?, ?, ?)' => @values)->then(sub {
271 my $results = shift;
272 ...
273 })->catch(sub {
274 my $err = shift;
275 ...
276 })->wait;
277
278 select
279 my $results = $db->select($source, $fields, $where, \%options);
280
281 Generate a "SELECT" statement with "abstract" in Mojo::Pg (usually an
282 SQL::Abstract::Pg object) and execute it with "query". You can also
283 append a callback to perform operations non-blocking.
284
285 $db->select(some_table => ['foo'] => {bar => 'yada'} => sub {
286 my ($db, $err, $results) = @_;
287 ...
288 });
289 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
290
291 Use all the same argument variations you would pass to the "select"
292 method of SQL::Abstract.
293
294 # "select * from some_table"
295 $db->select('some_table');
296
297 # "select id, foo from some_table"
298 $db->select('some_table', ['id', 'foo']);
299
300 # "select * from some_table where foo = 'bar'"
301 $db->select('some_table', undef, {foo => 'bar'});
302
303 # "select * from some_table where foo like '%test%'"
304 $db->select('some_table', undef, {foo => {-like => '%test%'}});
305
306 As well as some PostgreSQL specific extensions added by
307 SQL::Abstract::Pg.
308
309 # "select * from foo join bar on (bar.foo_id = foo.id)"
310 $db->select(['foo', ['bar', foo_id => 'id']]);
311
312 # "select * from foo left join bar on (bar.foo_id = foo.id)"
313 $db->select(['foo', [-left => 'bar', foo_id => 'id']]);
314
315 # "select foo as bar from some_table"
316 $db->select('some_table', [[foo => 'bar']]);
317
318 # "select * from some_table where foo = '[1,2,3]'"
319 $db->select('some_table', '*', {foo => {'=' => {-json => [1, 2, 3]}}});
320
321 # "select extract(epoch from foo) as foo, bar from some_table"
322 $db->select('some_table', [\'extract(epoch from foo) as foo', 'bar']);
323
324 # "select 'test' as foo, bar from some_table"
325 $db->select('some_table', [\['? as foo', 'test'], 'bar']);
326
327 Including a new last argument to pass many new options.
328
329 # "select * from some_table where foo = 'bar' order by id desc"
330 $db->select('some_table', '*', {foo => 'bar'}, {order_by => {-desc => 'id'}});
331
332 # "select * from some_table limit 10 offset 20"
333 $db->select('some_table', '*', undef, {limit => 10, offset => 20});
334
335 # "select * from some_table where foo = 23 group by foo, bar"
336 $db->select('some_table', '*', {foo => 23}, {group_by => ['foo', 'bar']});
337
338 # "select * from t where a = 'b' group by c having d = 'e'"
339 $db->select('t', '*', {a => 'b'}, {group_by => ['c'], having => {d => 'e'}});
340
341 # "select * from some_table where id = 1 for update"
342 $db->select('some_table', '*', {id => 1}, {for => 'update'});
343
344 # "select * from some_table where id = 1 for update skip locked"
345 $db->select('some_table', '*', {id => 1}, {for => \'update skip locked'});
346
347 select_p
348 my $promise = $db->select_p($source, $fields, $where, \%options);
349
350 Same as "select", but performs all operations non-blocking and returns
351 a Mojo::Promise object instead of accepting a callback.
352
353 $db->select_p(some_table => ['foo'] => {bar => 'yada'})->then(sub {
354 my $results = shift;
355 ...
356 })->catch(sub {
357 my $err = shift;
358 ...
359 })->wait;
360
361 tables
362 my $tables = $db->tables;
363
364 Return table and view names for this database, that are visible to the
365 current user and not internal, as an array reference.
366
367 # Names of all tables
368 say for @{$db->tables};
369
370 unlisten
371 $db = $db->unlisten('foo');
372 $db = $db->unlisten('*');
373
374 Unsubscribe from a channel, "*" can be used to unsubscribe from all
375 channels.
376
377 update
378 my $results = $db->update($table, \%fieldvals, \%where, \%options);
379
380 Generate an "UPDATE" statement with "abstract" in Mojo::Pg (usually an
381 SQL::Abstract::Pg object) and execute it with "query". You can also
382 append a callback to perform operations non-blocking.
383
384 $db->update(some_table => {foo => 'baz'} => {foo => 'bar'} => sub {
385 my ($db, $err, $results) = @_;
386 ...
387 });
388 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
389
390 Use all the same argument variations you would pass to the "update"
391 method of SQL::Abstract.
392
393 # "update some_table set foo = 'bar' where id = 23"
394 $db->update('some_table', {foo => 'bar'}, {id => 23});
395
396 # "update some_table set foo = {1,2,3} where id = 23"
397 $db->update('some_table', {foo => [1, 2, 3]}, {id => 23});
398
399 # "update some_table set foo = 'bar' where foo like '%test%'"
400 $db->update('some_table', {foo => 'bar'}, {foo => {-like => '%test%'}});
401
402 # "update some_table set foo = 'bar' where id = 23 returning id"
403 $db->update('some_table', {foo => 'bar'}, {id => 23}, {returning => 'id'});
404
405 # "update some_table set foo = '[1,2,3]' where bar = 23"
406 $db->update('some_table', {foo => {-json => [1, 2, 3]}}, {bar => 23});
407
408 update_p
409 my $promise = $db->update_p($table, \%fieldvals, \%where, \%options);
410
411 Same as "update", but performs all operations non-blocking and returns
412 a Mojo::Promise object instead of accepting a callback.
413
414 $db->update_p(some_table => {foo => 'baz'} => {foo => 'bar'})->then(sub {
415 my $results = shift;
416 ...
417 })->catch(sub {
418 my $err = shift;
419 ...
420 })->wait;
421
423 Mojo::Pg, Mojolicious::Guides, <https://mojolicious.org>.
424
425
426
427perl v5.30.0 2019-07-28 Mojo::Pg::Database(3)