| 1 | package Mojo::Pg::Database; | ||
| 2 | 6 | ▶ | use Mojo::Base 'Mojo::EventEmitter'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 3 | |||
| 4 | 6 | ▶ | use Carp qw(croak shortmess); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 0 | ▶ | use DBD::Pg qw(:async); |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 6 | use Mojo::IOLoop; | ||
| 7 | use Mojo::JSON qw(to_json); | ||
| 8 | use Mojo::Pg::Results; | ||
| 9 | use Mojo::Pg::Transaction; | ||
| 10 | use Mojo::Promise; | ||
| 11 | use Mojo::Util qw(monkey_patch); | ||
| 12 | use Scalar::Util qw(blessed); | ||
| 13 | |||
| 14 | has 'dbh'; | ||
| 15 | has pg => undef, weak => 1; | ||
| 16 | has results_class => 'Mojo::Pg::Results'; | ||
| 17 | |||
| 18 | for my $name (qw(delete insert select update)) { | ||
| 19 | monkey_patch __PACKAGE__, $name, sub { | ||
| 20 | my ($self, @cb) = (shift, ref $_[-1] eq 'CODE' ? pop : ()); | ||
| 21 | return $self->query($self->pg->abstract->$name(@_), @cb); | ||
| 22 | }; | ||
| 23 | monkey_patch __PACKAGE__, "${name}_p", sub { | ||
| 24 | my $self = shift; | ||
| 25 | return $self->query_p($self->pg->abstract->$name(@_)); | ||
| 26 | }; | ||
| 27 | } | ||
| 28 | |||
| 29 | sub DESTROY { | ||
| 30 | my $self = shift; | ||
| 31 | |||
| 32 | my $waiting = $self->{waiting}; | ||
| 33 | $waiting->{cb}($self, 'Premature connection close', undef) if $waiting->{cb}; | ||
| 34 | |||
| 35 | return unless (my $pg = $self->pg) && (my $dbh = $self->dbh); | ||
| 36 | $pg->_enqueue($dbh) unless $dbh->{private_mojo_no_reuse}; | ||
| 37 | } | ||
| 38 | |||
| 39 | sub begin { Mojo::Pg::Transaction->new(db => shift) } | ||
| 40 | |||
| 41 | sub disconnect { | ||
| 42 | my $self = shift; | ||
| 43 | $self->_unwatch; | ||
| 44 | $self->dbh->disconnect; | ||
| 45 | } | ||
| 46 | |||
| 47 | sub dollar_only { ++$_[0]{dollar_only} and return $_[0] } | ||
| 48 | |||
| 49 | sub is_listening { !!keys %{shift->{listen} || {}} } | ||
| 50 | |||
| 51 | sub listen { | ||
| 52 | my ($self, $name) = @_; | ||
| 53 | |||
| 54 | my $dbh = $self->dbh; | ||
| 55 | $dbh->do('LISTEN ' . $dbh->quote_identifier($name)) unless $self->{listen}{$name}++; | ||
| 56 | $self->_watch; | ||
| 57 | $self->_notifications; | ||
| 58 | |||
| 59 | return $self; | ||
| 60 | } | ||
| 61 | |||
| 62 | sub notify { | ||
| 63 | my ($self, $name, $payload) = @_; | ||
| 64 | |||
| 65 | my $dbh = $self->dbh; | ||
| 66 | my $notify = 'NOTIFY ' . $dbh->quote_identifier($name); | ||
| 67 | $notify .= ', ' . $dbh->quote($payload) if defined $payload; | ||
| 68 | $dbh->do($notify); | ||
| 69 | $self->_notifications; | ||
| 70 | |||
| 71 | return $self; | ||
| 72 | } | ||
| 73 | |||
| 74 | sub pid { shift->dbh->{pg_pid} } | ||
| 75 | |||
| 76 | sub ping { shift->dbh->ping } | ||
| 77 | |||
| 78 | sub query { | ||
| 79 | my ($self, $query, @args) = @_; | ||
| 80 | my $cb = ref $args[-1] eq 'CODE' ? pop @args : undef; | ||
| 81 | |||
| 82 | ($query, @args) = $query->to_list if (blessed($query) && $query->isa('Mojo::SQL::Statement')); | ||
| 83 | |||
| 84 | croak 'Non-blocking query already in progress' if $self->{waiting}; | ||
| 85 | |||
| 86 | my %attrs; | ||
| 87 | $attrs{pg_placeholder_dollaronly} = 1 if delete $self->{dollar_only}; | ||
| 88 | $attrs{pg_async} = PG_ASYNC if $cb; | ||
| 89 | my $sth = $self->dbh->prepare_cached($query, \%attrs, 3); | ||
| 90 | local $sth->{HandleError} = sub { $_[0] = shortmess $_[0]; 0 }; | ||
| 91 | |||
| 92 | for (my $i = 0; $#args >= $i; $i++) { | ||
| 93 | my ($param, $attrs) = ($args[$i], {}); | ||
| 94 | if (ref $param eq 'HASH') { | ||
| 95 | if (exists $param->{-json}) { $param = to_json $param->{-json} } | ||
| 96 | elsif (exists $param->{json}) { $param = to_json $param->{json} } | ||
| 97 | elsif (exists $param->{type} && exists $param->{value}) { | ||
| 98 | ($attrs->{pg_type}, $param) = @{$param}{qw(type value)}; | ||
| 99 | } | ||
| 100 | } | ||
| 101 | $sth->bind_param($i + 1, $param, $attrs); | ||
| 102 | } | ||
| 103 | my $rv = $sth->execute; | ||
| 104 | |||
| 105 | # Blocking | ||
| 106 | unless ($cb) { | ||
| 107 | $self->_notifications; | ||
| 108 | return $self->results_class->new(db => $self, sth => $sth, rv => $rv); | ||
| 109 | } | ||
| 110 | |||
| 111 | # Non-blocking | ||
| 112 | $self->{waiting} = {cb => $cb, sth => $sth}; | ||
| 113 | $self->{finish} = []; | ||
| 114 | $self->_watch; | ||
| 115 | } | ||
| 116 | |||
| 117 | sub query_p { | ||
| 118 | my $self = shift; | ||
| 119 | my $promise = Mojo::Promise->new; | ||
| 120 | $self->query(@_ => sub { $_[1] ? $promise->reject($_[1]) : $promise->resolve($_[2]) }); | ||
| 121 | return $promise; | ||
| 122 | } | ||
| 123 | |||
| 124 | sub tables { | ||
| 125 | my @tables = shift->dbh->tables('', '', '', ''); | ||
| 126 | return [grep { $_ !~ /^(?:pg_catalog|information_schema)\./ } @tables]; | ||
| 127 | } | ||
| 128 | |||
| 129 | sub unlisten { | ||
| 130 | my ($self, $name) = @_; | ||
| 131 | |||
| 132 | my $dbh = $self->dbh; | ||
| 133 | $dbh->do('UNLISTEN ' . $dbh->quote_identifier($name)); | ||
| 134 | $name eq '*' ? delete $self->{listen} : delete $self->{listen}{$name}; | ||
| 135 | $self->_notifications; | ||
| 136 | $self->_unwatch unless $self->{waiting} || $self->is_listening; | ||
| 137 | |||
| 138 | return $self; | ||
| 139 | } | ||
| 140 | |||
| 141 | sub _finish_when_safe { | ||
| 142 | my $self = shift; | ||
| 143 | if ($self->{finish}) { push @{$self->{finish}}, @_ } | ||
| 144 | else { $_->finish for @_ } | ||
| 145 | } | ||
| 146 | |||
| 147 | sub _notifications { | ||
| 148 | my $self = shift; | ||
| 149 | |||
| 150 | my $dbh = $self->dbh; | ||
| 151 | my $n; | ||
| 152 | return undef unless $n = eval { $dbh->pg_notifies }; | ||
| 153 | while ($n) { | ||
| 154 | $self->emit(notification => @$n); | ||
| 155 | $n = eval { $dbh->pg_notifies }; | ||
| 156 | } | ||
| 157 | |||
| 158 | return 1; | ||
| 159 | } | ||
| 160 | |||
| 161 | sub _unwatch { | ||
| 162 | my $self = shift; | ||
| 163 | return unless delete $self->{watching}; | ||
| 164 | Mojo::IOLoop->singleton->reactor->remove($self->{handle}); | ||
| 165 | $self->emit('close') if $self->is_listening; | ||
| 166 | } | ||
| 167 | |||
| 168 | sub _watch { | ||
| 169 | my $self = shift; | ||
| 170 | |||
| 171 | return if $self->{watching} || $self->{watching}++; | ||
| 172 | |||
| 173 | my $dbh = $self->dbh; | ||
| 174 | unless ($self->{handle}) { | ||
| 175 | open $self->{handle}, '<&', $dbh->{pg_socket} or die "Can't dup: $!"; | ||
| 176 | } | ||
| 177 | Mojo::IOLoop->singleton->reactor->io( | ||
| 178 | $self->{handle} => sub { | ||
| 179 | my $reactor = shift; | ||
| 180 | |||
| 181 | return $self->_unwatch if !$self->_notifications && !$self->{waiting}; | ||
| 182 | |||
| 183 | # Do not raise exceptions inside the event loop | ||
| 184 | return if !$self->{waiting} || !do { local $dbh->{RaiseError} = 0; $dbh->pg_ready }; | ||
| 185 | my ($sth, $cb) = @{delete $self->{waiting}}{qw(sth cb)}; | ||
| 186 | |||
| 187 | my $rv = do { local $dbh->{RaiseError} = 0; $dbh->pg_result }; | ||
| 188 | my $err = defined $rv ? undef : $dbh->errstr; | ||
| 189 | |||
| 190 | $self->$cb($err, $self->results_class->new(db => $self, sth => $sth, rv => $rv)); | ||
| 191 | $self->_finish_when_safe(@{delete $self->{finish}}) if $self->{finish}; | ||
| 192 | $self->_unwatch unless $self->{waiting} || $self->is_listening; | ||
| 193 | } | ||
| 194 | )->watch($self->{handle}, 1, 0); | ||
| 195 | } | ||
| 196 | |||
| 197 | 1; | ||
| 198 | |||
| 199 | =encoding utf8 | ||
| 200 | |||
| 201 | =head1 NAME | ||
| 202 | |||
| 203 | Mojo::Pg::Database - Database | ||
| 204 | |||
| 205 | =head1 SYNOPSIS | ||
| 206 | |||
| 207 | use Mojo::Pg::Database; | ||
| 208 | |||
| 209 | my $db = Mojo::Pg::Database->new(pg => $pg, dbh => $dbh); | ||
| 210 | $db->query('SELECT * FROM foo') ->hashes->map(sub { $_->{bar} })->join("\n")->say; | ||
| 211 | |||
| 212 | =head1 DESCRIPTION | ||
| 213 | |||
| 214 | L<Mojo::Pg::Database> is a container for L<DBD::Pg> database handles used by L<Mojo::Pg>. | ||
| 215 | |||
| 216 | =head1 EVENTS | ||
| 217 | |||
| 218 | L<Mojo::Pg::Database> inherits all events from L<Mojo::EventEmitter> and can emit the following new ones. | ||
| 219 | |||
| 220 | =head2 close | ||
| 221 | |||
| 222 | $db->on(close => sub ($db) { | ||
| 223 | ... | ||
| 224 | }); | ||
| 225 | |||
| 226 | Emitted when the database connection gets closed while waiting for notifications. | ||
| 227 | |||
| 228 | =head2 notification | ||
| 229 | |||
| 230 | $db->on(notification => sub ($db, $name, $pid, $payload) { | ||
| 231 | ... | ||
| 232 | }); | ||
| 233 | |||
| 234 | Emitted when a notification has been received. | ||
| 235 | |||
| 236 | =head1 ATTRIBUTES | ||
| 237 | |||
| 238 | L<Mojo::Pg::Database> implements the following attributes. | ||
| 239 | |||
| 240 | =head2 dbh | ||
| 241 | |||
| 242 | my $dbh = $db->dbh; | ||
| 243 | $db = $db->dbh($dbh); | ||
| 244 | |||
| 245 | L<DBD::Pg> database handle used for all queries. | ||
| 246 | |||
| 247 | # Use DBI utility methods | ||
| 248 | my $quoted = $db->dbh->quote_identifier('foo.bar'); | ||
| 249 | |||
| 250 | =head2 pg | ||
| 251 | |||
| 252 | my $pg = $db->pg; | ||
| 253 | $db = $db->pg(Mojo::Pg->new); | ||
| 254 | |||
| 255 | L<Mojo::Pg> object this database belongs to. Note that this attribute is weakened. | ||
| 256 | |||
| 257 | =head2 results_class | ||
| 258 | |||
| 259 | my $class = $db->results_class; | ||
| 260 | $db = $db->results_class('MyApp::Results'); | ||
| 261 | |||
| 262 | Class to be used by L</"query">, defaults to L<Mojo::Pg::Results>. Note that this class needs to have already been | ||
| 263 | loaded before L</"query"> is called. | ||
| 264 | |||
| 265 | =head1 METHODS | ||
| 266 | |||
| 267 | L<Mojo::Pg::Database> inherits all methods from L<Mojo::EventEmitter> and implements the following new ones. | ||
| 268 | |||
| 269 | =head2 begin | ||
| 270 | |||
| 271 | my $tx = $db->begin; | ||
| 272 | |||
| 273 | Begin transaction and return L<Mojo::Pg::Transaction> object, which will automatically roll back the transaction unless | ||
| 274 | L<Mojo::Pg::Transaction/"commit"> has been called before it is destroyed. | ||
| 275 | |||
| 276 | # Insert rows in a transaction | ||
| 277 | eval { | ||
| 278 | my $tx = $db->begin; | ||
| 279 | $db->insert('frameworks', {name => 'Catalyst'}); | ||
| 280 | $db->insert('frameworks', {name => 'Mojolicious'}); | ||
| 281 | $tx->commit; | ||
| 282 | }; | ||
| 283 | say $@ if $@; | ||
| 284 | |||
| 285 | =head2 delete | ||
| 286 | |||
| 287 | my $results = $db->delete($table, \%where, \%options); | ||
| 288 | |||
| 289 | Generate a C<DELETE> statement with L<Mojo::Pg/"abstract"> (usually an L<SQL::Abstract::Pg> object) and execute it with | ||
| 290 | L</"query">. You can also append a callback to perform operations non-blocking. | ||
| 291 | |||
| 292 | $db->delete(some_table => sub ($db, $err, $results) { | ||
| 293 | ... | ||
| 294 | }); | ||
| 295 | Mojo::IOLoop->start unless Mojo::IOLoop->is_running; | ||
| 296 | |||
| 297 | Use all the same argument variations you would pass to the C<delete> method of L<SQL::Abstract>. | ||
| 298 | |||
| 299 | # "DELETE FROM some_table" | ||
| 300 | $db->delete('some_table'); | ||
| 301 | |||
| 302 | # "DELETE FROM some_table WHERE foo = 'bar'" | ||
| 303 | $db->delete('some_table', {foo => 'bar'}); | ||
| 304 | |||
| 305 | # "DELETE from some_table WHERE foo LIKE '%test%'" | ||
| 306 | $db->delete('some_table', {foo => {-like => '%test%'}}); | ||
| 307 | |||
| 308 | # "DELETE FROM some_table WHERE foo = 'bar' RETURNING id" | ||
| 309 | $db->delete('some_table', {foo => 'bar'}, {returning => 'id'}); | ||
| 310 | |||
| 311 | =head2 delete_p | ||
| 312 | |||
| 313 | my $promise = $db->delete_p($table, \%where, \%options); | ||
| 314 | |||
| 315 | Same as L</"delete">, but performs all operations non-blocking and returns a L<Mojo::Promise> object instead of | ||
| 316 | accepting a callback. | ||
| 317 | |||
| 318 | $db->delete_p('some_table')->then(sub ($results) { | ||
| 319 | ... | ||
| 320 | })->catch(sub ($err) { | ||
| 321 | ... | ||
| 322 | })->wait; | ||
| 323 | |||
| 324 | =head2 disconnect | ||
| 325 | |||
| 326 | $db->disconnect; | ||
| 327 | |||
| 328 | Disconnect L</"dbh"> and prevent it from getting reused. | ||
| 329 | |||
| 330 | =head2 dollar_only | ||
| 331 | |||
| 332 | $db = $db->dollar_only; | ||
| 333 | |||
| 334 | Activate C<pg_placeholder_dollaronly> for next L</"query"> call and allow C<?> to be used as an operator. | ||
| 335 | |||
| 336 | # Check for a key in a JSON document | ||
| 337 | $db->dollar_only->query('SELECT * FROM foo WHERE bar ? $1', 'baz') | ||
| 338 | ->expand->hashes->map(sub { $_->{bar}{baz} })->join("\n")->say; | ||
| 339 | |||
| 340 | =head2 insert | ||
| 341 | |||
| 342 | my $results = $db->insert($table, \@values || \%fieldvals || \@fieldvals, \%options); | ||
| 343 | |||
| 344 | Generate an C<INSERT> statement with L<Mojo::Pg/"abstract"> (usually an L<SQL::Abstract::Pg> object) and execute it | ||
| 345 | with L</"query">. You can also append a callback to perform operations non-blocking. | ||
| 346 | |||
| 347 | $db->insert(some_table => {foo => 'bar'} => sub ($db, $err, $results) { | ||
| 348 | ... | ||
| 349 | }); | ||
| 350 | Mojo::IOLoop->start unless Mojo::IOLoop->is_running; | ||
| 351 | |||
| 352 | Use all the same argument variations you would pass to the C<insert> method of L<SQL::Abstract>. | ||
| 353 | |||
| 354 | # "INSERT INTO some_table (foo, baz) VALUES ('bar', 'yada')" | ||
| 355 | $db->insert('some_table', {foo => 'bar', baz => 'yada'}); | ||
| 356 | |||
| 357 | # "INSERT INTO some_table (foo) VALUES ({1,2,3})" | ||
| 358 | $db->insert('some_table', {foo => [1, 2, 3]}); | ||
| 359 | |||
| 360 | # "INSERT INTO some_table (foo) VALUES ('bar') RETURNING id" | ||
| 361 | $db->insert('some_table', {foo => 'bar'}, {returning => 'id'}); | ||
| 362 | |||
| 363 | # "INSERT INTO some_table (foo) VALUES ('bar') RETURNING id, foo" | ||
| 364 | $db->insert('some_table', {foo => 'bar'}, {returning => ['id', 'foo']}); | ||
| 365 | |||
| 366 | As well as some PostgreSQL specific extensions added by L<SQL::Abstract::Pg>. | ||
| 367 | |||
| 368 | # "INSERT INTO some_table (foo) VALUES ('{"test":23}')" | ||
| 369 | $db->insert('some_table', {foo => {-json => {test => 23}}}); | ||
| 370 | |||
| 371 | # "INSERT INTO some_table (foo) VALUES ('bar') ON CONFLICT DO NOTHING" | ||
| 372 | $db->insert('some_table', {foo => 'bar'}, {on_conflict => undef}); | ||
| 373 | |||
| 374 | Including operations commonly referred to as C<upsert>. | ||
| 375 | |||
| 376 | # "INSERT INTO t (a) VALUES ('b') ON CONFLICT (a) DO UPDATE SET a = 'c'" | ||
| 377 | $db->insert('t', {a => 'b'}, {on_conflict => [a => {a => 'c'}]}); | ||
| 378 | |||
| 379 | # "INSERT INTO t (a, b) VALUES ('c', 'd') ON CONFLICT (a, b) DO UPDATE SET a = 'e'" | ||
| 380 | $db->insert('t', {a => 'c', b => 'd'}, {on_conflict => [['a', 'b'] => {a => 'e'}]}); | ||
| 381 | |||
| 382 | And bulk inserts with multiple rows. | ||
| 383 | |||
| 384 | # "INSERT INTO t (a, b) VALUES ('c', 'd'), ('e', DEFAULT) RETURNING id" | ||
| 385 | $db->insert('t', [{a => 'c', b => 'd'}, {a => 'e'}], {returning => 'id'}); | ||
| 386 | |||
| 387 | =head2 insert_p | ||
| 388 | |||
| 389 | my $promise = $db->insert_p($table, \@values || \%fieldvals || \@fieldvals, \%options); | ||
| 390 | |||
| 391 | Same as L</"insert">, but performs all operations non-blocking and returns a L<Mojo::Promise> object instead of | ||
| 392 | accepting a callback. | ||
| 393 | |||
| 394 | $db->insert_p(some_table => {foo => 'bar'})->then(sub ($results) { | ||
| 395 | ... | ||
| 396 | })->catch(sub ($err) { | ||
| 397 | ... | ||
| 398 | })->wait; | ||
| 399 | |||
| 400 | =head2 is_listening | ||
| 401 | |||
| 402 | my $bool = $db->is_listening; | ||
| 403 | |||
| 404 | Check if L</"dbh"> is listening for notifications. | ||
| 405 | |||
| 406 | =head2 listen | ||
| 407 | |||
| 408 | $db = $db->listen('foo'); | ||
| 409 | |||
| 410 | Subscribe to a channel and receive L</"notification"> events when the L<Mojo::IOLoop> event loop is running. | ||
| 411 | |||
| 412 | =head2 notify | ||
| 413 | |||
| 414 | $db = $db->notify('foo'); | ||
| 415 | $db = $db->notify(foo => 'bar'); | ||
| 416 | |||
| 417 | Notify a channel. | ||
| 418 | |||
| 419 | =head2 pid | ||
| 420 | |||
| 421 | my $pid = $db->pid; | ||
| 422 | |||
| 423 | Return the process id of the backend server process. | ||
| 424 | |||
| 425 | =head2 ping | ||
| 426 | |||
| 427 | my $bool = $db->ping; | ||
| 428 | |||
| 429 | Check database connection. | ||
| 430 | |||
| 431 | =head2 query | ||
| 432 | |||
| 433 | my $results = $db->query('SELECT * FROM foo'); | ||
| 434 | my $results = $db->query('INSERT INTO foo VALUES (?, ?, ?)', @values); | ||
| 435 | my $results = $db->query('SELECT ?::JSON AS foo', {-json => {bar => 'baz'}}); | ||
| 436 | my $results = $db->query(sql('SELECT * FROM foo WHERE id = ?', $id)); | ||
| 437 | |||
| 438 | Execute a blocking L<SQL|http://www.postgresql.org/docs/current/static/sql.html> statement and return a results object | ||
| 439 | based on L</"results_class"> (which is usually L<Mojo::Pg::Results>) with the query results. The L<DBD::Pg> statement | ||
| 440 | handle will be automatically reused when it is not active anymore, to increase the performance of future queries. You | ||
| 441 | can also append a callback to perform operations non-blocking. | ||
| 442 | |||
| 443 | $db->query('INSERT INTO foo VALUES (?, ?, ?)' => @values => sub ($db, $err, $results) { | ||
| 444 | ... | ||
| 445 | }); | ||
| 446 | Mojo::IOLoop->start unless Mojo::IOLoop->is_running; | ||
| 447 | |||
| 448 | For composable SQL statements with protection from SQL injection attacks, you can also pass a L<Mojo::SQL::Statement> | ||
| 449 | object and all bind values will be used automatically. | ||
| 450 | |||
| 451 | use Mojo::SQL qw(sql); | ||
| 452 | $db->query(sql('SELECT ?::INT AS foo', 23)); | ||
| 453 | |||
| 454 | Hash reference arguments containing a value named C<-json> or C<json> will be encoded to JSON text with | ||
| 455 | L<Mojo::JSON/"to_json">. To accomplish the reverse, you can use the method L<Mojo::Pg::Results/"expand">, which | ||
| 456 | automatically decodes all fields of the types C<json> and C<jsonb> with L<Mojo::JSON/"from_json"> to Perl values. | ||
| 457 | |||
| 458 | # "I ♥ Mojolicious!" | ||
| 459 | $db->query('SELECT ?::JSONB AS foo', {-json => {bar => 'I ♥ Mojolicious!'}}) ->expand->hash->{foo}{bar}; | ||
| 460 | |||
| 461 | Hash reference arguments containing values named C<type> and C<value> can be used to bind specific L<DBD::Pg> data | ||
| 462 | types to placeholders. | ||
| 463 | |||
| 464 | # Insert binary data | ||
| 465 | use DBD::Pg ':pg_types'; | ||
| 466 | $db->query('INSERT INTO bar VALUES (?)', {type => PG_BYTEA, value => $bytes}); | ||
| 467 | |||
| 468 | =head2 query_p | ||
| 469 | |||
| 470 | my $promise = $db->query_p('SELECT * FROM foo'); | ||
| 471 | |||
| 472 | Same as L</"query">, but performs all operations non-blocking and returns a L<Mojo::Promise> object instead of | ||
| 473 | accepting a callback. | ||
| 474 | |||
| 475 | $db->query_p('INSERT INTO foo VALUES (?, ?, ?)' => @values)->then(sub ($results) { | ||
| 476 | ... | ||
| 477 | })->catch(sub ($err) { | ||
| 478 | ... | ||
| 479 | })->wait; | ||
| 480 | |||
| 481 | =head2 select | ||
| 482 | |||
| 483 | my $results = $db->select($source, $fields, $where, \%options); | ||
| 484 | |||
| 485 | Generate a C<SELECT> statement with L<Mojo::Pg/"abstract"> (usually an L<SQL::Abstract::Pg> object) and execute it with | ||
| 486 | L</"query">. You can also append a callback to perform operations non-blocking. | ||
| 487 | |||
| 488 | $db->select(some_table => ['foo'] => {bar => 'yada'} => sub ($db, $err, $results) { | ||
| 489 | ... | ||
| 490 | }); | ||
| 491 | Mojo::IOLoop->start unless Mojo::IOLoop->is_running; | ||
| 492 | |||
| 493 | Use all the same argument variations you would pass to the C<select> method of L<SQL::Abstract>. | ||
| 494 | |||
| 495 | # "SELECT * FROM some_table" | ||
| 496 | $db->select('some_table'); | ||
| 497 | |||
| 498 | # "SELECT id, foo FROM some_table" | ||
| 499 | $db->select('some_table', ['id', 'foo']); | ||
| 500 | |||
| 501 | # "SELECT * FROM some_table WHERE foo = 'bar'" | ||
| 502 | $db->select('some_table', undef, {foo => 'bar'}); | ||
| 503 | |||
| 504 | # "SELECT * FROM some_table WHERE foo LIKE '%test%'" | ||
| 505 | $db->select('some_table', undef, {foo => {-like => '%test%'}}); | ||
| 506 | |||
| 507 | As well as some PostgreSQL specific extensions added by L<SQL::Abstract::Pg>. | ||
| 508 | |||
| 509 | # "SELECT * FROM foo JOIN bar ON (bar.foo_id = foo.id)" | ||
| 510 | $db->select(['foo', ['bar', foo_id => 'id']]); | ||
| 511 | |||
| 512 | # "SELECT * FROM foo LEFT JOIN bar ON (bar.foo_id = foo.id)" | ||
| 513 | $db->select(['foo', [-left => 'bar', foo_id => 'id']]); | ||
| 514 | |||
| 515 | # "SELECT foo AS bar FROM some_table" | ||
| 516 | $db->select('some_table', [[foo => 'bar']]); | ||
| 517 | |||
| 518 | # "SELECT * FROM some_table WHERE foo = '[1,2,3]'" | ||
| 519 | $db->select('some_table', '*', {foo => {'=' => {-json => [1, 2, 3]}}}); | ||
| 520 | |||
| 521 | # "SELECT EXTRACT(EPOCH FROM foo) AS foo, bar FROM some_table" | ||
| 522 | $db->select('some_table', [\'extract(epoch from foo) AS foo', 'bar']); | ||
| 523 | |||
| 524 | # "SELECT 'test' AS foo, bar FROM some_table" | ||
| 525 | $db->select('some_table', [\['? AS foo', 'test'], 'bar']); | ||
| 526 | |||
| 527 | Including a new last argument to pass many new options. | ||
| 528 | |||
| 529 | # "SELECT * FROM some_table WHERE foo = 'bar' ORDER BY id DESC" | ||
| 530 | $db->select('some_table', '*', {foo => 'bar'}, {order_by => {-desc => 'id'}}); | ||
| 531 | |||
| 532 | # "SELECT * FROM some_table LIMIT 10 OFFSET 20" | ||
| 533 | $db->select('some_table', '*', undef, {limit => 10, offset => 20}); | ||
| 534 | |||
| 535 | # "SELECT * FROM some_table WHERE foo = 23 GROUP BY foo, bar" | ||
| 536 | $db->select('some_table', '*', {foo => 23}, {group_by => ['foo', 'bar']}); | ||
| 537 | |||
| 538 | # "SELECT * FROM t WHERE a = 'b' GROUP BY c HAVING d = 'e'" | ||
| 539 | $db->select('t', '*', {a => 'b'}, {group_by => ['c'], having => {d => 'e'}}); | ||
| 540 | |||
| 541 | # "SELECT * FROM some_table WHERE id = 1 FOR UPDATE" | ||
| 542 | $db->select('some_table', '*', {id => 1}, {for => 'update'}); | ||
| 543 | |||
| 544 | # "SELECT * FROM some_table WHERE id = 1 FOR UPDATE SKIP LOCKED" | ||
| 545 | $db->select('some_table', '*', {id => 1}, {for => \'update skip locked'}); | ||
| 546 | |||
| 547 | =head2 select_p | ||
| 548 | |||
| 549 | my $promise = $db->select_p($source, $fields, $where, \%options); | ||
| 550 | |||
| 551 | Same as L</"select">, but performs all operations non-blocking and returns a L<Mojo::Promise> object instead of | ||
| 552 | accepting a callback. | ||
| 553 | |||
| 554 | $db->select_p(some_table => ['foo'] => {bar => 'yada'})->then(sub ($results) { | ||
| 555 | ... | ||
| 556 | })->catch(sub ($err) { | ||
| 557 | ... | ||
| 558 | })->wait; | ||
| 559 | |||
| 560 | =head2 tables | ||
| 561 | |||
| 562 | my $tables = $db->tables; | ||
| 563 | |||
| 564 | Return table and view names for this database, that are visible to the current user and not internal, as an array | ||
| 565 | reference. | ||
| 566 | |||
| 567 | # Names of all tables | ||
| 568 | say for @{$db->tables}; | ||
| 569 | |||
| 570 | =head2 unlisten | ||
| 571 | |||
| 572 | $db = $db->unlisten('foo'); | ||
| 573 | $db = $db->unlisten('*'); | ||
| 574 | |||
| 575 | Unsubscribe from a channel, C<*> can be used to unsubscribe from all channels. | ||
| 576 | |||
| 577 | =head2 update | ||
| 578 | |||
| 579 | my $results = $db->update($table, \%fieldvals, \%where, \%options); | ||
| 580 | |||
| 581 | Generate an C<UPDATE> statement with L<Mojo::Pg/"abstract"> (usually an L<SQL::Abstract::Pg> object) and execute it | ||
| 582 | with L</"query">. You can also append a callback to perform operations non-blocking. | ||
| 583 | |||
| 584 | $db->update(some_table => {foo => 'baz'} => {foo => 'bar'} => sub ($db, $err, $results) { | ||
| 585 | ... | ||
| 586 | }); | ||
| 587 | Mojo::IOLoop->start unless Mojo::IOLoop->is_running; | ||
| 588 | |||
| 589 | Use all the same argument variations you would pass to the C<update> method of L<SQL::Abstract>. | ||
| 590 | |||
| 591 | # "UPDATE some_table SET foo = 'bar' WHERE id = 23" | ||
| 592 | $db->update('some_table', {foo => 'bar'}, {id => 23}); | ||
| 593 | |||
| 594 | # "UPDATE some_table SET foo = {1,2,3} WHERE id = 23" | ||
| 595 | $db->update('some_table', {foo => [1, 2, 3]}, {id => 23}); | ||
| 596 | |||
| 597 | # "UPDATE some_table SET foo = 'bar' WHERE foo LIKE '%test%'" | ||
| 598 | $db->update('some_table', {foo => 'bar'}, {foo => {-like => '%test%'}}); | ||
| 599 | |||
| 600 | # "UPDATE some_table SET foo = 'bar' WHERE id = 23 RETURNING id" | ||
| 601 | $db->update('some_table', {foo => 'bar'}, {id => 23}, {returning => 'id'}); | ||
| 602 | |||
| 603 | # "UPDATE some_table SET foo = '[1,2,3]' WHERE bar = 23" | ||
| 604 | $db->update('some_table', {foo => {-json => [1, 2, 3]}}, {bar => 23}); | ||
| 605 | |||
| 606 | =head2 update_p | ||
| 607 | |||
| 608 | my $promise = $db->update_p($table, \%fieldvals, \%where, \%options); | ||
| 609 | |||
| 610 | Same as L</"update">, but performs all operations non-blocking and returns a L<Mojo::Promise> object instead of | ||
| 611 | accepting a callback. | ||
| 612 | |||
| 613 | $db->update_p(some_table => {foo => 'baz'} => {foo => 'bar'})->then(sub ($results) { | ||
| 614 | ... | ||
| 615 | })->catch(sub ($err) { | ||
| 616 | ... | ||
| 617 | })->wait; | ||
| 618 | |||
| 619 | =head1 SEE ALSO | ||
| 620 | |||
| 621 | L<Mojo::Pg>, L<Mojolicious::Guides>, L<https://mojolicious.org>. | ||
| 622 | |||
| 623 | =cut | ||