@@ -321,3 +321,44 @@ class Test(ModelBase, table_name="table", primary_key="id"):
321321 await Test .insert_multiple (conn , [])
322322
323323 assert list (await Test .select (conn )) == []
324+
325+
326+ async def test_upsert_insert_only (conn ):
327+ @dataclass
328+ class Test (ModelBase , table_name = "test_upsert" , primary_key = "id" ):
329+ id : int
330+ name : str
331+ count : int
332+ created_at : str
333+
334+ await conn .execute (* Test .create_table_sql ())
335+
336+ # Initial insert
337+ record = Test (1 , "Alice" , 5 , "2023-01-01" )
338+ was_updated = await record .upsert (conn )
339+ assert not was_updated # Should be False for initial insert
340+
341+ # Verify record was inserted
342+ result = await Test .select (conn , where = sql ("id = {}" , 1 ))
343+ assert len (result ) == 1
344+ assert result [0 ] == record
345+
346+ # Update without insert_only - should update all fields including created_at
347+ updated_record = Test (1 , "Alice Updated" , 10 , "2023-01-02" )
348+ was_updated = await updated_record .upsert (conn )
349+ assert was_updated # Should be True for update
350+
351+ result = await Test .select (conn , where = sql ("id = {}" , 1 ))
352+ assert len (result ) == 1
353+ assert result [0 ] == updated_record
354+
355+ # Update with insert_only - should not update created_at
356+ final_record = Test (1 , "Alice Final" , 15 , "2023-01-03" )
357+ was_updated = await final_record .upsert (conn , insert_only = {"created_at" })
358+ assert was_updated # Should be True for update
359+
360+ result = await Test .select (conn , where = sql ("id = {}" , 1 ))
361+ assert len (result ) == 1
362+ # created_at should still be the old value, other fields should be updated
363+ expected = Test (1 , "Alice Final" , 15 , "2023-01-02" ) # created_at unchanged
364+ assert result [0 ] == expected
0 commit comments