DittoStore

public class DittoStore
extension DittoStore: DittoQueryExecuting

DittoStore provides access to DittoCollections and a write transaction API.

  • Returns a DittoCollection with the provided name.

    Declaration

    Swift

    public subscript(collectionName: DittoCollectionName) -> DittoCollection { get }

    Parameters

    collectionName

    The name of the collection.

    Return Value

    A DittoCollection.

  • Returns a DittoCollection with the provided name. A collection name is valid if:

    • its length is less than 100
    • it is not empty
    • it does not contain the char ‘\0’
    • it does not begin with “$TS_”

    Declaration

    Swift

    public func collection(_ name: DittoCollectionName) -> DittoCollection

    Parameters

    name

    The name of the collection.

    Return Value

    A DittoCollection.

  • Returns a list of the names of collections in the store.

    Declaration

    Swift

    public func collectionNames() -> [DittoCollectionName]

    Return Value

    A list of collection names found in the store.

  • Returns an object that lets you fetch or observe the collections in the store.

    Declaration

    Swift

    public func collections() -> DittoPendingCollectionsOperation

    Return Value

    An object that lets you fetch or observe the collections in the store.

  • Returns a hash representing the current version of the given queries. When a document matching such queries gets mutated, the hash will change as well.

    Please note that the hash depends on how queries are constructed, so you should make sure to always compare hashes generated with the same set of queries.

    Declaration

    Swift

    public func queriesHash(queries: [DittoLiveQuery]) -> UInt

    Parameters

    queries

    A list of DittoLiveQuery objects that you want to get the hash for.

    Return Value

    A hash representing the current version of the given queries.

  • Returns a sequence of English words representing the current version of the given queries. When a document matching such queries gets mutated, the words will change as well.

    Please note that the resulting sequence of words depends on how queries are constructed, so you should make sure to always compare hashes generated with the same set of queries.

    Declaration

    Swift

    public func queriesHashMnemonic(queries: [DittoLiveQuery]) -> String

    Parameters

    queries

    A list of DittoLiveQuery objects that you want to get the mnemonic hash for.

    Return Value

    A string representing the current version of the given queries.

  • Allows you to group multiple operations together that affect multiple documents, potentially across multiple collections.

    Declaration

    Swift

    @discardableResult
    public func write(
        _ block: @escaping (DittoWriteTransaction) -> Void
    ) -> [DittoWriteTransactionResult]

    Parameters

    block

    A closure that provides access to a write transaction object that can be used to perform operations on the store.

    Return Value

    A list of DittoWriteTransactionResults. There is a result for each operation performed as part of the write transaction.

Managing Store Observers

  • Returns all currently active store observers.

    Declaration

    Swift

    public private(set) var observers: Set<DittoStoreObserver> { get }
  • Convenience method, same as registerObserver(query:arguments:deliverOn:storeObservationHandlerWithSignalNext:) where signalNext is called automatically after the storeObservationHandler finishes.

    Declaration

    Swift

    @discardableResult
    public func registerObserver(
        query: String,
        arguments: Dictionary<String, Any?>? = nil,
        deliverOn queue: DispatchQueue = .main,
        handler: @escaping DittoStoreObservationHandler
    ) throws -> DittoStoreObserver
  • Installs and returns a store observer for a query, configuring Ditto to trigger the passed in change handler whenever documents in the local store change such that the result of the matching query changes. The passed in query must be a SELECT query, otherwise a store error with queryNotSupported reason is thrown.

    Use a DittoDiffer to calculate a diff between subsequent results delivered to the change handler.

    Throws

    DittoSwiftError > .storeError(.queryInvalid) if query string is not valid DQL.

    Throws

    DittoSwiftError > .storeError(.queryArgumentsInvalid) if arguments dictionary is not valid (contains unsupported types).

    Throws

    DittoSwiftError > .storeError(.queryNotSupported) if query is not a SELECT query.

    Throws

    May throw other DittoSwiftErrors.

    Declaration

    Swift

    @discardableResult
    public func registerObserver(
        query: String,
        arguments: Dictionary<String, Any?>? = nil,
        deliverOn queue: DispatchQueue = .main,
        handlerWithSignalNext: @escaping DittoStoreObservationHandlerWithSignalNext
    ) throws -> DittoStoreObserver

    Return Value

    An active DittoStoreObserver for the passed in query and arguments. You’ll have to keep it to be able to cancel the observation. Otherwise it will remain active until the owning Ditto object goes out of scope.

