DataRaft swift package

This commit is contained in:
2025-05-18 17:47:22 +03:00
parent d64c6b2ef2
commit 1b2cdaf23e
23 changed files with 1862 additions and 0 deletions

View File

@@ -0,0 +1,251 @@
import Foundation
import DataLiteCore
import DataLiteC
/// A base class for services that operate on a database connection.
///
/// `DatabaseService` provides a shared interface for executing operations on a `Connection`,
/// with support for transaction handling and optional request serialization.
///
/// Subclasses can use this base to coordinate safe, synchronous access to the database
/// without duplicating concurrency or transaction logic.
///
/// For example, you can define a custom service for managing notes:
///
/// ```swift
/// final class NoteService: DatabaseService {
/// func insertNote(_ text: String) throws {
/// try perform { connection in
/// let stmt = try connection.prepare(
/// sql: "INSERT INTO notes (text) VALUES (?)"
/// )
/// try stmt.bind(text, at: 0)
/// try stmt.step()
/// }
/// }
///
/// func fetchNotes() throws -> [String] {
/// try perform { connection in
/// let stmt = try connection.prepare(sql: "SELECT text FROM notes")
/// var result: [String] = []
/// while try stmt.step() {
/// if let text: String = stmt.columnValue(at: 0) {
/// result.append(text)
/// }
/// }
/// return result
/// }
/// }
/// }
///
/// let connection = try Connection(location: .inMemory, options: .readwrite)
/// let service = NoteService(connection: connection)
///
/// try service.insertNote("Hello, world!")
/// let notes = try service.fetchNotes()
/// print(notes) // ["Hello, world!"]
/// ```
///
/// This approach allows you to build reusable service layers on top of a safe, transactional,
/// and serialized foundation.
open class DatabaseService: DatabaseServiceProtocol {
/// A closure that provides a new database connection when invoked.
///
/// `ConnectionProvider` is used to defer the creation of a `Connection` instance
/// until it is actually needed. It can throw errors if the connection cannot be
/// established or configured correctly.
///
/// - Returns: A valid `Connection` instance.
/// - Throws: Any error encountered while opening or configuring the connection.
public typealias ConnectionProvider = () throws -> Connection
// MARK: - Properties
private let provider: ConnectionProvider
private var connection: Connection
private let queue: DispatchQueue
private let queueKey = DispatchSpecificKey<Void>()
/// The object that provides the encryption key for the database connection.
///
/// When this property is set, the service attempts to retrieve an encryption key from the
/// provider and apply it to the current database connection. This operation is performed
/// synchronously on the services internal queue to ensure thread safety.
///
/// If an error occurs during key retrieval or application, the service notifies the provider
/// by calling `databaseService(_:didReceive:)`.
///
/// This enables external management of encryption keys, including features such as key rotation,
/// user-scoped encryption, or error handling delegation.
///
/// - Important: The service does not retry failed key applications. Ensure the provider is
/// correctly configured and able to supply a valid key when needed.
public weak var keyProvider: DatabaseServiceKeyProvider? {
didSet {
perform { connection in
do {
if let key = try keyProvider?.databaseServiceKey(self) {
try connection.apply(key)
}
} catch {
keyProvider?.databaseService(self, didReceive: error)
}
}
}
}
// MARK: - Inits
/// Creates a new `DatabaseService` using the given connection provider and optional queue.
///
/// This convenience initializer wraps the provided autoclosure in a `ConnectionProvider`
/// and delegates to the designated initializer. It is useful when passing a simple
/// connection expression.
///
/// - Parameters:
/// - provider: A closure that returns a `Connection` instance and may throw.
/// - queue: An optional dispatch queue used as a target for internal serialization. If `nil`,
/// a default serial queue with `.utility` QoS is created internally.
/// - Throws: Rethrows any error thrown by the connection provider.
public convenience init(
connection provider: @escaping @autoclosure ConnectionProvider,
queue: DispatchQueue? = nil
) rethrows {
try self.init(provider: provider, queue: queue)
}
/// Creates a new `DatabaseService` with the specified connection provider and dispatch queue.
///
/// This initializer immediately invokes the `provider` closure to establish the initial database
/// connection. An internal serial queue is created for synchronizing database access. If a
/// `queue` is provided, it is set as the target of the internal queue, allowing you to control
/// scheduling and quality of service.
///
/// - Parameters:
/// - provider: A closure that returns a new `Connection` instance. May throw on failure.
/// - queue: An optional dispatch queue to target for internal serialization. If `nil`,
/// a dedicated serial queue with `.utility` QoS is created.
/// - Throws: Any error thrown by the `provider` during initial connection setup.
public init(
provider: @escaping ConnectionProvider,
queue: DispatchQueue? = nil
) rethrows {
self.provider = provider
self.connection = try provider()
self.queue = .init(for: Self.self, qos: .utility)
self.queue.setSpecific(key: queueKey, value: ())
if let queue = queue {
self.queue.setTarget(queue: queue)
}
}
// MARK: - Methods
/// Re-establishes the database connection using the stored connection provider.
///
/// This method creates a new `Connection` instance by invoking the original provider. If a
/// `keyProvider` is set, the method attempts to retrieve and apply an encryption key to the new
/// connection. The new connection replaces the existing one.
///
/// The operation is executed synchronously on the internal dispatch queue via `perform(_:)`
/// to ensure thread safety.
///
/// - Throws: Any error thrown during connection creation or while retrieving or applying the
/// encryption key.
public func reconnect() throws {
try perform { _ in
let connection = try provider()
if let key = try keyProvider?.databaseServiceKey(self) {
try connection.apply(key)
}
self.connection = connection
}
}
/// Executes the given closure using the active database connection.
///
/// This method ensures thread-safe access to the underlying `Connection` by synchronizing
/// execution on an internal serial dispatch queue. If the call is already on that queue, the
/// closure is executed directly to avoid unnecessary dispatching.
///
/// If the closure throws a `SQLiteError` with code `SQLITE_NOTADB` (e.g., when the database file
/// is corrupted or invalid), the service attempts to re-establish the connection by calling
/// ``reconnect()``. The error is still rethrown after reconnection.
///
/// - Parameter closure: A closure that takes the active connection and returns a result.
/// - Returns: The value returned by the closure.
/// - Throws: Any error thrown by the closure or during reconnection logic.
public func perform<T>(_ closure: Perform<T>) rethrows -> T {
do {
switch DispatchQueue.getSpecific(key: queueKey) {
case .none: return try queue.asyncAndWait { try closure(connection) }
case .some: return try closure(connection)
}
} catch {
switch error {
case let error as Connection.Error:
if error.code == SQLITE_NOTADB {
try reconnect()
}
fallthrough
default:
throw error
}
}
}
/// Executes a closure inside a transaction if the connection is in autocommit mode.
///
/// If the current connection is in autocommit mode, a new transaction of the specified type
/// is started, and the closure is executed within it. If the closure completes successfully,
/// the transaction is committed. If an error is thrown, the transaction is rolled back.
///
/// If the thrown error is a `SQLiteError` with code `SQLITE_NOTADB`, the service attempts to
/// reconnect and retries the entire transaction block exactly once.
///
/// If the connection is already within a transaction (i.e., not in autocommit mode),
/// the closure is executed directly without starting a new transaction.
///
/// - Parameters:
/// - transaction: The type of transaction to begin (e.g., `deferred`, `immediate`, `exclusive`).
/// - closure: A closure that takes the active connection and returns a result.
/// - Returns: The value returned by the closure.
/// - Throws: Any error thrown by the closure, transaction control statements,
/// or reconnect logic.
public func perform<T>(
in transaction: TransactionType,
closure: Perform<T>
) rethrows -> T {
if connection.isAutocommit {
try perform { connection in
do {
try connection.beginTransaction(transaction)
let result = try closure(connection)
try connection.commitTransaction()
return result
} catch {
try connection.rollbackTransaction()
guard let error = error as? Connection.Error,
error.code == SQLITE_NOTADB
else { throw error }
try reconnect()
return try perform { connection in
do {
try connection.beginTransaction(transaction)
let result = try closure(connection)
try connection.commitTransaction()
return result
} catch {
try connection.rollbackTransaction()
throw error
}
}
}
}
} else {
try perform(closure)
}
}
}

