@@ -270,6 +270,24 @@ class QueryTests : XCTestCase {
270270 )
271271 }
272272
273+ func test_upsert_withOnConflict_compilesInsertOrOnConflictExpression( ) {
274+ AssertSQL (
275+ " INSERT INTO \" users \" ( \" email \" , \" age \" ) VALUES ('[email protected] ', 30) ON CONFLICT ( \" email \" ) DO UPDATE SET \" age \" = \" excluded \" . \" age \" " , 276+ users
. upsert ( email
<- " [email protected] " , age
<- 30 , onConflictOf
: email
) 277+ )
278+ }
279+
280+ func test_upsert_encodable( ) throws {
281+ let emails = Table ( " emails " )
282+ let string = Expression < String > ( " string " )
283+ let value = TestCodable ( int: 1 , string: " 2 " , bool: true , float: 3 , double: 4 , optional: nil , sub: nil )
284+ let insert = try emails. upsert ( value, onConflictOf: string)
285+ AssertSQL (
286+ " INSERT INTO \" emails \" ( \" int \" , \" string \" , \" bool \" , \" float \" , \" double \" ) VALUES (1, '2', 1, 3.0, 4.0) ON CONFLICT ( \" string \" ) DO UPDATE SET \" int \" = \" excluded \" . \" int \" , \" bool \" = \" excluded \" . \" bool \" , \" float \" = \" excluded \" . \" float \" , \" double \" = \" excluded \" . \" double \" " ,
287+ insert
288+ )
289+ }
290+
273291 func test_update_compilesUpdateExpression( ) {
274292 AssertSQL (
275293 " UPDATE \" users \" SET \" age \" = 30, \" admin \" = 1 WHERE ( \" id \" = 1) " ,
@@ -378,7 +396,8 @@ class QueryIntegrationTests : SQLiteTestCase {
378396
379397 let id = Expression < Int64 > ( " id " )
380398 let email = Expression < String > ( " email " )
381-
399+ let age = Expression < Int > ( " age " )
400+
382401 override func setUp( ) {
383402 super. setUp ( )
384403
@@ -486,6 +505,20 @@ class QueryIntegrationTests : SQLiteTestCase {
486505 XCTAssertEqual ( 1 , id)
487506 }
488507
508+ func test_upsert( ) throws {
509+ let fetchAge = { ( ) throws -> Int ? in
510+ return try self . db
. pluck ( self . users
. filter ( self . email
== " [email protected] " ) ) . flatMap { $0 [ self . age
] } 511+ }
512+
513+ let id = try db
. run ( users
. upsert ( email
<- " [email protected] " , age
<- 30 , onConflictOf
: email
) ) 514+ XCTAssertEqual ( 1 , id)
515+ XCTAssertEqual ( 30 , try fetchAge ( ) )
516+
517+ let nextId = try db
. run ( users
. upsert ( email
<- " [email protected] " , age
<- 42 , onConflictOf
: email
) ) 518+ XCTAssertEqual ( 1 , nextId)
519+ XCTAssertEqual ( 42 , try fetchAge ( ) )
520+ }
521+
489522 func test_update( ) {
490523 let changes = try ! db
. run ( users
. update ( email
<- " [email protected] " ) ) 491524 XCTAssertEqual ( 0 , changes)
0 commit comments