Databases

      +

      Description — Working with Couchbase Lite on Android databases
      Related Content — Blobs | Documents | Indexing

      Database Concepts

      Databases created on Couchbase Lite can share the same hierarchical structure as Capella databases. This makes it easier to sync data between mobile applications and applications built using Capella.

      Couchbase Lite Database Hierarchy
      Figure 1. Couchbase Lite Database Hierarchy

      Although the terminology is different, the structure can be mapped to relational database terms:

      Table 1. Relational Database → Couchbase
      Relational database Couchbase

      Database

      Database

      Schema

      Scope

      Table

      Collection

      This structure gives you plenty of choices when it comes to partitioning your data. The most basic structure is to use the single default scope with a single default collection; or you could opt for a structure that allow you to split your collections into logical scopes.

      Couchbase Lite Examples
      Figure 2. Couchbase Lite Examples
      Storing local configuration

      You may not need to sync all the data related for a particular application. You can set up a scope that syncs data, and a second scope that doesn’t.

      One reason for doing this is to store local configuration data (such as the preferred screen orientation or keyboard layout). Since this information only relates to a particular device, there is no need to sync it:

      local data scope

      Contains information pertaining to the device.

      syncing data scope

      Contains information pertaining to the user, which can be synced back to the cloud for use on the web or another device.

      Initializer

      Your first step in using the API must be to call its initializer. An exception is raised if any other API method is invoked before the initializer.

      Example 1. Initializer code
      • Kotlin

      • Java

      override fun onCreate() {
          super.onCreate()
          // Initialize the Couchbase Lite system
          CouchbaseLite.init(this)
      }
      @Override
      public void onCreate() {
          super.onCreate();
          // Initialize the Couchbase Lite system
          CouchbaseLite.init(this);
      }

      Create or Open Database

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

      Things to watch for include:

      Example 2. Open or create a database
      • Kotlin

      • Java

      val database = Database("my-db") (1)
      Database database = new Database(DB_NAME);

      Close Database

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

      To close a database, use Database.close() — see: Example 3. This also closes [1] active replications, listeners and-or live queries connected to the database.

      Closing a database soon after starting a replication involving it can cause an exception as the asynchronous replicator (start) may not yet be connected.
      Safely Closing a Database pre 2.8
      Before closing, check that any attached listeners (query/replication/change) indicate they are at least at connected status before closing — see for example: Monitor Status.
      Example 3. Close a Database
      • Kotlin

      • Java

      database.close()
      database.close();

      Database Full Sync

      Database Full Sync will prevent the loss of transactional data due to an unexpected system crash or loss of power. This feature is not enabled by default and must be manually set in your database configuration.

      Database Full Sync is a safe method to prevent data loss but will incur a significant degredation of performance.
      Example 4. Enable Database Full Sync
      • Kotlin

      • Java

      val db = Database(
          "my-db",
          DatabaseConfigurationFactory.newConfig(
              fullSync = true
          )
      )
      config.setFullSync(true);
      It is not possible to change the configuration of a Database after instantiating the Database with the configuration by updating its DatabaseConfiguration property.

      Database Encryption

      This is an Enterprise Edition feature.

      Couchbase Lite on Android 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.

      Enabling

      To enable encryption, use DatabaseConfiguration.setEncryptionKey() to set the encryption key of your choice. Provide this encryption key every time the database is opened — see Example 5.

      Example 5. Configure Database Encryption
      • Kotlin

      • Java

      val db = Database(
          "my-db",
          DatabaseConfigurationFactory.newConfig(
              encryptionKey = EncryptionKey("PASSWORD")
          )
      )
      DatabaseConfiguration config = new DatabaseConfiguration();
      config.setEncryptionKey(new EncryptionKey("PASSWORD"));
      Database database = new Database(DB_NAME, config);

      Persisting

      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 Android’s Keystore.

      Opening

      An encrypted database can only be opened with the same platform that was used to encrypt it in the first place. So a database encrypted using the Android SDK, and then exported, is readable only by the Android SDK.

      Changing

      To change an existing encryption key, open the database using its existing encryption-key and use Database.changeEncryptionKey() to set the required new encryption-key value.

      Removing

      To remove encryption, open the database using its existing encryption-key and use Database.changeEncryptionKey() with a null value as the encryption key.

      Upgrading

      To upgrade an encrypted database see: Upgrade 1.x databases

      Finding a Database File

      When the application is running on the Android emulator, you can locate the application’s data folder and access the database file by using the adb CLI tools. For example, to list the different databases on the emulator, you can run the following commands.

      List
      $ adb shell
      $ su
      $ cd /data/data/{APPLICATION_ID}/files
      $ ls

      The adb pull command can be used to pull a specific database to your host machine.

      Example 6. Pull using adb command
      $ adb root
      $ adb pull /data/data/{APPLICATION_ID}/files/{DATABASE_NAME}.cblite2 .

      Database Maintenance

      From time to time it may be necessary to perform certain maintenance activities on your database, for example to compact the database file, removing unused documents and blobs no longer referenced by any documents.

      Couchbase Lite’s API provides the Database.performMaintenance() method. The available maintenance operations, including compact are as shown in the enum MaintenanceType to accomplish this.

      This is a resource intensive operation and is not performed automatically. It should be run on-demand using the API. If in doubt, consult Couchbase support.

      Command Line Tool

      cblite is a command-line tool for inspecting and querying Couchbase Lite 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 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 7.

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

      Example 7. Increase Level of Database Log Messages
      • Kotlin

      • Java

      Database.log.console.level = LogLevel.DEBUG (1)
      Database.log.getConsole().setLevel(LogLevel.DEBUG); (1)

      1. Commencing with Release 2.8