View File

@@ -0,0 +1,138 @@
import Foundation
import DataLiteCore
/// A service responsible for managing and applying database migrations in a versioned manner.
///
/// `MigrationService` manages a collection of migrations identified by versions and script URLs,
/// and applies them sequentially to update the database schema. It ensures that each migration
/// is applied only once, and in the correct version order based on the current database version.
///
/// This service is generic over a `VersionStorage` implementation that handles storing and
/// retrieving the current database version. Migrations must have unique versions and script URLs
/// to prevent duplication.
///
/// ```swift
/// let connection = try Connection(location: .inMemory, options: .readwrite)
/// let storage = UserVersionStorage<BitPackVersion>()
/// let service = MigrationService(storage: storage, connection: connection)
///
/// try service.add(Migration(version: "1.0.0", byResource: "v_1_0_0.sql")!)
/// try service.add(Migration(version: "1.0.1", byResource: "v_1_0_1.sql")!)
/// try service.add(Migration(version: "1.1.0", byResource: "v_1_1_0.sql")!)
/// try service.add(Migration(version: "1.2.0", byResource: "v_1_2_0.sql")!)
///
/// try service.migrate()
/// ```
///
/// ### Custom Versions and Storage
///
/// You can customize versioning by providing your own `Version` type conforming to
/// ``VersionRepresentable``, which supports comparison, hashing, and identity checks.
///
/// The storage backend (`VersionStorage`) defines how the version is persisted, such as
/// in a pragma, table, or metadata.
///
/// This allows using semantic versions, integers, or other schemes, and storing them
/// in custom places.
public final class MigrationService<Service: DatabaseServiceProtocol, Storage: VersionStorage> {
/// The version type used by this migration service, derived from the storage type.
public typealias Version = Storage.Version
/// Errors that may occur during migration registration or execution.
public enum Error: Swift.Error {
/// A migration with the same version or script URL was already registered.
case duplicateMigration(Migration<Version>)
/// Migration execution failed, with optional reference to the failed migration.
case migrationFailed(Migration<Version>?, Swift.Error)
/// The migration script is empty.
case emptyMigrationScript(Migration<Version>)
}
// MARK: - Properties
private let service: Service
private let storage: Storage
private var migrations = Set<Migration<Version>>()
/// The encryption key provider delegated to the underlying database service.
public weak var keyProvider: DatabaseServiceKeyProvider? {
get { service.keyProvider }
set { service.keyProvider = newValue }
}
// MARK: - Inits
/// Creates a new migration service with the given database service and version storage.
///
/// - Parameters:
/// - service: The database service used to perform migrations.
/// - storage: The version storage implementation used to track the current schema version.
public init(
service: Service,
storage: Storage
) {
self.service = service
self.storage = storage
}
// MARK: - Migration Management
/// Registers a new migration.
///
/// Ensures that no other migration with the same version or script URL has been registered.
///
/// - Parameter migration: The migration to register.
/// - Throws: ``Error/duplicateMigration(_:)`` if the migration version or script URL duplicates an existing one.
public func add(_ migration: Migration<Version>) throws {
guard !migrations.contains(where: {
$0.version == migration.version
|| $0.scriptURL == migration.scriptURL
}) else {
throw Error.duplicateMigration(migration)
}
migrations.insert(migration)
}
/// Executes all pending migrations in ascending version order.
///
/// This method retrieves the current schema version from the storage, filters and sorts
/// pending migrations, executes each migration script within a single exclusive transaction,
/// and updates the schema version on success.
///
/// If a migration script is empty or a migration fails, the process aborts and rolls back changes.
///
/// - Throws: ``Error/migrationFailed(_:_:)`` if a migration script fails or if updating the version fails.
public func migrate() throws {
do {
try service.perform(in: .exclusive) { connection in
try storage.prepare(connection)
let version = try storage.getVersion(connection)
let migrations = migrations
.filter { $0.version > version }
.sorted { $0.version < $1.version }
for migration in migrations {
let script = try migration.script
guard !script.isEmpty else {
throw Error.emptyMigrationScript(migration)
}
do {
try connection.execute(sql: script)
} catch {
throw Error.migrationFailed(migration, error)
}
}
if let version = migrations.last?.version {
try storage.setVersion(connection, version)
}
}
} catch let error as Error {
throw error
} catch {
throw Error.migrationFailed(nil, error)
}
}
}

