Return fiields in INSERT .. SELECT query

140 views
Skip to first unread message

Dmitry Krivenko

unread,
Apr 6, 2015, 3:48:38 AM4/6/15
to jooq...@googlegroups.com
Hi there! 
In case when I use a SELECT statement as the source of values for the INSERT statement I don't have ability to return the inserted record.    
I need to implement a query like this:
INSERT INTO test
   
(text)
    SELECT
'1234567890123456789'
    WHERE
        NOT EXISTS
(
            SELECT id FROM test WHERE text
= '1234567890123456789'
       
) returning id;

And I use this approach ( by the way, it would be great, if we had an ability to do it via InsertQuery) :
List<Param<?>> params = new LinkedList<>();
params.add(DSL.val("1234567890123456789"));
 
List<Field<?>> fields = new LinkedList<>();
fields
.add(TEST.TEXT);

SelectConditionStep<Record1<TEXT>> notExistsSelect = context.select(TEST.TEXT).from(TEST).where(TEST.TEXT.eq("1234567890123456789"));
SelectConditionStep<Record> insertIntoSelect = context.select(params).whereNotExists(notExistsSelect);

context
.insertInto(TEST, fields).select(insertIntoSelect).execute();
But I can't return inserted value, because Insert interface, which is returned by select(insertIntoSelect), doesn't have returning() method.
Are there any reason why it hasn't been implemented? Or maybe there is another approach to execute my query?

Lukas Eder

unread,
Apr 6, 2015, 12:26:02 PM4/6/15
to jooq...@googlegroups.com
For the record, this question has been cross-posted also to Stack Overflow:

This is a known API limitation and is currently being tracked here:

The simplest workaround right now is to resort to plain SQL:

DSL.using(configuration)
   .fetch("insert into {0} ({1}) {2} returning {3}",
       TEST, TEST.TEXT, select, TEST.ID);

Hope this helps,
Lukas

--
You received this message because you are subscribed to the Google Groups "jOOQ User Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jooq-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Dmitry Krivenko

unread,
Apr 7, 2015, 3:28:03 AM4/7/15
to jooq...@googlegroups.com
Thanks!

Lukas Eder

unread,
May 1, 2015, 8:20:29 AM5/1/15
to jooq...@googlegroups.com
This has now been implemented for jOOQ 3.7:

Cheers,
Lukas

Dmitry Krivenko

unread,
May 1, 2015, 8:46:21 AM5/1/15
to jooq...@googlegroups.com
great! thank you!
Reply all
Reply to author
Forward
0 new messages