Databases — Data Model

    +

    Description — Working with Couchbase Lite on Android (Java) databases
    Related Content — Blobs | Documents | Indexes |

    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.

    The init() API accepts no parameters.

    Example 1. Initializer code
    // Initialize the Couchbase Lite system
    CouchbaseLite.init(context);

    Default Database Location

    By default, Couchbase Lite on Android (Java) creates databases in the following path location shown in Example 2.

    Example 2. Default database path
    <root dir>/.couchbase/<db name>.cblite (1)
    1 Where the <root dir> can be identified using context.getFilesDir()

    New Database

    As the top-level entity in the API, new databases can be created using the Database class by passing in a name, configuration, or both. The following example opens, or creates, a database using the Database(String name, DatabaseConfiguration config) method.

    Example 3. Open or create a database
    final DatabaseConfiguration config = new DatabaseConfiguration();
    config.setDirectory(context.getFilesDir().getAbsolutePath()); (1)
    
    Database database = new Database("my-database", config);

    Just as before, the database will be created in a default location. Alternatively, the Database(string name, DatabaseConfiguration config) initializer can be used to provide specific options in the DatabaseConfiguration object.

    1 Here we are specifying the database directory path.

    Database Encryption

    This is an Enterprise Edition feature.

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

    Example 4. Database encryption
    DatabaseConfiguration config = new DatabaseConfiguration();
    config.setEncryptionKey(new EncryptionKey("PASSWORD"));
    Database database = new Database("mydb", 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 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 5. Pull using adb command
    $ adb root
    $ adb pull /data/data/{APPLICATION_ID}/files/{DATABASE_NAME}.cblite2 .

    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.

    The cblite tool is not covered under the Couchbase Support Policy.

    Logging

    If you are using a Couchbase Lite release prior to 2.5 see Deprecated functionality

    From version 2.5, Couchbase Lite provides a logging API that unifies the logging behavior across all platforms, making debugging and troubleshooting easier during development and in production.

    The retrieval of logs from the device is out of scope of this feature.

    Available logging features include:

    • Console based logging

    • File based logging

    • Custom logging

    Console based logging

    Default: Enabled.

    Console based logging is often used to facilitate troubleshooting during development.

    File based logging

    Default: Disabled.

    Available file based logging formats:

    • Binary — most efficient for storage and performance. It is the default for file based logging.

    • Plaintext

    We recommend using the binary log format and a decoder, such as cbl-log, to view them. Download cbl-log from couchbaselabs/couchbase-mobile-tools.

    The following example enables file based logging.

    final File path = context.getCacheDir();
    Database.log.getFile().setConfig(new LogFileConfiguration(path.toString()));
    Database.log.getFile().setLevel(LogLevel.INFO);

    Custom logging

    Default: Disabled.

    Allows registration of a callback function to receive Couchbase Lite log messages, which may be logged using any external logging framework.

    Apps must implement the Logger interface, as shown below:

    class LogTestLogger implements Logger {
        @NonNull
        private final LogLevel level;
    
        public LogTestLogger(@NonNull LogLevel level) { this.level = level; }
    
        @NonNull
        @Override
        public LogLevel getLevel() { return level; }
    
        @Override
        public void log(@NonNull LogLevel level, @NonNull LogDomain domain, @NonNull String message) {
            // this method will never be called if param level < this.level
            // handle the message, for example piping it to a third party framework
        }
    }

    And set it on the custom property.

    // this custom logger will never be asked to log an event
    // with a log level < WARNING
    Database.log.setCustom(new LogTestLogger(LogLevel.WARNING));

    Decoding binary logs

    The cbl-log tool should be used to decode binary log files as shown in these examples.

    • macOS

    • CentOS

    • Windows

    Download the cbl-log tool using wget.

    wget https://packages.couchbase.com/releases/couchbase-lite-log/2.8.0/couchbase-lite-log-2.8.0-macos.zip

    Navigate to the bin directory and run the cbl-log executable.

    $ ./cbl-log logcat LOGFILE <OUTPUT_PATH>

    Download the cbl-log tool using wget.

    wget https://packages.couchbase.com/releases/couchbase-lite-log/2.8.0/couchbase-lite-log-2.8.0-centos.zip

    Navigate to the bin directory and run the cbl-log executable.

    cbl-log logcat LOGFILE <OUTPUT_PATH>

    Download the cbl-log tool using PowerShell.

    Invoke-WebRequest https://packages.couchbase.com/releases/couchbase-lite-log/2.8.0/couchbase-lite-log-2.8.0-windows.zip -OutFile couchbase-lite-log-2.8.0-windows.zip

    Run the cbl-log executable.

    $ .\cbl-log.exe logcat LOGFILE <OUTPUT_PATH>

    Logging functionality prior to Release 2.5

    Deprecation
    The pre-Couchbase Lite 2.5 logging functionality is deprecated. It was superseded by an enhanced Logging API in that release. This information is included for completeness only.

    The log messages are split into different domains (LogDomains) which can be tuned to different log levels. The following example enables verbose logging for the replicator and query domains.

    Example 6. Enable verbose logging on a domain
    Database.setLogLevel(LogDomain.REPLICATOR, LogLevel.VERBOSE);
        Database.setLogLevel(LogDomain.QUERY, LogLevel.VERBOSE);

    Loading a pre-built database

    If your app needs to sync a lot of data initially, but that data is fairly static and won’t change much, it can be a lot more efficient to bundle a database in your application and install it on the first launch. Even if some of the content changes on the server after you create the app, the app’s first pull replication will bring the database up to date.

    To use a prebuilt database, you need to set up the database, build the database into your app bundle as a resource, and install the database during the initial launch. After your app launches, it needs to check whether the database exists.

    If the database does not exist, the app should copy it using the following method.

    // Note: Getting the path to a database is platform-specific.
    // For Android you need to extract it from your
    // assets to a temporary directory and then pass that path to Database.copy()
    DatabaseConfiguration configuration = new DatabaseConfiguration();
    if (!Database.exists("travel-sample", context.getFilesDir())) {
          ZipUtils.unzip(getAsset("travel-sample.cblite2.zip"), context.getFilesDir());
          File path = new File(context.getFilesDir(), "travel-sample");
          try {
              Database.copy(path, "travel-sample", configuration);
          } catch (CouchbaseLiteException e) {
              e.printStackTrace();
          }
      }