Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ open class SQLiteEngine: Engine {
try db.execute(sql: "PRAGMA foreign_keys = ON")
}

try createParentDirectory(ofDatabaseAt: path)
let queue = try retryLockedDatabaseWork {
try DatabaseQueue(path: path, configuration: configuration)
}
Expand Down Expand Up @@ -147,6 +148,16 @@ open class SQLiteEngine: Engine {
0.05 * Double(attempt + 1)
}

/// Creates the directory that will hold the database file, if it is missing. SQLite does not create
/// directories, so opening the database fails without it. The Documents directory exists in an app,
/// but not, for example, when Swift package tests run on the iOS Simulator without a host app.
static func createParentDirectory(ofDatabaseAt path: String) throws {
let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
if !FileManager.default.fileExists(atPath: directory.path) {
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
}

private static func fileURL(for path: String) -> URL {
FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
.appendingPathComponent(sqliteFileName(for: path))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,24 @@ class UnitTests: XCTestCase {
XCTAssertNotNil(original.completionHandler)
}

/// The directory of the database file is created when it is missing, so the database can be opened.
func testCreateParentDirectoryOfDatabase() throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("aware_dir_test_\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(at: root) }
let path = root.appendingPathComponent("nested/Documents/a.sqlite").path
XCTAssertFalse(FileManager.default.fileExists(atPath: root.path))

try SQLiteEngine.createParentDirectory(ofDatabaseAt: path)
var isDirectory: ObjCBool = false
XCTAssertTrue(FileManager.default.fileExists(atPath: root.appendingPathComponent("nested/Documents").path,
isDirectory: &isDirectory))
XCTAssertTrue(isDirectory.boolValue)
XCTAssertNoThrow(try DatabaseQueue(path: path))

// An existing directory is left as it is
XCTAssertNoThrow(try SQLiteEngine.createParentDirectory(ofDatabaseAt: path))
}

/// Makes a SQLite engine with an empty table `A` in its own database file.
private func makeEmptySQLiteEngine(_ dbPath: String) -> SQLiteEngine? {
let sensor = AwareSensor()
Expand Down
Loading