View File

@@ -0,0 +1,111 @@
import Foundation
import DataLiteCore
import DataLiteCoder
/// A database service that provides built-in row encoding and decoding.
///
/// `RowDatabaseService` extends `DatabaseService` by adding support for
/// value serialization using `RowEncoder` and deserialization using `RowDecoder`.
///
/// This enables subclasses to perform type-safe operations on models
/// encoded from or decoded into SQLite row representations.
///
/// For example, a concrete service might define model-aware fetch or insert methods:
///
/// ```swift
/// struct User: Codable {
/// let id: Int
/// let name: String
/// }
///
/// final class UserService: RowDatabaseService {
/// func fetchUsers() throws -> [User] {
/// try perform(in: .deferred) { connection in
/// let stmt = try connection.prepare(sql: "SELECT * FROM users")
/// let rows = try stmt.execute()
/// return try decoder.decode([User].self, from: rows)
/// }
/// }
///
/// func insertUser(_ user: User) throws {
/// try perform(in: .deferred) { connection in
/// let row = try encoder.encode(user)
/// let columns = row.columns.joined(separator: ", ")
/// let parameters = row.namedParameters.joined(separator: ", ")
/// let stmt = try connection.prepare(
/// sql: "INSERT INTO users (\(columns)) VALUES (\(parameters))"
/// )
/// try stmt.execute(rows: [row])
/// }
/// }
/// }
/// ```
///
/// `RowDatabaseService` encourages a reusable, type-safe pattern for
/// model-based interaction with SQLite while preserving thread safety
/// and transactional integrity.
open class RowDatabaseService: DatabaseService, RowDatabaseServiceProtocol {
// MARK: - Properties
/// The encoder used to serialize values into row representations.
public let encoder: RowEncoder
/// The decoder used to deserialize row values into strongly typed models.
public let decoder: RowDecoder
// MARK: - Inits
/// Creates a new `RowDatabaseService`.
///
/// This initializer accepts a closure that supplies the database connection. If no encoder
/// or decoder is provided, default instances are used.
///
/// - Parameters:
/// - provider: A closure that returns a `Connection` instance. May throw an error.
/// - encoder: The encoder used to serialize models into SQLite-compatible rows.
/// Defaults to a new encoder.
/// - decoder: The decoder used to deserialize SQLite rows into typed models.
/// Defaults to a new decoder.
/// - queue: An optional dispatch queue used for serialization. If `nil`, an internal
/// serial queue with `.utility` QoS is created.
/// - Throws: Any error thrown by the connection provider.
public convenience init(
connection provider: @escaping @autoclosure ConnectionProvider,
encoder: RowEncoder = RowEncoder(),
decoder: RowDecoder = RowDecoder(),
queue: DispatchQueue? = nil
) rethrows {
try self.init(
provider: provider,
encoder: encoder,
decoder: decoder,
queue: queue
)
}
/// Designated initializer for `RowDatabaseService`.
///
/// Initializes a new instance with the specified connection provider, encoder, decoder,
/// and an optional dispatch queue for synchronization.
///
/// - Parameters:
/// - provider: A closure that returns a `Connection` instance. May throw an error.
/// - encoder: A custom `RowEncoder` used for encoding model data. Defaults to a new encoder.
/// - decoder: A custom `RowDecoder` used for decoding database rows. Defaults to a new decoder.
/// - queue: An optional dispatch queue for serializing access to the database connection.
/// If `nil`, a default internal serial queue with `.utility` QoS is used.
/// - Throws: Any error thrown by the connection provider.
public init(
provider: @escaping ConnectionProvider,
encoder: RowEncoder = RowEncoder(),
decoder: RowDecoder = RowDecoder(),
queue: DispatchQueue? = nil
) rethrows {
self.encoder = encoder
self.decoder = decoder
try super.init(
provider: provider,
queue: queue
)
}
}