Working with Transactions

  • Executes multiple DQL queries within a single atomic transaction.

    This ensures that either all statements are executed successfully, or none are executed at all, providing strong consistency guarantees. Certain mesh configurations may impose limitations on these guarantees. For more details, refer to the Ditto documentation. Transactions are initiated as read-write transactions by default, and only a single read-write transaction is being executed at any given time. Any other read-write transaction started concurrently will wait until the current transaction has been committed or rolled back. Therefore, it is crucial to make sure a transaction finishes as early as possible so other read-write transactions aren’t blocked for a long time.

    A transaction can also be configured to be read-only using the isReadOnly parameter. Multiple read-only transactions can be executed concurrently. However, executing a mutating DQL statement in a read-only transaction will throw an error.

    If errors occur in an execute() call within a transaction block and the error is caught and handled within the block, the transaction will continue to run and not be rolled back. When an error is thrown at any point inside the transaction block or while committing the transaction, the transaction is implicitly rolled back and the error is propagated up to the caller.

    When a Ditto instance goes out of scope, it will drive all pending transactions to completion before being shut down.

    Warning

    Calling ditto.store.execute() or creating a nested transaction within a transaction may lead to a deadlock.

    For a complete guide on transactions, please refer to the Ditto documentation.

    Throws

    DittoSwiftError > .storeError(.transactionReadOnly) if the transaction is read-only but a mutating query was executed.

    Throws

    May throw other DittoSwiftErrors.

    Throws

    Will rethrow any error thrown within the scope closure.

    See also

    DittoTransaction

    Declaration

    Swift

    @discardableResult
    public func transaction(
        hint: String? = nil,
        isReadOnly: Bool = false,
        with scope: ((_ transaction: DittoTransaction) async throws -> DittoTransactionCompletionAction)
    ) async throws -> DittoTransactionCompletionAction

    Parameters

    hint

    A hint for the transaction, which is logged. Mostly useful for debugging and testing.

    isReadOnly

    A flag indicating whether the transaction is read-only.

    scope

    A closure that provides access to a transaction object that can be used to execute DQL queries.

    Return Value

    transaction action that was taken (.commit or .rollback).

  • Convenience method, same as transaction(hint:isReadOnly:with:), but propagates the return value of the scope rather than the completion action.

    The transaction is committed implicitly upon return and rolled back if an error is thrown.

    Declaration

    Swift

    public func transaction<T>(
        hint: String? = nil,
        isReadOnly: Bool = false,
        with scope: ((_ transaction: DittoTransaction) async throws -> T)
    ) async throws -> T

