Untitled

mail@pastecode.io avatar
unknown
swift
a year ago
1.1 kB
16
Indexable
Never
  func openDatabase(inMemory: Bool = false) {
    NSLog("start openDatabase")
    var rc: Int32

    if inMemory {
      rc = sqlite3_open(":memory:", &db)
    } else {
      let manager = FileManager.default
      do {
        let databaseUrlDirectory = try manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)

        let databaseUrl = databaseUrlDirectory.appendingPathComponent("database.db")
        NSLog("database path: \(databaseUrl.path)")
        rc = sqlite3_open_v2(databaseUrl.path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nil)
      } catch {
        NSLog("error while trying to open the database path: \(error)")
        return
      }
    }

    if rc != SQLITE_OK {
      let errmsg = String(cString: sqlite3_errmsg(db))
      NSLog("Error opening database: \(errmsg)")
      return
    }

    rc = sqlite3_key(db, password, Int32(password.utf8CString.count))
    if rc != SQLITE_OK {
      let errmsg = String(cString: sqlite3_errmsg(db))
      NSLog("Error setting key: \(errmsg)")
      return
    }
    NSLog("✅ Database opened")
  }