Database for Swift

    +

    Description — Working with Couchbase Lite Databases
    Related Content — Blobs | Documents | Indexing

    Create or Open Database

    You can create a new database and-or open and existing database, using the Database class. Just pass in a database name and optionally a DatabaseConfiguration — see Example 1.

    Things to watch for include:

    • Opening/Creating a database is an asynchronous process

    • If the named database does not exist in the specified, or default, location then a new one is created

    • The database is created in a default location unless you specify a directory for it — see: DatabaseConfiguration and DatabaseConfiguration.directory()

      Best Practice is to always specify the path to the database explicitly.

      Typically, the default location for Swift is the application sandbox.

    Example 1. Open or create a database
    do {
        self.database = try Database(name: "my-database")
    } catch {
        print(error)
    }
    1 Here we are specifying the database directory path.

    Close Database

    You are advised to incorporate the closing of all open databases into your application workflow.

    Closing a database is a simple, just use Database.close() — see: Example 2.
    However, there are a number of things to be aware of:

    • Closing a database is a synchronous operation, it is effective immediately

    • You cannot close a database that is not open.
      Remember that opening (or creating) a database is asynchronous. So issuing a close immediately after initiating an open/create, may result in an error if that process has not completed.

    • Closing a database [1] also closes any active replications, listeners and-or live queries attached to the database.
      Closing a database immediately after kicking-off a replication could cause the sync to generate an exception.
      For example:
      IllegalStateException: Attempt to perform an operation on a closed database

    Safely Closing a Database pre 2.8
    1. Stop any active live queries — by removing the query’s change listener

    2. Remove any active replication change listeners

    3. Stop any active replications — this is an asynchronous operation

    4. Wait for all active replications to fully stop — for this you can monitor the replication status — see: Replication Status.

    5. Finally, close the database

    Example 2. Close a Database
    do {
        try userDb.close()
    }

    Database Encryption

    This is an Enterprise Edition feature.

    Couchbase Lite on Swift includes the ability to encrypt Couchbase Lite databases. This allows mobile applications to secure the data at rest, when it is being stored on the device. The algorithm used to encrypt the database is 256-bit AES.

    To enable encryption, you must set the DatabaseConfiguration.encryptionKey property to the encryption key of your choice. Provide this encryption key every time the database is opened.

    let config = DatabaseConfiguration()
    config.encryptionKey = EncryptionKey.password("secretpassword")
    self.database = try Database(name: "my-database", config: config)

    Couchbase Lite does not persist the key. It is the application’s responsibility to manage the key and store it in a platform specific secure store such as Apple’s Keychain or Android’s Keystore.

    An encrypted database can only be opened with the same language SDK that was used to encrypt it in the first place (Swift, C#, Java, Java (Android) or Objective-C). For example, if a database is encrypted with the Swift SDK and then exported, it will only be readable with the Swift SDK.

    Upgrading from 1.x when Encryption is Enabled

    If you’re migrating an application from Couchbase Lite 1.x to 2.x, note that the automatic database upgrade functionality is not supported for encrypted databases. Thus, to upgrade an encrypted 1.x database, you should do the following:

    1. Disable encryption using the Couchbase Lite 1.x framework (see 1.x encryption guide)

    2. Open the database file with encryption enabled using the Couchbase Lite 2.x framework.

    Since it is not possible to package Couchbase Lite 1.x and Couchbase Lite 2.x in the same application this upgrade path would require two successive upgrades. If you are using Sync Gateway to synchronize the database content, it may be preferable to run a pull replication from a new 2.x database with encryption enabled and delete the 1.x local database.

    Finding a Database File

    When the application is running on the iOS simulator, you can locate the application’s sandbox directory using the SimPholders utility.

    Command Line Tool

    cblite is a command-line tool for inspecting and querying Couchbase Lite 2.x databases.

    You can download and build it from the couchbaselabs GitHub repository. Note that the cblite tool is not supported by the Couchbase Support Policy.

    Troubleshooting

    You should use Couchbase’s console logs as your first source of diagnostic information. If the information in the default logging level is insufficient you can focus it on database errors and generate more verbose messages — see: Example 3.

    For more on using Couchbase logs — see: Using Logs.

    Example 3. Increase Level of Database Log Messages
    Database.log.console.domains = .database

    1. Commencing with Release 2.8