Working with Attachments

  • Creates a new attachment, which can then be inserted into a document.

    The file residing at the provided path will be copied into Ditto’s store. The DittoAttachment object that is returned is what you can then use to insert an attachment into a document.

    You can provide metadata about the attachment, which will be replicated to other peers alongside the file attachment.

    Below is a snippet to show how you can use the newAttachment() functionality to insert an attachment into a document.

    if let attachment = try await store.newAttachment("/path/to/my/file.zip") {
        let document: [String: Any] = ["some": "string", "myAttachment": attachment]
        let insertQueryResult = try await store.execute(
            query: "INSERT INTO COLLECTION myCollection (myAttachment ATTACHMENT) DOCUMENTS (:document1)",
            arguments: ["document1": document]
        )
    }
    

    Throws

    DittoSwiftError > .storeError(.attachmentFileNotFound) if the corresponding file couldn’t be found.

    Throws

    DittoSwiftError > .storeError(.attachmentFilePermissionDenied) if permission to access the file has been denied.

    Throws

    DittoSwiftError > .storeError(.failedToFetchAttachment) if an unknown error occured while trying to fetch an attachment.

    Declaration

    Swift

    public func newAttachment(path: String, metadata: [String : String] = [:]) async throws -> DittoAttachment

    Parameters

    path

    Path to the file on disk that will be used as the attachment.

    metadata

    Optional metadata relating to the attachment.

    Return Value

    A DittoAttachment object, which can be used to insert the attachment into a document.

  • Returns all currently active attachment fetchers.

    Declaration

    Swift

    public private(set) var attachmentFetchers: Set<DittoAttachmentFetcher> { get }
  • Fetch the attachment corresponding to the provided attachment token.

    Throws

    DittoSwiftError > .storeError(.attachmentNotFound) if the corresponding attachment couldn’t be found.

    Throws

    DittoSwiftError > .storeError(.failedToFetchAttachment) if an unknown error occured while trying to fetch an attachment.

    Declaration

    Swift

    @discardableResult
    public func fetchAttachment(
        token: DittoAttachmentToken,
        deliverOn deliveryQueue: DispatchQueue = .main,
        onFetchEvent: @escaping (DittoAttachmentFetchEvent) -> Void
    ) throws -> DittoAttachmentFetcher

    Parameters

    token

    The token for the attachment that you want to fetch.

    dispatchQueue

    The dispatch queue that will be used to deliver attachment fetch updates. Defaults to the main queue.

    onFetchEvent

    A closure that will be called when there is an update relating to the attachment fetch attempt. If the attachment is already available then this will be called almost immediately with a completed fetch event value.

    Return Value

    An active DittoAttachmentFetcher for the passed in token. You’ll have to keep it to be able to cancel the fetching. Otherwise the fetch will remain active until it either completes, the attachment is deleted, or the owning Ditto object goes out of scope.

  • Fetch the attachment corresponding to the provided attachment token. Expects a dictionary representation of the token as returned in a DittoQueryResultItem.

    Throws

    DittoSwiftError > .storeError(.failedToFetchAttachment) if the corresponding attachment couldn’t be found.

    Declaration

    Swift

    @discardableResult
    public func fetchAttachment(
        token: [String: Any],
        deliverOn queue: DispatchQueue = .main,
        onFetchEvent: @escaping (DittoAttachmentFetchEvent) -> Void
    ) throws -> DittoAttachmentFetcher

    Parameters

    token

    Dictionary representation of the token for the attachment that you want to fetch.

    dispatchQueue

    The dispatch queue that will be used to deliver attachment fetch updates. Defaults to the main queue.

    onFetchEvent

    A closure that will be called when there is an update relating to the attachment fetch attempt. If the attachment is already available then this will be called almost immediately with a completed fetch event value.

    Return Value

    A DittoAttachmentFetcher object.

  • A Combine publisher that fetches an attachement. Can also be used to monitor progress as a large attachment is downloaded across the network.

    See more

    Declaration

    Swift

    struct FetchAttachmentPublisher : Publisher
  • A Combine publisher that fetches an attachement.

    Declaration

    Swift

    func fetchAttachmentPublisher(attachmentToken: DittoAttachmentToken) -> FetchAttachmentPublisher

    Parameters

    attachmentToken

    The DittoAttachmentToken for the attachment to fetch.

    Return Value

    A FetchAttachmentPublisher which has an output of DittoAttachmentFetchEvent

  • A Combine publisher that fetches an attachement given the attachment token as dictionary representation.

    Declaration

    Swift

    func fetchAttachmentPublisher(attachmentToken: [String : Any]) -> FetchAttachmentPublisher

    Parameters

    attachmentToken

    The DittoAttachmentToken for the attachment to fetch as dictionary representation.

    Return Value

    A FetchAttachmentPublisher which has an output of DittoAttachmentFetchEvent

DittoQueryExecuting