maslbl4
maslbl4

Reputation: 136

jOOQ idempotent batch insert

I'm trying to implement an idempotent insert, this query looks good for this task

insert into test_table
select *
from (
         values (1, 2, 3, 4),
                (3, 4, 5, 6),
                (1, 2, 3, 4),
                (3, 4, 5, 6)
     ) as data(a, b, c, d)
where not exists(select 1
                 from test_table
                 where test_table.a = data.a
                   and test_table.b = data.b
                   and test_table.c = data.c);

Please help translate this query to jOOQ DSL
I used Greenplum database and is not supported ON CONFLICT syntax

Upvotes: 3

Views: 235

Answers (1)

Lukas Eder
Lukas Eder

Reputation: 221106

ctx.insertInto(TEST_TABLE)
   .select(
       select()
       .from(values(
           row(1, 2, 3, 4),
           row(3, 4, 5, 6),
           row(1, 2, 3, 4),
           row(3, 4, 5, 6)
       ).as("data", "a", "b", "c", "d"))
       .whereNotExists(
           selectOne()
           .from(TEST_TABLE)
           .where(TEST_TABLE.A.eq(field(name("data", "a"), TEST_TABLE.A.getDataType())))
           .and(TEST_TABLE.B.eq(field(name("data", "b"), TEST_TABLE.A.getDataType())))
           .and(TEST_TABLE.C.eq(field(name("data", "c"), TEST_TABLE.A.getDataType())))
       )
   )
   .execute();

This answer is assuming you're using the code generator for TEST_DATA (otherwise, construct your identifiers manually, as shown above for name("data", "a"), etc. or as shown here). Also, it assumes:

import static org.jooq.impl.DSL.*;

When Greenplum is formally supported, see #4700, then ON CONFLICT or ON DUPLICATE KEY IGNORE can be emulated for you.

Upvotes: 2

Related Questions