使用事务插入会引发错误Sqlite.swift [英] Using transactions to insert is throwing errors Sqlite.swift

查看:244
本文介绍了使用事务插入会引发错误Sqlite.swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经这样创建了一个数据库类:

I have created a Database class as so:

class Database {
    static let instance = Database()
    private let categories = Table("Category")
    private var db: Connection?

    let cat_id = Expression<String>("id")
    let cat_name = Expression<String>("name")


    private init() {
        let path = NSSearchPathForDirectoriesInDomains(
            .documentDirectory, .userDomainMask, true
            ).first!
        do {
            db = try Connection("\(path)/SalesPresenterDatabase.sqlite3")
            createTable()
        } catch {
            print("error")
        }
    }
    func createTable() {
        do{
            try self.db!.run(self.categories.create(ifNotExists: true) { table in
                table.column(self.cat_id)
                table.column(self.cat_name)
            })
        }catch{
             print("error")
        }
    }

    func addRow(table: DBTableNames, object: [Any]) -> Int64? {
      do {
         try self.db!.transaction() {
            for obj in object{
                if table.rawValue == DBTableNames.Category.rawValue{
                    let cats : CategoryObject = obj as! CategoryObject
                    let insert = self.categories.insert(self.cat_id <- cats.id,
                                                        self.cat_name <- cats.name)
                    try self.db!.run(insert)

                }
             }
          }
        }catch{
           print("Insert failed \(error)")
           return -1
        }
        return 1
         }
}

然后我通过运行以下命令继续调用我的代码以添加一行:

I then go on to call my code to add a row by running the following:

    let returnValue = Database.instance.addRow(table: DBTableNames(rawValue: entity)!,
                                               object: databaseObject)

我的问题是它总是抛出一个错误:

The problem I have is that it always throws an error saying:

插入失败操作无法完成. (SQLite.Result 错误0.)且已满:无法回滚-没有活动处于活动状态(代码: 1)

Insert failed The operation couldn’t be completed. (SQLite.Result error 0.) and full: cannot rollback - no transaction is active (code: 1)

如果再次出现此错误,我的Mac将会退出窗口!

If I see this error one more time my Mac will be going out of the window!

整个操作都在后台线程中进行,但我也尝试了以下操作:

The whole operation is in a background thread but I have tried the following as well:

    DispatchQueue.main.async{
    let returnValue = Database.instance.addRow(table: DBTableNames(rawValue: entity)!,
                                                   object: databaseObject)
}

它没有用.这没有意义,因为我也尝试在事务中创建表,并且效果很好.

It didn't work. It doesn't make sense as I also tried creating the tables in a transaction and that worked perfectly.

任何帮助将不胜感激!

推荐答案

您的func createTable()func addRow()方法不是线程安全的.多个线程可以同时访问它.

Your func createTable() and func addRow() methods are not thread safe. Multiple threads can access it at the same time.

在Singleton类中创建一个专用串行DispatchQueue,并通过此串行队列执行上述功能.这样可以防止同时从多个线程访问数据库,并且串行队列将对并发任务进行排队.

Create a private serial DispatchQueue inside your Singleton class and do above functions through this serial queue. This will prevent accessing the database from several threads at the same time, and serial queue will queue concurrent tasks.

这篇关于使用事务插入会引发错误Sqlite.swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