I'm trying to use Sqlite.swift to manage the database in my iOS app. But for some reason insert does not work, stupidly comes into catch and does not write anything to the database. Although the table successfully created

Here is the approximate code that I use (as written in the tutorial) `

 import SQLite let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! db = try Connection("\(path)/my_db.sqlite3") let users = Table("users") let id = Expression<Int64>("id") let name = Expression<String?>("name") let email = Expression<String>("email") try db.run(users.create { t in t.column(id, primaryKey: true) t.column(name) t.column(email, unique: true) }) // CREATE TABLE "users" ( // "id" INTEGER PRIMARY KEY NOT NULL, // "name" TEXT, // "email" TEXT NOT NULL UNIQUE // ) do { let insert = users.insert(name <- "Alice", email <- "alice@mac.com") let rowid = try db.run(insert) } catch{ print("Not inserted") } 

Maybe I missed something or something else should be used for databases in iOS?

    2 answers 2

    Carefully look at this line:

     t.column(email, unique: true) 

    Here it is stated that the e-mail must be unique. Thus, if it falls into the catch block, then an attempt was made to add another user with the same email.

    For clarity check write, for example:

     do{ let insert = users.insert(name <- "Alice", email <- "alice\(arc4random_uniform(9999))@mac.com") let rowid = try db.run(insert) } catch{ print("Not inserted") } 

    Well, print the result:

     for user in try db.prepare(users) { print("id: \(user[id]), name: \(user[name]), email: \(user[email])") } 
    • Yes, the point is, I cannot add to an empty database, where there are no records at all. But it does not work. - Alexander
    • @Alexander what a mistake? - VAndrJ

    I may be wrong, but instead of let users = Table ("users")

    try to use

    var users = Table ("users")

    • If you are not sure, try creating a minimal code sample. - 0xdb