使用 https://cocoapods.org/pods/SQLite.swift 附加两个 sqlite 数据库时出现问题

Problems attaching two sqlite databases with https://cocoapods.org/pods/SQLite.swift

我正在使用 stephencelis/SQLite.swift 并尝试在运行时附加 2 个数据库:

附加数据库\'(databasePath.Local)\' AS LOCAL_USER_DB;

//
//  DatabaseWrapper.swift
// ...
//

import UIKit
import SQLite

class DatabaseWrapper {

    // MARK: - Constants

    struct databaseName {
        static let Interface: String = "app_interface_sqlite3_db.db3"
        static let Local: String = "app_local_sqlite3_db_local.db3"
    }
    struct databasePath {
        static let path = NSSearchPathForDirectoriesInDomains(
            .documentDirectory, .userDomainMask, true
        ).first!
        static let Interface = "\(path)/\(databaseName.Interface)"
        static let Local = "\(path)//\(databaseName.Local)"
        static let Interface_Bundle: String = Bundle.main.path(forResource: "app_interface_sqlite3_db", ofType: "db3") ?? ""
        static let Local_Bundle: String = Bundle.main.path(forResource: "app_local_sqlite3_db_local", ofType: "db3") ?? ""
    }

    // MARK: Copy Databases

    public static func copyDatabasesIfNeeded() {
        copyDatabaseIfNeeded(databaseName: databaseName.Interface)
        copyDatabaseIfNeeded(databaseName: databaseName.Local)
    }

    public static func copyDatabaseIfNeeded(databaseName: String) {

        print("PATH: \(databasePath.Interface)")

        // Move database file from bundle to documents folder
        let fileManager = FileManager.default
        let documentsUrl = fileManager.urls(for: .documentDirectory,
                                            in: .userDomainMask)

        guard documentsUrl.count != 0 else {
            return // Could not find documents URL
        }

        let finalDatabaseURL = documentsUrl.first!.appendingPathComponent(databaseName)

        if !( (try? finalDatabaseURL.checkResourceIsReachable()) ?? false) {
            print("DB does not exist in documents folder")

            let documentsURL = Bundle.main.resourceURL?.appendingPathComponent(databaseName)

            do {
                try fileManager.copyItem(atPath: (documentsURL?.path)!, toPath: finalDatabaseURL.path)
            } catch let error as NSError {
                print("Couldn't copy file to final location! Error:\(error.description)")
            }

        } else {
            print("Database file found at path: \(finalDatabaseURL.path)")
        }
    }

    // MARK: - Attach Local User Database TESTS
    public static func attachDatabase() {

        do {
            // if the database connection works

            let db = try Connection(databasePath.Interface);

            let attachStr = "ATTACH DATABASE \'\(databasePath.Local)\' AS LOCAL_USER_DB;"

            try db.execute(attachStr)

        } catch {
            // handle error
            print("Unexpected error: \(error).")
        }

    }

    public static func checkIfDatabase2IsAttached() -> Bool {

        var isAllreadyAttached = false

        do {
            // if the database connection works

            let db = try Connection(databasePath.Interface);

            // seq, name, file
            var row_counter = 0
            for row in try db.prepare("PRAGMA database_list;") {
                print("\n\n----------\row: \(row)\n----------\n\n")
                row_counter += 1
            }
            isAllreadyAttached = (row_counter == 2) ? true : false

        } catch {
            // handle error
            print("Unexpected error: \(error).")
        }

        return isAllreadyAttached
    }

    public static func testIfDatabaseWasAttached() {

        do {
            // if the database connection works

            let db = try Connection(databasePath.Interface);

            for row in try db.prepare("SELECT * FROM LOCAL_USER_DB.users;") {
                print("row: \(row)")
            }

        } catch {
            // handle error
            print("Unexpected error: \(error).")
        }

    }

    // ...

}

当我打电话时

// Copy both databases if needed
        DatabaseWrapper.copyDatabasesIfNeeded()
        DatabaseWrapper.attachDatabase()

        if (DatabaseWrapper.checkIfDatabase2IsAttached()) {
            print("ATTACHED")
        } else {
            print("NOT ATTACHED YET")
        }

        DatabaseWrapper.testIfDatabaseWasAttached()

很遗憾,我没有工作,也没有收到任何错误消息。

在 consule 中我得到了日志:

---------- ow: [Optional(0), Optional("main"), Optional("..../Developer/CoreSimulator/Devices/F93B5F0C-87D0-439C-ACB9-B1C6B5B7BE60/data/Containers/Data/Application/BB9587A1-2512-4003-ABC0-8AB1A7F6B4AF/Documents/app_interface_sqlite3_db.db3")]

NOT ATTACHED YET Unexpected error: no such table: LOCAL_USER_DB.users (code: 1).

有没有人知道,以前做过这个或者有人帮助我?

提前致谢。

据我所知,该问题与 testIfDatabaseWasAttached() 有关。您确定您的 table 的名字是 LOCAL_USER_DB.users 吗?您可以使用此代码 - 我已经检查并从 table LOCAL_USER_DB.users 获取用户(table 的名称很奇怪,但还可以)。

public static func testIfDatabaseWasAttached() {
    do {

        let db = try Connection(databasePath.Interface);
        for element in try db.prepare(Table("LOCAL_USER_DB.users")) {
            print(element)
        }
    } catch {
        // handle error
        print("Unexpected error: \(error).")
    }
}

您应该确定您的 table 名称为 LOCAL_USER_DB.users 并且错误说明了您的问题。这个数据库结构:

PS 当我 运行 你的代码时 - 在 [.documents] 中创建了 2 个数据库,但它们完全是空的(根本没有数据,只有两个数据库)。我建议检查流程逻辑

也许这对遇到同样问题的人有所帮助。这是临时的 "solution"(下一步):

发现: 它在规划清单上,但尚未实施。很高兴知道,但很遗憾。自从 Stephen Celis 项目成为 Swift.

的最佳 sqlite 以来

解决方案是:

  1. 为项目做贡献。查看讨论:https://github.com/stephencelis/SQLite.swift/issues/30
  2. 编写您自己的包装器。这里 discribed solution worked. For further inspiration see also: Accessing an SQLite Database in Swift

为了让我的项目达到 运行:首先我选择 2。如果可行,我计划 post 它是为了获得 1 的灵感。