stephencelis / SQLite.swift

A type-safe, Swift-language layer over SQLite3.
MIT License
9.64k stars 1.56k forks source link

Support : How to Update if exists, insert if not #1013

Closed tongclement closed 4 years ago

tongclement commented 4 years ago

Build Information: IOS12 Xcode V11.0

Issue: How to update if exists, insert if not. My Current implementation with 'try' and 'catch' does not work as 'update' seems to update the whole db instead of saving the data properly.

My Current Implementation:

let rowid = try db.run(target_user.update(uuid <- uuidin, last_contact_date <- lastdate, contact_distance <- usr_closest_prox, contact_length <- usr_contact_length))
                     print("inserted id: \(rowid)")
                 } catch {
                     print("db update failed - never seen this user before - adding user instead: \(error)")
                    do {
                        let rowid = try db.run(contacts_db.insert(uuid <- uuidin, last_contact_date <- lastdate, contact_distance <- distance, contact_length <- length))
                        print("inserted id: \(rowid)")
                    } catch {
                        print("insertion failed: \(error)")
                    }
                 }

Expected Result:

For an existing user :

1: Update DB 2: Print Inserted ID = (eg:0)

For New User: 1: Attempt to update DB and produce ERROR -> Catched by db.insert method (prints "never seen this user before") 2: Successfully appends a new user, user id != 0

Current Result:

Even for a new user, it just directly overrides the db. The appended user id printed out is always 0

Code also sometimes produce error code 5

tongclement commented 4 years ago

Solved: One Option: Do Insert or replace into

try db.run(users.insert(or: .replace, email <- "alice@mac.com", name <- "Alice B."))
// INSERT OR REPLACE INTO "users" ("email", "name") VALUES ('alice@mac.com', 'Alice B.')

Other methods that I am still investigating and need help with: As all I am doing is incrementing a counter, maybe I can user the += method or counter++ method

Ucdemir commented 4 years ago

It is work if only conflict that means if it cross with primary keys