Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
add a shortcut for simple conflict targets
  • Loading branch information
kraih committed Jan 29, 2018
1 parent 7a7237f commit 7bb2864
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 3 deletions.
2 changes: 2 additions & 0 deletions Changes
@@ -1,5 +1,7 @@

4.08 2018-01-29
- Improved on_conflict option of insert and insert_p methods in
Mojo::Pg::Database with a shortcut for simple conflict targets.

4.07 2018-01-28
- Added support for "JOIN" to select and select_p methods in
Expand Down
5 changes: 4 additions & 1 deletion lib/Mojo/Pg/Database.pm
Expand Up @@ -372,7 +372,10 @@ As well as some PostgreSQL specific extensions added by L<SQL::Abstract::Pg>.
Including operations commonly referred to as C<upsert>.
# "insert into t (a) values ('b') on conflict (a) do update set a = 'c'"
$db->insert('t', {a => 'b'}, {on_conflict => [['a'], {a => 'c'}]});
$db->insert('t', {a => 'b'}, {on_conflict => [a => {a => 'c'}]});
# "insert into t (a) values ('b') on conflict (a, b) do update set a = 'c'"
$db->insert('t', {a => 'b'}, {on_conflict => [['a', 'b'], {a => 'c'}]});
=head2 insert_p
Expand Down
8 changes: 6 additions & 2 deletions lib/SQL/Abstract/Pg.pm
Expand Up @@ -48,8 +48,9 @@ sub _insert_returning {
ARRAYREF => sub {
my ($fields, $set) = @$conflict;
puke 'on_conflict value must be in the form [\@fields, \%set]'
unless ref $fields eq 'ARRAY' && ref $set eq 'HASH';
unless ref $set eq 'HASH';

$fields = [$fields] unless ref $fields eq 'ARRAY';
$conflict_sql
= '(' . join(', ', map { $self->_quote($_) } @$fields) . ')';
$conflict_sql .= $self->_sqlcase(' do update set ');
Expand Down Expand Up @@ -205,7 +206,10 @@ SQL with bind values are supported.
This includes operations commonly referred to as C<upsert>.
# "insert into t (a) values ('b') on conflict (a) do update set a = 'c'"
$abstract->insert('t', {a => 'b'}, {on_conflict => [['a'], {a => 'c'}]});
$abstract->insert('t', {a => 'b'}, {on_conflict => [a => {a => 'c'}]});
# "insert into t (a) values ('b') on conflict (a, b) do update set a = 'c'"
$abstract->insert('t', {a => 'b'}, {on_conflict => [['a', 'b'], {a => 'c'}]});
# "insert into t (a) values ('b') on conflict (a) do update set a = 'c'"
$abstract->insert(
Expand Down
11 changes: 11 additions & 0 deletions t/sql.t
Expand Up @@ -55,6 +55,17 @@ $result = [
'baz', 'yada'
];
is_deeply \@sql, $result, 'right query';
@sql = $abstract->insert(
'foo',
{bar => 'baz'},
{on_conflict => [foo => {foo => 'yada'}]}
);
$result = [
'INSERT INTO "foo" ( "bar") VALUES ( ? )'
. ' ON CONFLICT ("foo") DO UPDATE SET "foo" = ?',
'baz', 'yada'
];
is_deeply \@sql, $result, 'right query';

# ON CONFLICT (unsupported value)
eval { $abstract->insert('foo', {bar => 'baz'}, {on_conflict => [[], []]}) };
Expand Down

0 comments on commit 7bb2864

Please sign in to comment.