@@ -277,6 +277,79 @@ describe "lapis.db.model", ->
277277 post\ update user_id : db. raw " (case when false then 1234 else null end)"
278278 assert . same nil , post. user_id
279279
280+ describe " on_conflict" , ->
281+ it " creates with on_conflict do_nothing" , ->
282+ Likes \ create_table!
283+ -- First insert should succeed
284+ like1 = Likes \ create {
285+ user_id : 1
286+ post_id : 1
287+ count : 5
288+ }
289+
290+ assert . same 1 , like1. user_id
291+ assert . same 1 , like1. post_id
292+ assert . same 5 , like1. count
293+
294+ -- Second insert with same primary key should be ignored
295+ like2 = Likes \ create {
296+ user_id : 1
297+ post_id : 1
298+ count : 99
299+ } , on_conflict : " do_nothing"
300+
301+ -- When conflict occurs, the returned object has the input values
302+ -- but nothing was actually inserted
303+ assert . same 1 , like2. user_id
304+ assert . same 1 , like2. post_id
305+ assert . same 99 , like2. count
306+
307+ -- Verify only one row exists with original count
308+ assert . same 1 , Likes \ count!
309+ original = Likes \ find 1 , 1
310+ assert . same 5 , original. count
311+
312+ it " creates with on_conflict and returning *" , ->
313+ Likes \ create_table!
314+ -- First insert
315+ Likes \ create {
316+ user_id : 1
317+ post_id : 1
318+ count : 5
319+ }
320+
321+ -- Conflicting insert with returning * - should return nothing when conflict
322+ like2 = Likes \ create {
323+ user_id : 1
324+ post_id : 1
325+ count : 99
326+ } , on_conflict : " do_nothing" , returning : " *"
327+
328+ -- Values come from input since RETURNING gives nothing on conflict
329+ assert . same 1 , like2. user_id
330+ assert . same 1 , like2. post_id
331+
332+ -- Verify only one row exists
333+ assert . same 1 , Likes \ count!
334+
335+ it " creates successfully with on_conflict when no conflict" , ->
336+ Likes \ create_table!
337+ -- Insert with on_conflict should work normally when no conflict
338+ like = Likes \ create {
339+ user_id : 1
340+ post_id : 1
341+ count : 10
342+ } , on_conflict : " do_nothing"
343+
344+ assert . same 1 , like. user_id
345+ assert . same 1 , like. post_id
346+ assert . same 10 , like. count
347+
348+ -- Verify row was inserted
349+ assert . same 1 , Likes \ count!
350+ found = Likes \ find 1 , 1
351+ assert . same 10 , found. count
352+
280353 describe " delete" , ->
281354 before_each ->
282355 Posts \ create_table!
0 commit comments