Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor SQLiteConnection.swift to support readonly mode for file-bas… #74

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
18 changes: 14 additions & 4 deletions Sources/SQLiteNIO/SQLiteConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public final class SQLiteConnection: SQLiteDatabase, Sendable {
///
/// File-based databases persist as long as the files representing them on disk does, and can be opened
/// multiple times within the same process or even by multiple processes if configured properly.
case file(path: String)
case file(path: String, readonly: Bool = false)
}

/// Return the version of the embedded libsqlite3 as a 32-bit integer value.
Expand Down Expand Up @@ -149,16 +149,26 @@ public final class SQLiteConnection: SQLiteDatabase, Sendable {
eventLoop: any EventLoop
) throws -> SQLiteConnection {
let path: String
var readonlyMode = false

switch storage {
case .memory: path = ":memory:"
case .file(let file): path = file
case .file(let file, let readonly):
path = file
readonlyMode = readonly
}

var handle: OpaquePointer?
let openOptions = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_URI | SQLITE_OPEN_EXRESCODE
var openOptions =
readonlyMode ? SQLITE_OPEN_READONLY : SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE
openOptions |=
SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_URI
| SQLITE_OPEN_EXRESCODE
let openRet = sqlite_nio_sqlite3_open_v2(path, &handle, openOptions, nil)
guard openRet == SQLITE_OK else {
throw SQLiteError(reason: .init(statusCode: openRet), message: "Failed to open to SQLite database at \(path)")
throw SQLiteError(
reason: .init(statusCode: openRet),
message: "Failed to open to SQLite database at \(path)")
}

let busyRet = sqlite_nio_sqlite3_busy_handler(handle, { _, _ in 1 }, nil)
Expand Down
Loading