Database

public final class Database
extension Database : QueryFactory

A Couchbase Lite database.

  • The default scope name constant

    Declaration

    Swift

    public static let defaultScopeName: String
  • The default collection name constant

    Declaration

    Swift

    public static let defaultCollectionName: String
  • Initializes a Couchbase Lite database with a given name and database options. If the database does not yet exist, it will be created, unless the readOnly option is used.

    Throws

    An error when the database cannot be opened.

    Declaration

    Swift

    public init(name: String, config: DatabaseConfiguration = DatabaseConfiguration()) throws

    Parameters

    name

    The name of the database.

    config

    The database options, or nil for the default options.

  • The database’s name.

    Declaration

    Swift

    public var name: String { get }
  • The database’s path. If the database is closed or deleted, nil value will be returned.

    Declaration

    Swift

    public var path: String? { get }
  • The total numbers of documents in the database.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.count instead.")
    public var count: UInt64 { get }
  • The database configuration.

    Declaration

    Swift

    public let config: DatabaseConfiguration
  • Gets a document from the default collection by document ID. If the document doesn’t exist, nil will be returned.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.document(id:﹚ instead.")
    public func document(withID id: String) -> Document?
  • Gets document fragment object from the default collection by document ID.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.subscript(key:﹚ instead.")
    public subscript(key: String) -> DocumentFragment { get }
  • Saves a document to the default collection. When write operations are executed concurrently, the last writer will overwrite all other written values. Calling this function is the same as calling the saveDocument(document, concurrencyControl) function with ConcurrencyControl.lastWriteWins.

    Throws

    An error on a failure.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.save(:﹚ instead.")
    public func saveDocument(_ document: MutableDocument) throws

    Parameters

    document

    The document.

  • Saves a document to the default collection. When used with lastWriteWins concurrency control, the last write operation will win if there is a conflict. When used with failOnConflict concurrency control, save will fail with ‘false’ value returned.

    Throws

    An error on a failure.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.save(:concurrencyControl:﹚ instead.")
    @discardableResult
    public func saveDocument(
        _ document: MutableDocument, concurrencyControl: ConcurrencyControl) throws -> Bool

    Parameters

    document

    The document.

    concurrencyControl

    The concurrency control.

    Return Value

    True if successful. False if the failOnConflict concurrency control is used, and there is a conflict.

  • Saves a document to the default collection. When write operations are executed concurrently and if conflicts occur, the conflict handler will be called. Use the conflict handler to directly edit the document to resolve the conflict. When the conflict handler returns ‘true’, the save method will save the edited document as the resolved document. If the conflict handler returns ‘false’, the save operation will be canceled with ‘false’ value returned as the conflict wasn’t resolved.

    Throws

    An error on a failure.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.save(:conflictHandler:﹚ instead.")
    @discardableResult
    public func saveDocument(
        _ document: MutableDocument, conflictHandler: @escaping (MutableDocument, Document?) -> Bool
    ) throws -> Bool

    Parameters

    document

    The document.

    conflictHandler

    The conflict handler closure which can be used to resolve it.

    Return Value

    True if successful. False if there is a conflict, but the conflict wasn’t resolved as the conflict handler returns ‘false’ value.

  • Deletes a document from the default collection. When write operations are executed concurrently, the last writer will overwrite all other written values. Calling this function is the same as calling the deleteDocument(document, concurrencyControl) function with ConcurrencyControl.lastWriteWins.

    Throws

    An error on a failure.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.delete(:﹚ instead.")
    public func deleteDocument(_ document: Document) throws

    Parameters

    document

    The document.

  • Deletes a document from the default collection. When used with lastWriteWins concurrency control, the last write operation will win if there is a conflict. When used with failOnConflict concurrency control, save will fail with ‘false’ value returned.

    Throws

    An error on a failure.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.delete(:concurrencyControl:﹚ instead.")
    @discardableResult
    public func deleteDocument(
        _ document: Document, concurrencyControl: ConcurrencyControl) throws -> Bool

    Parameters

    document

    The document.

    concurrencyControl

    The concurrency control.

    Return Value

    True if successful. False if the failOnConflict concurrency control is used, and there is a conflict.

  • Purges the given document from the default collection. This is more drastic than deletion: it removes all traces of the document. The purge will NOT be replicated to other databases.

    Throws

    An error on a failure.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.purge(:﹚ instead.")
    public func purgeDocument(_ document: Document) throws

    Parameters

    document

    The document.

  • Purges the document with the given documentID from the default collection. This is more drastic than deletion: it removes all traces of the document. The purge will NOT be replicated to other databases.

    Throws

    An error on a failure.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.purge(id:﹚ instead.")
    public func purgeDocument(withID documentID: String) throws

    Parameters

    documentID

    The document.

  • Save a blob object directly into the database without associating it with any documents.

    Note: Blobs that are not associated with any documents will be removed from the database when compacting the database.

    Throws

    An error on a failure.

    Declaration

    Swift

    public func saveBlob(blob: Blob) throws

    Parameters

    blob

    The blob to save.

  • Get a blob object using a blob’s metadata. If the blob of the specified metadata doesn’t exist, the nil value will be returned.

    Throws

    An error on a failure.

    Note

    Note:

    Key | Value | Mandatory | Description

    @type | constant string “blob” | Yes | Indicate Blob data type. content_type | String | No | Content type ex. text/plain. length | Number | No | Binary length of the Blob in bytes. digest | String | Yes | The cryptographic digest of the Blob’s content.

    Declaration

    Swift

    public func getBlob(properties: [String : Any]) throws -> Blob?

    Parameters

    properties

    The properties for getting the blob object. If dictionary is not valid, it will throw InvalidArgument exception. See the note section

  • Runs a group of database operations in a batch. Use this when performing bulk write operations like multiple inserts/updates; it saves the overhead of multiple database commits, greatly improving performance.

    Throws

    An error on a failure.

    Declaration

    Swift

    public func inBatch(using block: () throws -> Void) throws

    Parameters

    block

    The block to be executed as a batch operations.

  • Sets an expiration date on a document in the default collection. After this time the document will be purged from the default collection.

    Throws

    An error on a failure.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.setDocumentExpiration(id:expiration:﹚ instead.")
    public func setDocumentExpiration(withID documentID: String, expiration: Date?) throws

    Parameters

    documentID

    The ID of the document to set the expiration date for

    expiration

    The expiration date. Set nil date will reset the document expiration.

  • Returns the expiration time of a document in the default collection, if exists, else nil.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.getDocumentExpiration(id:﹚ instead.")
    public func getDocumentExpiration(withID documentID: String) -> Date?

    Parameters

    documentID

    The ID of the document to set the expiration date for.

    Return Value

    the expiration time of a document, if one has been set, else nil.

  • Adds a change listener to listen to changes in the default collection. Changes will be posted on the main queue.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.addChangeListener(:﹚ instead.")
    @discardableResult
    public func addChangeListener(
        _ listener: @escaping (DatabaseChange) -> Void) -> ListenerToken

    Parameters

    listener

    The listener to post changes.

    Return Value

    An opaque listener token object for removing the listener.

  • Adds a change listener with the dispatch queue on which changes will be posted to listen to changes in the default collection. If the dispatch queue is not specified, the changes will be posted on the main queue.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.addChangeListener(queue:listener:﹚ instead.")
    @discardableResult
    public func addChangeListener(withQueue queue: DispatchQueue?,
        listener: @escaping (DatabaseChange) -> Void) -> ListenerToken

    Parameters

    queue

    The dispatch queue.

    listener

    The listener to post changes.

    Return Value

    An opaque listener token object for removing the listener.

  • Adds a document change listener for the document with the given document ID in the default collection.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.addDocumentChangeListener(id:listener:﹚ instead.")
    @discardableResult
    public func addDocumentChangeListener(withID id: String,
        listener: @escaping (DocumentChange) -> Void) -> ListenerToken

    Parameters

    documentID

    The document ID.

    listener

    The listener to post changes.

    Return Value

    An opaque listener token object for removing the listener.

  • Adds a document change listener for the document with the given document ID in the default collection with the dispatch queue on which changes will be posted . If the dispatch queue is not specified, the changes will be posted on the main queue.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.addDocumentChangeListener(id:queue:listener:﹚ instead.")
    @discardableResult
    public func addDocumentChangeListener(withID id: String,
                                          queue: DispatchQueue?,
                                          listener: @escaping (DocumentChange) -> Void) -> ListenerToken

    Parameters

    id

    The document ID.

    queue

    The dispatch queue.

    listener

    The listener to post changes.

    Return Value

    An opaque listener token object for removing the listener.

  • Removes a change listener with the given listener token.

    Declaration

    Swift

    @available(*, deprecated, message: "Use token.remove(﹚ instead.")
    public func removeChangeListener(withToken token: ListenerToken)

    Parameters

    token

    The listener token.

  • Close database synchronously. Before closing the database, the active replicators, listeners and live queries will be stopped.

    Throws

    An error on a failure.

    Declaration

    Swift

    public func close() throws
  • Close and delete the database synchronously. Before closing the database, the active replicators, listeners and live queries will be stopped.

    Throws

    An error on a failure.

    Declaration

    Swift

    public func delete() throws
  • Performs database maintenance.

    Throws

    An error on a failure

    Declaration

    Swift

    public func performMaintenance(type: MaintenanceType) throws
  • Deletes a database of the given name in the given directory.

    Throws

    An error on a failure.

    Declaration

    Swift

    public static func delete(withName name: String, inDirectory directory: String? = nil) throws

    Parameters

    name

    The database name.

    directory

    The directory where the database is located at.

  • Checks whether a database of the given name exists in the given directory or not.

    Declaration

    Swift

    public static func exists(withName name: String, inDirectory directory: String? = nil) -> Bool

    Parameters

    name

    The database name.

    directory

    The directory where the database is located at.

    Return Value

    True if the database exists, otherwise false.

  • Copies a canned databaes from the given path to a new database with the given name and the configuration. The new database will be created at the directory specified in the configuration. Without given the database configuration, the default configuration that is equivalent to setting all properties in the configuration to nil will be used.

    Note

    This method will copy the database without changing the encryption key of the original database. The encryption key specified in the given config is the encryption key used for both the original and copied database. To change or add the encryption key for the copied database, call Database.changeEncryptionKey(key) for the copy.

    Note

    It is recommended to close the source database before calling this method.

    Throws

    An error on a failure.

    Declaration

    Swift

    public static func copy(fromPath path: String, toDatabase name: String,
                           withConfig config: DatabaseConfiguration?) throws

    Parameters

    path

    The source database path.

    name

    The name of the new database to be created.

    config

    The database configuration for the new database name.

  • log

    Log object used for configuring console, file, and custom logger.

    Declaration

    Swift

    public static let log: Log

Scopes

  • Get the default scope.

    Declaration

    Swift

    public func defaultScope() throws -> Scope
  • Get scope names that have at least one collection. Note: the default scope is exceptional as it will always be listed even though there are no collections under it.

    Declaration

    Swift

    public func scopes() throws -> [Scope]
  • Get a scope object by name. As the scope cannot exist by itself without having a collection, the nil value will be returned if there are no collections under the given scope’s name. Note: The default scope is exceptional, and it will always be returned.

    Declaration

    Swift

    public func scope(name: String) throws -> Scope?

Collections

  • Get the default collection.

    Declaration

    Swift

    public func defaultCollection() throws -> Collection
  • Get all collections in the specified scope.

    Declaration

    Swift

    public func collections(scope: String? = defaultScopeName) throws -> [Collection]
  • Create a named collection in the specified scope. If the collection already exists, the existing collection will be returned.

    Declaration

    Swift

    public func createCollection(name: String, scope: String? = defaultScopeName) throws -> Collection
  • Get a collection in the specified scope by name. If the collection doesn’t exist, a nil value will be returned.

    Declaration

    Swift

    public func collection(name: String, scope: String? = defaultScopeName) throws -> Collection?
  • Delete a collection by name in the specified scope. If the collection doesn’t exist, the operation will be no-ops.

    Note

    The default collection cannot be deleted.

    Declaration

    Swift

    public func deleteCollection(name: String, scope: String? = defaultScopeName) throws
  • ENTERPRISE EDITION ONLY.

    Changes the database’s encryption key, or removes encryption if the new key is nil.

    Throws

    An error on a failure.

    Declaration

    Swift

    public func changeEncryptionKey(_ key: EncryptionKey?) throws

    Parameters

    key

    The encryption key.

  • ENTERPRISE EDITION ONLY

    The predictive model manager for registering and unregistering predictive models.

    Declaration

    Swift

    public static let prediction: Prediction
  • Creates a Query object from the given query string.

    Throws

    An error on when the given query string is invalid.

    Declaration

    Swift

    public func createQuery(_ query: String) throws -> Query

    Parameters

    query

    Query string.

    Return Value

    A query created by the given query string.

  • All index names.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.indexes(﹚ instead.")
    public var indexes: Array<String> { get }
  • Creates an index wih the given name in the default collection. The index could be a value index or a full-text index. The index name can be used later for deleting the index. Creating a new different index with an existing index name will replace the old index. Creating the same index with the same name will be no-ops.

    Throws

    An error on a failure.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.createIndex(:name:﹚ instead.")
    public func createIndex(_ index: Index, withName name: String) throws

    Parameters

    index

    The index.

    name

    The index name.

  • Creates an index in the default collection with the index config and the index name. The index config could be a value index or a full-text index config. The index name can be used later for deleting the index. Creating a new different index with an existing index name will replace the old index. Creating the same index with the same name will be no-ops.

    Throws

    An error on a failure.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.createIndex(:name:﹚ instead.")
    public func createIndex(_ config: IndexConfiguration, name: String) throws

    Parameters

    config

    The index configuration

    name

    The index name.

  • Deletes the index from the default collection by name.

    Throws

    An error on a failure.

    Declaration

    Swift

    @available(*, deprecated, message: "Use database.defaultCollection(﹚.deleteIndex(forName:﹚ instead.")
    public func deleteIndex(forName name: String) throws

    Parameters

    name

    The index name.