View File

@@ -0,0 +1,66 @@
import Foundation
import DataLiteCore
/// A database version storage that uses the `user_version` field.
///
/// This class implements ``VersionStorage`` by storing version information
/// in the SQLite `PRAGMA user_version` field. It provides a lightweight,
/// type-safe way to persist versioning data in a database.
///
/// The generic `Version` type must conform to both ``VersionRepresentable``
/// and `RawRepresentable`, where `RawValue == UInt32`. This allows
/// converting between stored integer values and semantic version types
/// defined by the application.
public final class UserVersionStorage<
Version: VersionRepresentable & RawRepresentable
>: VersionStorage where Version.RawValue == UInt32 {
/// Errors related to reading or decoding the version.
public enum Error: Swift.Error {
/// The stored `user_version` could not be decoded into a valid `Version` case.
case invalidStoredVersion(UInt32)
}
// MARK: - Inits
/// Creates a new user version storage instance.
public init() {}
// MARK: - Methods
/// Returns the current version stored in the `user_version` field.
///
/// This method reads the `PRAGMA user_version` value and attempts to
/// decode it into a valid `Version` value. If the stored value is not
/// recognized, it throws an error.
///
/// - Parameter connection: The database connection.
/// - Returns: A decoded version value of type `Version`.
/// - Throws: ``Error/invalidStoredVersion(_:)`` if the stored value
/// cannot be mapped to a valid `Version` instance.
public func getVersion(
_ connection: Connection
) throws -> Version {
let raw = UInt32(bitPattern: connection.userVersion)
guard let version = Version(rawValue: raw) else {
throw Error.invalidStoredVersion(raw)
}
return version
}
/// Stores the given version in the `user_version` field.
///
/// This method updates the `PRAGMA user_version` field
/// with the raw `UInt32` value of the provided `Version`.
///
/// - Parameters:
/// - connection: The database connection.
/// - version: The version to store.
public func setVersion(
_ connection: Connection,
_ version: Version
) throws {
connection.userVersion = .init(
bitPattern: version.rawValue
)
}
}