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