com.webos.service.db

API Summary

Enables apps to store persistent data. 

Overview of the API

(click to expand)

DB8 is a userspace service that provides access to the webOS database. Access to the database APIs is provided over the luna-service bus.

Formally, a database refers to a set of related objects and the way it is structured or organized. Access to these objects is usually provided by a luna API that allows applications to interact with the database and one with another. It also provides access to the objects in the database (although there may be restrictions that grant or limit access to particular data). DB8 provides various functions that allow to enter, store, and retrieve large volumes of information as well as provides the interface to manage how that information is organized.

Designing a database:

The first task of a database designer is to produce a conceptual model that reflects the structure of data as it is going to be stored in a database. A common approach to this is to develop a Kind that implements the relevant data structures within the database.

Example of Kind creation:

luna-send -n 1 luna://com.webos.service.db/putKind '{
   "id": "com.webos.service.test:1",
   "owner":"com.webos.service.test",
   "indexes":[
       {"name":"sample",   "props":[ {"name":"sample"} ]},
       {"name":"testsample","props":[ {"name":"test"}, {"name":"sample"}]} ]}
   ]
}'

In the example above, we create a Kind with an Id: "com.webos.service.test:1" (this is similar to a schema name).

The owner of this Kind service is com.webos.service.test. The owner of a Kind has permissions to calculate quotas, grant permissions to modify or delete a Kind, grant permissions to other services for Kind data, etc.

We have also specified two indexes for the Kind. An index is a data structure that allows data retrieval operations on a database at the cost of additional writes and storage space to maintain the index data structure. Indexes are used to quickly locate data without having to search every row in a database every time a database is accessed. Indexes are created using one or more columns of a database object, providing the basis for both rapid random searches and efficient access of ordered records.

The number after the colon in the id is the Kind Revision number. When a service updates a Kind, the service should increment its revision number to indicate that the schema has changed.

Philosopher's stone (objects):

DB8 operates with objects. Objects have fields. Every object that is stored within DB8 always has an id and a revision.

An object id uniquely identifies an object within a database. The object id does not repeat within a database.

Object revisions:

Object revision is a number, that determines "Version of an object in the database". This number is required to avoid collisions when two or more services simultaneously try to update an object at the same time.

For all new objects, the database will append a _rev field, that indicates the object revision. By default, the database will set object revision _rev field to Database Revision (Number, that atomically increments on any database modification).

If an object already exists in the database, the database engine will automatically increment the object revision number on each each successfull put/merge API for this object.

Explanation by example: com.webos.service.test and com.webos.service.othertest applications have access for read/write to Kind com.webos.service.test:1 . Both applications, at the same time, read an object from com.webos.service.test:1 kind object with id ++JZk1sXYW7lCdqU and revision 777.

Both applications execute a merge command like the following:

luna-send -n 1 luna://com.webos.service.db/merge
'{
    "objects" : [{
        "_id" : "++JZk1sXYW7lCdqU",
        "_rev": 777,
        "_kind" : "com.webos.service.test:1",
        "sample" : "I am new sample value"
    }]
}'

Following is the merge call response, that will be received by one of the applications - (may be com.webos.service.test or com.webos.service.othertest, depends who is more lucky):

{
  "returnValue":true,
  "results":[
    {
       "id":"++JZk1sXYW7lCdqU",
       "rev":778                               <--- See, the database increments the revision after a successfull object update!
    }
]}

The other application will get the following error:

{
    "returnValue":false,
    "errorCode":-3961,
    "errorText":"db: revision mismatch - expected 778, got 777",
}

This error indicates that someone else has already updated this object. After receiving this error, the application MUST execute the get API call to get the object again with a new _rev, and then try to re-execute the merge query.

Create:

To store an object in the database, a client can use the put API call.

Complexity guaranteed for a put API call is log(n). 

luna-send -n 1 luna://com.webos.service.db/put '{
    "objects" : [ {
        "_kind" : "com.webos.service.test:1", 
        "sample" : "sample1",
        "test" : "test1",
        "name" : "max"
    }]
}'

Update (replace):

The put API call updates an object. Update by default will replace the database object with the new one (in other words, if a new object does not have some fields that were present in the old databse object, those old database fields will be removed)

As an example, consider the following object in a database:

        {
           "_kind": "com.webos.service.test:1"
            "_id": "JZR3hyjVyB3",           
            "_rev": 12,
            "name": "MAX",          
            "sample": "sample777",
            "test": "test777"          
        }

And the following luna call is made:

luna-send -n 1 -m com.webos.service.configurator luna://com.webos.service.db/put '{
    "objects" : [
        {  "_kind": "com.webos.service.test:1",
            "_id": "JZR3hyjVyB3",
            "_rev": 12,
            "sample": "sample777"           
        }]
}'

If the call is successful, the database will contain:

{
        "_rev": 13,
        "sample": "sample777",
        "_id": "JZR3hyjVyB3",
        "_kind": "com.webos.service.test:1"
}

Update (Merge):

Sometimes a service does not need to replace an object in the database, but simply needs to add a field to a database object. For this type of update, a client can call the merge API method instead of the put API method.

For example, if we have an object:

        {
           "_kind": "com.webos.service.test:1"
            "_id": "JZR3hyjVyB3",           
            "_rev": 12,
            "name": "MAX",          
            "sample": "sample777",
            "test": "test777"          
        }

And the following luna call is made:

luna-send -n 1 -m com.webos.service.configurator luna://com.webos.service.db/merge '{
    "objects" : [
        {
             "_kind": "com.webos.service.test:1"
            "_id": "JZR3hyjVyB3",           
            "_rev": 12,
            "sername" : "Super Hero!!!"
        }]
}'

If the call is successful, the database will contain:

{
        "_kind": "com.webos.service.test:1"
        "_id": "JZR3hyjVyB3",           
        "_rev": 13,
        "name": "MAX",    
        "sername" : "Super Hero!!!",
        "sample": "sample777",
        "test": "test777"      
}

Trick with put/merge and object revision:

The _rev object field shows the revision number of an object. But what happens if an application wants to track updates to specific field/fields? DB8 can do that.

The application should modify the Kind and add revSets.

Revision set (revSets) is a set of object field names, that the database should track for changes. If the tracked field/fields are modified, the database will increment the number.

luna-send -n 1 -f luna://com.webos.service.db/putKind '{
   "id": "com.webos.service.test:2",
   "owner":"com.webos.service.test",
   "indexes":[
       {"name":"field1", "props":[ {"name": "field1"} ]},
       {"name":"field2", "props":[ {"name": "field2"} ]},
       {"name":"field12","props":[ {"name": "field1"}, {"name" : "field2"}] },
       {"name":"field21","props":[ {"name": "field2"}, {"name" : "field1"}] }
   ],
   "revSets" : [ { "name" : "field1_rev", "props" : [ { "name" : "field1" } ] }]
}'

The above modification to the Kind tells DB8 to do the following:

  1. Add the field1_rev field to each object
  2. Increment its value when the field1 object is modified.

The default value of field1_rev will be the same as object _rev.

Example:

Lets create a new object:

luna-send -n 1 luna://com.webos.service.db/put '{
    "objects" : [
            {
                "_kind" : "com.webos.service.test:1",
                "field1" : "a",
                "field2" : "a",
            }
      ]
}'

In the database, the object will be stored as:

        {
            "field1_rev": 408,
            "_rev": 408,
            "field1": "a",
            "field2": "a",
            "_id": "++JZlENT5FkVcjy3",
            "_kind": "com.webos.service.test:1"
        }

The database then adds the field1_rev field to the object.

When an application updates field1, DB8 will automatically increment the field1_rev field:

luna-send -n 1 luna://com.webos.service.db/merge '{
    "objects" : [
        {
             "_id" : "++JZlENT5FkVcjy3",
             "_kind" : "com.webos.service.test:2",
             "_rev": 408,
             "field1" : "Join to dark DB8 side, Luke!"
         }
    ]
}'

The database will contain:

      {
            "field1_rev": 409,
            "_rev": 409,
            "field1": "Join to dark DB8 side, Luke!",
            "field2": "c",
            "_id": "++JZlENT5FkVcjy3",
            "_kind": "com.webos.service.test:2"
        }

Now, if we update the field2 only, the database will not increment the field1_rev field, as it does not track updates to field2.

luna-send -n 1luna://com.webos.service.db/merge '{
     "objects" : [
         {
             "_id" : "++JZlENT5FkVcjy3",
            "_kind" : "com.webos.service.test:2",
            "_rev": 409,
           "field2" : "Lalala"
        }
    ]
}'

The database will contain:

        {
            "field1_rev": 409,
            "_rev": 410,
            "field1": "Join to dark DB8 side, Luke!",
            "field2": "Lalala",
            "_id": "++JZlENT5FkVcjy3",
            "_kind": "com.webos.service.test:2"
        }

Queries:

DB8 guarantees complexity for all CRUD (create, read, update, delete) API calls.

To retrieve data, a client can call either the get or the find API method.

  • The get API method provides the ability to get an object by the object id.
    Complexity guaranteed for get API call is log(n)
  • The find API method provides the ability to get objects by condition. The find query must use the index fields of an object for searching.
    Complexity guaranteed for the find API call is log(n)
  • The search API method provides the ability to get objects by condition. The search Query uses any object field for searching.
    Complexity guaranteed for the find API call is n

It may not be clear, why the find API method does not allow operations, like filter or substring search. Think about it this way: DB8 always guarantees complexity for all of its API calls without exception. An operation like the filter can search by object fields that do not have indexes. In other words, DB8 would have to iterate over n objects to process the resulting set. However, since DB8 guarantees a complexity of log(n) to the find call, it does not allow the filtering operation.

Some quick examples for find (with collate and limit):

luna-send -n 1 luna://com.webos.service.db/find '{
    "query" : {
        "from" : "com.webos.service.test:1",
        "where" : [{ "prop" : "sample",
                           "op": "=",
                           "val" : "test1"
                      }],
        "limit" : 1,      
    }
}'

Quick example for search:

luna-send -n 1 luna://com.webos.service.db/search '{
    "query" : {
        "from" : "com.webos.service.test:1",
        "where" : [{ "prop" : "name", "op": "=", "val" : "max" }],
        "limit" : 1
    }
}'

Pages:

Processing of result sets that contain a lot of objects (thousands, millions, etc) can consume all available memory. Assume that a database has 1 million objects and we need to build a JSON representation of those objects on a target system that has only 1M of free RAM memory. How can that be achieved? To handle such a scenario, DB8 will output result sets by pages. Each page will have a limit on the maximum number of objects it can contain. If an application does not specify a limit in find/search, DB8 will add a default limit. On most platforms, the default limit value is 500 objects per page, but this can be reconfigured.

For example, we retrieve data from a DB8 database on a Tamagochi device (each page will contain only two objects):

luna-send -f -n 1 luna://com.webos.service.db/find '{
    "query" : {
        "from" : "com.webos.service.test:1",
        "limit" : 2,                    
    }                                 
}'

DB8 response:

{
    "next": "1lg403dPJY4mHMCDHJd9+F",
    "returnValue": true,
    "results": [
        {
            "name": "max",
            "_rev": 3,
            "sample": "sample1",
            "test": "test1",
            "_id": "JZQjZfgzFPw",
            "_kind": "com.webos.service.test:1"
        },
        {
            "name": "max",
            "_rev": 8,
            "sample": "sample1",
            "test": "test1",
            "_id": "JZR1rIsNIJJ",
            "_kind": "com.webos.service.test:1"
        }
    ]
}

The next parameter in the response indicates the ID of the next page in the result dataset (internally, DB8 interprets this id as a very tricky offset). To get the next object in the result dataset, execute query with a page parameter:

luna-send -f -n 1 luna://com.webos.service.db/find '{
    "query" : {
        "from" : "com.webos.service.test:1",
        "limit" : 2,                    
        "page" : "1lg403dPJY4mHMCDHJd9+F"
    }                                 
}'

And DB8 will response with next 2 objects and id of the next page:

{
    "next": "1lg403dPJYCcTLdLTJ7n+F",
    "returnValue": true,
    "results": [
        {
            "name": "max",
            "_rev": 9,
            "sample": "sample2",
            "test": "test2",
            "_id": "JZR1vy_Lb8c",
            "_kind": "com.webos.service.test:1"
        },
        {
            "sername": "Super Hero!!!",
            "_rev": 15,
            "sample": "sample777",
            "_id": "JZR3hyjVyB3",
            "_kind": "com.webos.service.test:1"
        }
    ]
}

If DB8 does not have any objects in the result set and the last retrieved page contains the final objects from the result set, DB8 will not provide the next parameter in the response.

Complex Queries:

For this section we are using the following test Kind:

luna-send -n 1 -a com.webos.service.configurator luna://com.webos.service.db/putKind '{
    "id": "com.webos.service.test:1",
    "owner":"com.webos.service.test",
    "indexes":[
        {
             "name":"field1",
             "props":[ {"name": "field1"} ]
        },
        {
            "name":"field2",
            "props":[ {"name": "field2"} ]
        },
        {
            "name":"field12",
            "props":[ {"name": "field1"}, {"name" : "field2"}]
        }
    ]    
}'

Example database set for this documentation section:

field1 field2
a a
a b
b a
b b

For test queries, we use these put API calls:

luna-send -n 1 luna://com.webos.service.db/put '{
    "objects" : [
        {
            "_kind" : "com.webos.service.test:1",
            "field1" : "a",
            "field2" : "a"
       },
       {
           "_kind" : "com.webos.service.test:1",
           "field1" : "a",
           "field2" : "b"
      },
      {
           "_kind" : "com.webos.service.test:1",
          "field1" : "b",
          "field2" : "a"
      },
      {
          "_kind" : "com.webos.service.test:1",
          "field1" : "b",
          "field2" : "b"
       }
    ]
}'

In the Queries section you can find how to create an index for one field and execute some trivial queries, like:

"where":[{"prop":"field1","op":"=", "val":"a" }

If an application developer tries to search using two fields at the same time:

"where":[{"prop":"field1","op":"=", "val":"a" }, {"prop":"field2","op":"=","val":"b"}]

DB8 will return "Sorry, I don't know such index". This error is returned because the db8 Planner is not very intelligent and will never try to guess the index.

An application developer should provide complex indexes for such complex quires. To get an object using 2 fields (third object from example set):

(field1 == b) && (field2 == a)

the client should provide the Kind for such index like following:

{"name":"field12","props":[ {"name": "field1"}, {"name" : "field2"}] }

(see at top of this documentation section for full luna comand for kind creation)

After modification of the Kind, an application can execute a query like this:

luna-send -n 1 -f luna://com.webos.service.db/find '{
    "query":{
        "from":"com.webos.service.test:1",
        "where":[ { "prop":"field1", "op":"=", "val":"a" }, { "prop":"field2", "op":"=", "val":"b" } ]
   }
}'

Complex Queries tricks:

Imagine, that an application developer extends a Kind with a complex index like the one below, and then tries to execute it:

(field1 < b) && (field2 == b)

luna-send -n 1 -f luna://com.webos.service.db/find '{
    "query": {
        "from":"com.webos.service.test:1",
        "where":[
            {
                 "prop" : "field1",
                 "op":"<",
                 "val":"a"
            },
            {
                "prop" : "field2",
                "op":"=",
                "val":"b"
           }
        ]
    }
}'

DB8 will return "Index not found", even if you have created a complex index for field1 and field2. In the example below, the index has the name field12.

To work around this, you should also create a reverse index field21:

{"name":"field21","props":[ {"name": "field2"}, {"name" : "field1"}] }

luna-send -n 1 luna://com.webos.service.db/putKind '{
    "id": "com.webos.service.test:1",
    "owner":"com.webos.service.test",
    "indexes":[
        {
            "name":"field1", "props":[  { "name": "field1"} ]
        },
        {
            "name":"field2", "props":[ {"name": "field2"} ]
        },
        {
            "name":"field12","props":[ {"name": "field1"}, {"name" : "field2"} ]
        },
        {
            "name":"field21","props":[ {"name": "field2"}, {"name" : "field1"} ]
        }
    ]
}'

After such a tricky index creation, DB8 can successfully search for data.


Watch:

Sometimes a client may want to be notified about an object in a database that satisfy some condition. For this, the client can use the watch API call.
Example:

luna-send -i -m com.webos.service.configurator luna://com.webos.service.db/watch '{     
    "query" : {
        "from" : "com.webos.service.test:1",
        "where" : [{ "prop" : "processed",
                           "op": "=",
                           "val" : false
                      }]      
    }, "subscribe" : true
}'

If no object exists with the field processed=false for Kind com.webos.service.test:1, the client will be blocked in the watch API call. The watch will be unblocked, when an object that satisfies a query will appear in a database. In the example above, the database will have object for com.webos.service.test:1 with field processed=false (if someone will insert object or modify field for existing object).

Note about blocking: for a blocking watch API call, the caller cannot do anything until the watch API call returns. It is very similar to system calls blocks. For more information about blocking calls, see the luna-service2 API documentation.

Example of watch response, when it is unblocked:

{
    "returnValue": true,
    "fired": true
}

The fired param in the response informs the client that DB8 contains one or more objects that satisfy the watch query and that the client can retrieve those objects.

Sample workflow for the watch API:

Assume that you are developing a chat application.
The chat application creates a DB8 Kind com.chat.messages:1
The chat application will have 2 independent threads: A UI thread that shows messages and a reader thread, that recieves messages from the network.

  1. Phase: Applicatoin startup
    UI thread reads all objects from com.chat.messages:1 Kind and shows the messages to the end user.
  2. Phase: UI Blocks till new message arrive
    UI thread calls DB8 watch API call with query: processed=false. If the database does not have such objects, the UI thread is blocked in watch API call.
  3. Phase: reader thread recieves a new message
    The reader thread recieves messages over the network, stores those message into com.chat.messages:1 with set field processed=false.
  4. Phase: UI thread ublocked
    The Database unblocks watch API call (UI thread was blocked in watch API call on 2 step), the UI executes the query find with parameter processed=false
  5. Phase: UI thread processes the new message
    For each new object in the result set, the UI thread shows those object to the end user. To indicate, that each new object was processed and shown to the end user by the UI, UI thread set field processed=false and merge each object into database.
  6. Phase: UI thread is blocked again
    UI go to step 2

Collation:

Information is displayed in sorted order to enable users to easily find the items they are looking for. However, users of different languages might have very different expectations of what a "sorted" list should look like. Not only does the alphabetical order vary from one language to another, but it also can vary from document to document within the same language. For example, phonebook ordering might be different than dictionary ordering. String comparison is one of the basic functions most applications require, and yet implementations often do not match local conventions. Collation provides string comparison capability with support for appropriate sort orderings for each of the locales needed by a client.

Collation rule:

A RuleBasedCollator is built from a rule string which changes the sort order of some characters and strings relative to the default order. An empty string (or one with only white space and comments) results in a collator that behaves like the root collator.

Customization is specified via a string containing a set of rules. ICU implements the (CLDR) For more details see LDML collation rule syntax

Each rule contains a string of ordered characters that starts with an anchor point or a reset value. For example, "&a < g", places "g" after "a" and before "b", and the "a" does not change place. This rule has the following sorting consequences:

Without rule With rule
apple apple
Abernathy Abernathy
bird green
Boston bird
green Boston
Graham Graham

Note: Only the word that starts with "g" has changed place. All the words sorted after "a" and "A" are sorted after "g".

This is a non-complex example of a custom rule. Custom rules consist of zero or more rules and zero or more options. There must be at least one rule or at least one option. The rule syntax is discussed in more detail in the following sections.

Note: The custom rules override the UCA ordering. In addition, if a character is reordered, it automatically reorders any other equivalent characters. For example, if the rule "&e<a" is used to reorder "a" in the list, "á" is also greater than "é".

Syntax:

The following table summarizes the basic syntax necessary for most usages:

Symbol Example Description
< a < b Identifies a primary (base letter) difference between "a" and "b"
<< a << ä Signifies a secondary (accent) difference between "a" and "ä"
<<< a<<<A Identifies a tertiary difference between "a" and "A"
<<<< か<<<<カ Identifies a quaternary difference between "か" and "カ". (New in ICU 53.) ICU permits up to three quaternary relations in a row (except for intervening "=" identity relations).
= x = y Signifies no difference between "x" and "y".
& &Z Instructs ICU to reset at this letter. These rules will be relative to this letter from here on, but will not affect the position of Z itself.

For more information, see:

Collation can be specified in the putKind or the find API call.

Example of using collator with putKind - set default collation for kind:

luna-send -n 1 luna://com.webos.service.db/putKind '{
   "id": "com.webos.service.test:1",
   "owner":"com.webos.service.test",
   "indexes":[
       {"name":"sample",   "props":[ {"name":"sample"} ]},
       {"name":"testsample","props":[ {"name":"test"}, {"name":"sample"}]} ]}
   ],
   "collation" : "secondary"
}'

Internally, DB8 process strings via ICU. All ICU documentation about strings somewhat applies to db8 string processing.

Permissions:

DB8 are central storage for applications. Every application can not only store/retrieve data by itself, it can share and interact with other applications.

Application can share kind and grand permissions for any CRUD operator. For more information, see putPermissions API call documentation.

Quotas:

The function of quotas is to allocate limited disk space in a reasonable way for target device. Those limits are set by product developers via db8 configuration files.

In other words, quotas limit the amount of disk space that can be used by s certain application.
Every process can see its quota usage by using the quotaStats api call.

Encoding:

When the DB8 daemon starts, it uses UTF8 en_US.en_US encoding which is it's default encoding.

DB8 subscribes for com.webos.service.systemservice/getPreferences '{ "keys" : "locale"}' . If the systemservice does not exist on the platform or returns an error, DB8 will continue use UTF8 en_US.en_US encoding by default.

Disk Storage Logic:

When DB8 starts, it creates 2 activities in Activity Manager:

  • Sheduled space check
  • Garbage collector (purge)

Activity for space check will check for available storage space. If the free storage space is too low, DB8 will reject all new CRUD API calls with quota exceeded error. If the storage has enough free space, then on the next sheduled space check DB8 will continue to process CRUD API calls.

Garbage collector:

By default, DB8 does not remove objects from it's database, it only marks it for future delete. DB8 use this logic, as an update operation takes less resources compared with delete. Physical objects are removed when processed by the DB8 garbage collector.

The garbage collector can be called in 2 ways: by ActivityManager or directly by service.

On startup, DB8 dynamicly registers an activity to call the garbage collector.

If s client wants to delete an object and immediately free storage space, the client can specify the purge option in the del API call. The del API call with the purge paramater can be potentially slow.

Complexity for garbage collector: m*log(n), where m - count of objects marked for removal.

Error handling:

If DB8 cannot process method calls (internal error, bad params, no resources, etc) it always returns error in the following format:

  • returnValue - if an error occurs, it  will contain false
  • errorCode - code that indicates the cause of  the error
  • errorText   -  text representation of the error code

Error codes and description are provided for each method call. For example, if the client calls the load method with bad parameter:

luna-send -n 1 -f -m com.webos.service.configurator luna://com.webos.service.db/load '{"path" : "/tmp/dump.json" }'
{
     "returnValue": false,
     "errorCode": 2,  
     "errorText": "No such file or directory"
}

The above reponse indicates, that:

  • returnValue: false - method call failed
  • errorCode2        - See method call load for more details on error code 2
  • errorText: No such file or directory - A quick textual explanation of the error

Basic API functions:

It provides the following data management functions:

  • Add objects
  • Update objects
  • Delete objects
  • Query objects 
  • Manage access to objects within the database

Open All


batch

Description

The batch method enables apps to execute multiple database operations in one service request. It allows only the following database operations:

  • put
  • get
  • del
  • find (without a watch)
  • merge 

Atomicity is NOT guaranteed across batched operations.

Parameters

Name

Required

Type

Description

operations Required Object array: BatchOperation

The operations parameter contains the list of database operations to perform.

Call Returns

Name

Required

Type

Description

batchResponse Optional Object: BatchResponse

If DB8 modifies any record, status of the executing batch will be returned in a BatchResponse object

errorCode Optional Number

The error code for the failed operation.

errorText Optional String

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

returnValue Required Boolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details

Error References

Error Code

Error Text

Error Description

-3982 db: invalid operation in batch

This message implies that an incorrect or an unsupported database operation was specified in the operations parameter. 

-3984 No required key: "method"

This message implies that the required database operations name is missing.

-3984 No required key: "params"

This message implies that the required parameters for a database operation is missing.

Example

luna-send -n 1 -f luna://com.webos.service.db/batch

'{

"operations":[

{

"method":"put",

"params":{

"objects":[

{

"_kind":"com.webos.service.test:1",

"sample":"sample1",

"test":"test1"

}

]

}

},

{

"method":"merge",

"params":{

"query":{

"from":"com.webos.service.test:1",

"where":[

{

"prop":"sample",

"op":"=",

"val":"sample1"

}

]

},

"props":{

"sample":"sample2",

"test": "test2"

}

}

}

]

}'

 

Result of exec of command:

{

"responses": [

{

"returnValue": true,

"results": [

{

"id": "J8qx+EwdBs7",

"rev": 2

}

]

},

{

"count": 1,

"returnValue": true

}

],

"returnValue": true

}


compact

Description

The compact method invokes the the low level garbage collector. When DB8 executes a del operation without Purge:True param, it only marks the object as to be deleted. The object will be removed by DB8, when the garbage collector is called. To call the garbage collector manualy, the client can call the compact method.

This command is implemented only for the LevelDB and Sandwich engine.

Parameters

None

Call Returns

Name

Required

Type

Description

returnValue Required Boolean
  • If the method succeeds, returnValue will contain true.
  • If the method fails, returnValue will contain false

The method may fail because of one the error conditions described in the Error Codes Reference table of this method. See the Error Code Reference table for more information. 

errorCode Optional Number

The error code for the failed operation.

errorText Optional String

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3988 db: backup file is full

This message implies that the storage does not have free space.

-3997 db: corrupt database

This message implies that some part of the database is logically corrupted.

Example

luna-send -n 1 -f luna://com.webos.service.db/compact '{}'

 

Result of exec of command:

{

"returnValue": true

}


del

Description

The del method deletes JSON data objects from the database.

Apps can specify the objects to be deleted by providing:

  • a set of ids to be deleted
  • a DB8 query

Parameters

Name

Required

Type

Description

ids Optional String array

The ids parameter contains an array of JSON object ids that you wish to delete. If you do not wish to specify JSON object ids, you must specify a query in the query parameter.

query Optional Object: Query

The query parameter contains a query for a set of objects to be deleted. If you do not wish to specify a query, you must specify a list of JSON object ids in the ids parameter.

purge Optional Boolean

The default value of the purge parameter is false.

  • If the purge parameter is set to false, the target objects will only be marked for deletion. Objects marked for deletion can still be restored. They will be purged permanently only when an administrative purge operation is run.
  • If the purge parameter is set to true, the target objects will be deleted permanently immediately. 

Call Returns

Name

Required

Type

Description

results Optional Object array: PutResponse

When the del method succeeds, and the objects to be deleted were specified as a list of JSON object ids, the del method will return a list of deleted ids.

count Optional Number

When the del method succeeds, and the objects to be deleted were specified as a query, the del method will return a count of deleted objects.

returnValue Required Boolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCode Optional Number

The error code for the failed operation.

errorText Optional String

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3963 db: permission denied

This message implies that the app does not have permission to delete the specified object. 

-3965 db: no index for query

This message implies that the query is referring to an index that does not exist for the specified kind. 

-3962 db: quota exceeded

This message implies that there is no space left on the device to complete this operation. It is recommended that the app should call the method again with purge set to true.

Example

Del by ids

luna-send -n 1 -f luna://com.webos.service.db/del '{"ids" :["J8rBI6u7uh+"]}'

---

Result of execution

{

"returnValue": true,

"results": [

{

"id": "J8rBI6u7uh+"

}

]

}

--

Del by query:

luna-send -n 1 -f luna://com.webos.service.db/del '{"query" : { "from" : "com.webos.service.test:1"}}'

---

Result of execution

{

"count": 11,

"returnValue": true

}


delKind

Description

The delKind method deletes a Kind from the database. Deleting a Kind deletes ALL data objects of that Kind.

Parameters

Name

Required

Type

Description

idRequiredString

The id parameter contains the id of thw kind the app wants to delete.

Call Returns

Name

Required

Type

Description

returnValueRequiredBoolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCodeOptionalNumber

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3970db: kind not registered

This message implies that the specified kind doesn't exist in the database.

-3999db: access denied

This message implies that the specified kind exists in the database, however the app does not have the delete permissions. 

Example

luna-send -n 1 -f -a com.webos.service.configurator luna://com.webos.service.db/delKind '{"id" : "com.webos.service.test:1"}'

Result of execution

{

"returnValue": true

}


dump

Description

The dump method is used to backup a database. The file created by the dump method typically contains JSON statements to recreate all of the Kinds and data of the database from which they have been dumped.

Parameters

Name

Required

Type

Description

pathRequiredString

Path to the dump file

Call Returns

Name

Required

Type

Description

countRequiredNumber

The total number of objects stored if the dump method succeeds.

returnValueRequiredBoolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCodeOptionalNumber

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3998db: backup file is full

This message implies that there is insufficent space to create a backup file or that the backup file size exceeds COUNT limit.

Example

luna-send -n 1 -f -a com.webos.service.configurator luna://com.webos.service.db/dump '{"path":"/tmp/dump.json"}'

Result of execution:

{

"count": 0,

"returnValue": true

}


find

Description

The find method returns a set of objects that match the query specified in the query parameter.

The app can specify the number of results to return. However, if the app does not want to specify a limit, it can set the count parameter to true. This will cause the find method to return the total number of results returned in the SuccessResponse1 object.

The app can also request to be notified if any of the returned results from the query change in the future. In order to receive change notifications, set the watch parameter to true.

The find method supports distinct groups enabling the app to remove duplicate objects.

Parameters

Name

Required

Type

Description

queryRequiredObject: Query

DB8 query for retrieving results.

countOptionalBoolean

The default value of the count parameter is false.

If the app did not specify a limit on the number of results to return, and wants to know the total number of results returned, the app should set the count parameter to true.

watchOptionalBoolean

The default value of the watch parameter is false

If an app wants to be notified about any change in the returned results, the app should set the watch parameter to true

Call Returns

Name

Required

Type

Description

SuccessResponse1OptionalObject: FindResponse

If the find method succeeds, the find method will return the SuccessResponse1​ object.

SuccessResponse2OptionalObject: NotificationResponse

If the watch parameter was set to true by the app, the find method will return the SuccessResponse2 object.

returnValueRequiredString

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCodeOptionalNumber

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3970db: kind not registered

This message implies that the specified kind is not registered in the database.

-3978db: invalid query

This message implies that the query syntax is correct, but contains misspelled commands or logical errors.

-3965db: no index for query

This message implies that the SELECT query contains field name(s) that do not exist for the selected kind. 

-3963db: permission denied

This message implies that the specified kind exists in the database, however the app does not have permissions to read the data for the specified kind.

Example

luna-send -n 1 -f luna://com.webos.service.db/find

'{

"query":{

"from":"com.webos.service.test:1",

"where":[

{

"prop":"sample",

"op":"=",

"val":"sample1"

}

]

}

}'

---

Result:

{

"returnValue": true,

"results": [

{

"_rev": 19,

"sample": "sample1",

"test": "test1",

"_id": "J8rKQDOvxdF",

"_kind": "com.webos.service.test:1"

},

{

"_rev": 21,

"sample": "sample1",

"test": "test1",

"_id": "J8rKTaBClIo",

"_kind": "com.webos.service.test:1"

}

]

}


get

Description

The ​get method retrieves JSON data objects by ids. This is the fastest way to retrieve data.

Parameters

Name

Required

Type

Description

idsRequiredString array

Ids of the JSON data objects to retrieve.

Call Returns

Name

Required

Type

Description

resultsRequiredObject array

If the get method succeeds, it will return the array of objects.

returnValueRequiredBoolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCodeOptionalNumber

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3999db: access denied

This message implies that the specified object exists in the database, but the app does not have permissions to access the object.

-3950db: I/O error

This message implies that it is not possible to read from the database and that this is a critical error. 

Example

luna-send -n 1 -f luna://com.webos.service.db/get '{"ids" : ["J8rKTaBClIo"]}'

Result of execution:

{

"returnValue": true,

"results": [

{

"_rev": 21,

"sample": "sample1",

"test": "test1",

"_id": "J8rKTaBClIo",

"_kind": "com.webos.service.test:1"

}

]

}


getProfile

Description

Get profiling data for applications. Profile data includes the queries made and related information such as request time and response time.

Note: This method is available only in the develop release.

Parameters

Name

Required

Type

Description

applicationOptionalString

Name of application for which to get profile data.

  • If no name is specified, returns the the profile data for the current application.
  • If name is given as *, returns profile data for all applications. The caller application must have admin permissions.
queryOptionalObject: Query

Additional filters for retrieving profile data.

Call Returns

Name

Required

Type

Description

returnValueRequiredBoolean

Indicates the status of the operation.

  • True - Indicates success of the operation.
  • False - Indicates failure in the operation. The details of the failure are provided in the errorCode and errorText fields of the response.
SuccessResponse1OptionalString

If the method succeeds, the relevant details are returned in the response.

errorCodeOptionalNumber

Indicates the error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation.

Error References

Error Code

Error Text

Error Description

-3970db: kind not registered

The specified kind is not registered in the database.

-3978db: invalid query

The query syntax is correct but contains misspelled commands or logical errors.

-3965db: no index for query

The SELECT query contains field name(s) that do not exist for the selected kind.

-3963db: permission denied

The specified kind exists in the database, but the app does not have permissions to read the data for the specified kind.

-3946db: profiling not enabled for this application

Application profiling is disabled. Enable it by using the "profile" method.

-3947db: profiling feature is not supported

DB8 profiling feature is not supported.

Example

Example 1: Get profile data for application "com.webos.service.test:3"

luna-send -n 1 -a com.webos.service.test:3 luna://com.webos.service.db/getProfile '{ }' -f

{
    "returnValue": true,
    "results": [
        {
            "memory_info": "%MEM=1.01, VSS=70104, RSS=7888, SHR=6264",
            "application": "com.webos.service.test:3",
            "category": "/",
            "method": "get",
            "_rev": 5366,
            "payload": {
                "ids": [
                    "J8rKTaBClIo"
                ]
            },
            "_kind": "com.webos.service.test:3.profile:1",
            "_id": "+++11eN6jck",
            "time": "0.083334"
        },
        {
            "memory_info": "%MEM=1.01, VSS=70104, RSS=7888, SHR=6264",
            "application": "com.webos.service.test:3",
            "category": "/",
            "method": "put",
            "_rev": 5368,
            "payload": {
                "objects": [
                    {
                        "sample": "sample1",
                        "test": "test1",
                        "_id": "14f9",
                        "_kind": "com.webos.service.tes:3t.profile:1"
                    }
                ]
            },
            "_kind": "com.webos.service.test:3.profile:1",
            "_id": "+++19DpixTc",
            "time": "0.066458"
        },
        {
            "_rev": 5370,
            "sample": "sample1",
            "test": "test1",
            "_id": "+++1BZDmwCg",
            "_kind": "com.webos.service.test:3.profile:1"
        },
        {
            "memory_info": "%MEM=1.01, VSS=70104, RSS=7888, SHR=6264",
            "application": "com.webos.service.test:3",
            "category": "/",
            "method": "put",
            "_rev": 5371,
            "payload": {
                "objects": [
                    {
                        "sample": "sample1",
                        "test": "test1",
                        "_id": "14fc",
                        "_kind": "com.webos.service.test:3.profile:1"
                    }
                ]
            },
            "_kind": "com.webos.service.test:3.profile:1",
            "_id": "+++1BZHnhrV",
            "time": "0.321958"
        }
    ]
}

Example 2: Get profile data for an application for only get commands.

luna-send -n 1 -a com.webos.service.test:3  luna://com.webos.service.db/getProfile '{"application":"com.webos.service.test:3","query":{"where":[{"prop":"method","op":"=","val":"get"}]}}'
 -f

{
    "returnValue": true,
    "results": [
        {
            "memory_info": "%MEM=1.01, VSS=70104, RSS=7888, SHR=6264",
            "application": "com.webos.service.test:3",
            "category": "/",
            "method": "get",
            "_rev": 5366,
            "payload": {
                "ids": [
                    "J8rKTaBClIo"
                ]
            },
            "_kind": "com.webos.service.test:3.profile:1",
            "_id": "+++11eN6jck",
            "time": "0.083334"
        }
    ]
}


load

Description

The load method restores a database from a dumped JSON file.

Parameters

Name

Required

Type

Description

pathRequiredString

The complete path of the JSON dump file. For example: /tmp/dump.json

Call Returns

Name

Required

Type

Description

countRequiredNumber

Count of objects loaded from the dump file

returnValueRequiredBoolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCodeOptionalNumber

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-987path too long

This message implies that the path provided for the dump file is too long

2No such file or directory

File specified in path parameter not found or DB8 doesn't have permissions to read it

Example

luna-send -n 1 -f luna://com.webos.service.db/load '{"path": "/tmp/dump.json"}'

Result of execution

{

"count": 0,

"returnValue": true

}


merge

Description

The merge method updates the properties of existing objects.

The objects can be specified in one of the following ways:

  • A query
  • An array of IDs

Parameters

Name

Required

Type

Description

objectsOptionalObject array

The object parameter is an array of objects, each object will have an id and key/value pairs that represents the object properties the app needs to merge. The objects parameter is required if the query​ parameter is not specified.

queryOptionalObject: Query

The query parameter is a Query object specificying the set of objects whose properties the app wants to update.

The query parameter is required if the object parameter is not specified.

propsOptionalObject

The props parameter is an object with key/value pairs that specify the set of properties to be merged into the existing object(s) specified in the query parameter. If the app specifies the properties in the prop parameter, the query​ is required.

Call Returns

Name

Required

Type

Description

resultsOptionalObject array: PutResult

If the objects parameter was specified, and the merge method succeeds, merge will return the ids and revisions of the updated object.

countOptionalNumber

If the query parameter was specified, and the merge method succeeds, merge will return the count of updated objects.

returnValueRequiredBoolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCodeOptionalNumber

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3961db: quota exceeded

 This message implies that the app has exceeded its quota or there is no free space available on the device.

-3963db: permission denied

This message implies that the app does not have permission to modify the specified objects.

-3965db: no index for query

This message implies that the query contains a SELECT for object properties that do not have an index associated with them. 

Example

Example, how to update similar object

luna-send -n 1 -f -a com.webos.service.configurator luna://com.webos.service.db/merge

'{

"objects":[

{

"_id":"J8rKTaBClIo",

"test":"test1",

"sample":"sample_updated_value"

}

]

}'

Result of execution:

{

"returnValue": true,

"results": [

{

"id": "J8rKTaBClIo",

"rev": 23

}

]

}

-------------

Example, how to update in all object with filed "sample" and value "sample1" to value "sample_updated_value"

luna-send -n 1 -f -a com.webos.service.configurator luna://com.webos.service.db/merge '

{

"query":{

"from":"com.webos.service.test:1",

"where":[

{

"prop":"sample",

"op":"=",

"val":"sample1"

}

]

},

"props":{

"sample":"sample_updated_value"

}

}'

Result of execution:

{

"count": 2,

"returnValue": true

}


mergePut

Description

The mergePut method updates the properties of existing objects. If an object doesn't exist, new one will be created in database.

The object to be updated can be specified in one of the following ways:

  • A query
  • An array of IDs

Parameters

Name

Required

Type

Description

objectsOptionalObject array

The object parameter is an array of objects, each object will have an id and key/value pairs that represent the object properties the app needs to merge. 

This is required if the query​ parameter is not specified.

queryOptionalObject: Query

The query parameter is a Query object specificying the set of objects whose properties the app wants to update.

The query parameter is required if the object parameter is not specified.

propsOptionalObject

The props parameter is an object with key/value pairs that specify the set of properties to be merged into the existing object(s) specified in the query parameter. If the app specifies the properties in the prop parameter, the query​ is required.

Call Returns

Name

Required

Type

Description

resultsOptionalObject: PutResult

If the objects parameter was specified, and the merge method succeeds, merge will return the ids and revisions of the updated object.

countOptionalNumber

If the query parameter was specified, and the merge method succeeds, merge will return the count of updated objects.

returnValueRequiredBoolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCodeOptionalNumber

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3961db: quota exceeded

This message implies that the app has exceeded its quota or there is no free space available on the device.

-3963db: permission denied

This message implies that the app does not have permission to modify the specified objects.

-3965db: no index for query

This message implies that the query contains a SELECT for object properties that do not have an index associated with them. 

Example

Example, how to insert object, if it doesn't exists in database

luna-send -n 1 -f -a com.webos.service.configurator luna://com.webos.service.db/mergePut
'{

"objects":[

{

"_id":"J8rKTaBClIo",

"test":"test1",

"sample":"sample_updated_value"

}

]

}'

Result of execution:

{

"returnValue": true,

"results": [

{

"id": "J8rKTaBClIo",

"rev": 23

}

]

}


profile

Description

Enables or disables DB8 profiling for an application. When enabled, profiling data is stored for the application.

You can enable DB8 profiling using one of the following approaches:

- Self enabling: In this approach, the 3rd-party application enables profiling on itself (see example 1).

- Enable profiling using admin-privileged applications: In the approach, an admin-privileged application controls DB8 profiling for 3rd-party applications. Use this approach when you want the admin to conrol the profiling of 3rd-party applications. You can choose to enable profiling for a single application or for all 3rd-party applications. See example 2 and 3.

Note: This method is available only in the develop release.

Parameters

Name

Required

Type

Description

enableOptionalBoolean

Status of DB8 profiling.

Possible values: TRUE, FALSE

Default value: TRUE

applicationOptionalString

Name of application to be profiled.

  • If no name is specified, the current/caller application is profiled.
  • If name is given as *, all applications are profiled. The caller application must have admin permissions.

Call Returns

Name

Required

Type

Description

returnValueRequiredBoolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details.
errorCodeOptionalNumber

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3947db: profiling feature is not supported

Profiling feature is not supported.

-3963db: permission denied

The application does not have permission to enable/disable profiles for other applications.

-3945db: profiling restricted by admin for this application

Profiling restricted by admin for this application.

Example

Example 1: 3rd-party application "com.webos.testApp" enables profiling for itself.

luna-send -f -a com.webos.testApp -n 1 luna://com.webos.service.db/profile '{"enable":true}'

 

Example 2: Admin-privileged application (com.webos.service.configurator) enables profiling for all 3rd-party applications.

luna-send -n 1 -a com.webos.service.configurator luna://com.webos.service.db/profile '{"enable":true, "application":"*"}'

 

Example 3: Admin-privileged application (com.webos.service.configurator) enables profiling for the "com.webos.testApp" 3rd-party application.

luna-send -n 1 -a com.webos.service.configurator luna://com.webos.service.db/profile '{"enable":true, "application":"com.webos.testApp"}'


purge

Description

The purge method invokes the garbage collector. The purge method will:

  • Remove all objects that were marked for deletion
  • Perform a space check, and remove all temporary data

Parameters

None

Call Returns

Name

Required

Type

Description

returnValueRequiredBoolean

If the purge  method succeeds, returnValue will contain true.
If the purge  method fails, returnValue will contain false. The purge method may fail because of:

  • Insufficent disk space
  • I/O error
countRequiredNumber

count contains the total number of objects that were permanently deleted by the purge method.

Example

luna-send -n 1 -f luna://com.webos.service.db/purge '{}'

Result of execution

{

"count": 0,

"returnValue": true

}


purgeStatus

Description

The purgeStatus method returns the status of the last run purge command. If the last run purge command was successful, the objects were permanently deleted, and the purgeStatus method will return the updated database revision number.

Parameters

None

Call Returns

Name

Required

Type

Description

returnValue Required Boolean

If the purgeStatus  method succeeds, returnValue will contain true.

If the purgeStatus  method fails, returnValue will contain false.

rev Required Number

If the purgeStatus method is successful, rev will contain the updated database revision number.

If the purgeStatus method fails, rev will contain database revision number before the purge.


put

Description

The put method stores JSON data objects of a particular Kind into the database. The put method will:

  • Assign an id field to each object, if it was not set.
  • Return the id and rev for each stored object.

Parameters

Name

Required

Type

Description

objectsRequiredObject array

List of JSON data objects of a particular kind that the app wants to store in the database.

Call Returns

Name

Required

Type

Description

resultsRequiredObject array: PutResponse

If the object was inserted, results will contain id and revision of the inserted object

returnValueRequiredBoolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCodeOptionalNumber

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3962db: quota exceeded

 This message implies that the app has exceeded its quota or there is no free space available on the device.

-3970db: kind not registered

This message implies that the kind for the specified object is not registered with the database.

-3963db: permission denied

This message implies that the app does not have permission to save objects of a specified kind.

Example

luna-send -n 1 -f -a com.webos.service.configurator luna://com.webos.service.db/put 

'{

"objects":[

{

"_kind":"com.webos.service.test:1",

"sample":"sample1",

"test":"test1"

}

]

}'

Result of command execution:

{

"returnValue": true,

"results": [

{

"id": "J8rTIa65u++",

"rev": 27

}

]

}


putKind

Description

The putKind method registers a kind with the database.
Kinds define the owner, and the indexes for a JSON data object. Indexes can be composed of single or multiple properties. When you create your index, be aware that queries can only return results that are indexed, and are contiguously ordered.
If your app or service wants to be notified only when a subset of an object's properties are updated, then you can use revision sets.
If your app or service creates objects that other apps or services need to access, then see the putPermissions method for more information.

Parameters

Name

Required

Type

Description

id Required String

Id of the kind to be registered with the database.

owner Required String

Onwer of the kind, can be any one of the following values:

  • The service's bus address
  • The app's app ID

Only the owner has permission to modify the kind.

Syntax Optional Object

JSON Syntax for data objects of a specific kind. If set, this kind's data objects are validated before being stored. For details refer to http://json-schema.org/documentation.html

sync Optional Boolean

The sync parameter allows apps to enable backing up and restoring specific kinds of objects. 

The default value for the sync parameter is false.

extends Optional String array

List of ids of parent kinds from which the kind has been derived.

indexes Optional Object: IndexClause

The indexes parameter contains indexes for the kind.

revsets Optional Object array: RevSetClause

List of database revision sets.

Call Returns

Name

Required

Type

Description

returnValue Required Boolean
  • If the method succeeds, returnValue will contain true.
  • If the method fails, returnValue will contain false

The method may fail because of one the error conditions described in the Error Codes Reference table of this method. See the Error Code Reference table for more information. 

errorCode Optional Number

errorCode contains the error code if the method fails. The method will return errorCode only if it fails.

See the Error Codes Reference of this method for more details.

errorText Optional String

errorText contains the error text if the method fails. The method will return errorText only if it fails.

See the Error Codes Reference of this method for more details.

Error References

Error Code

Error Text

Error Description

-3981 db: invalid owner for kind

This message implies that the specified owner does not have permissions to add or modify the specified kind. 

-3962 db: quota exceeded

This message implies that app has exceeded its quota or does not have enough disk space available to create the specified kind.

Example

luna-send -n 1 luna://com.webos.service.db/putKind

'{

"id": "com.webos.service.test:1",

"owner":"com.webos.service.test",

"indexes":[

{"name":"sample", "props":[ {"name":"sample"} ]},

{"name":"testsample","props":[ {"name":"test"}, {"name":"sample"}]} ]}

]

}'

 

Result of command execution:

{

"returnValue": true

}


putPermissions

Description

The putPermissions method enables other apps or services to access an app's stored DB8 data. The app can give permissions to access data objects of a specific Kind.

Parameters

Name

Required

Type

Description

typeRequiredString

Must be set to db.kind.

objectRequiredString

The DB8 kind of the object for which the app wants to provide access.

callerRequiredString

The id of the app or service that the app is granting permission to access its data.

operationsRequiredObject: operation

Database operations the app is granting permissions for.

createOptionalString

To grant create permission, set the create parameter to allow.

readOptionalString

To grant read permission, set the read parameter to allow.

updateOptionalString

To grant update permission, set the update parameter to allow.

deleteOptionalString

To grant delete permission, set the delete parameter to allow.

Call Returns

Name

Required

Type

Description

returnValueRequiredBoolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCodeOptionalNumber

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3999db: access denied

This message implies that the app cannot modify the permissions of the specified kind. 

Example

luna-send -n 1 -f luna://com.webos.service.db/putPermissions

'{

"permissions":[

{

"operations":{

"read":"allow",

"create":"allow",

"update":"allow",

"delete":"allow"

},

"object":"com.webos.service.test:1",

"type":"db.kind",

"caller":"com.webos.service.testapp"

}

]

}'

Result of command execution:

{

"returnValue": true

}


putQuotas

Description

The putQuotas method provides the ability to update a quota's current service limits at runtime. This service is used by private webOS services to increase/decrease quotas for critical webOS services.

Parameters

Name

Required

Type

Description

quotasRequiredObject array: putQuotas

List of quotas

Call Returns

Name

Required

Type

Description

returnValueRequiredBoolean

If the putQuotas  method succeeds, returnValue will contain true.

If the putQuotas  method fails, returnValue will contain false. The putQuotas  method may fail because of:

  • Insufficient free disk space
  • Disk I/O
  • Not found kind

Example

luna-send -f -n 1 -a com.webos.service.configurator luna://com.webos.service.db/putQuotas '{ "quotas" : [ {"owner" : "com.test", "size" : 1000000 } ] }'

{

"returnValue": true

}

And after executing of this command, quotas will be:

luna-send -f -n 1 -a com.webos.service.configurator luna://com.webos.service.db/quotaStats '{}'

{

"returnValue": true,

"results": {

"com.test": {

"size": 1000000,

"used": 0

}

}

}


quotaStats

Description

The quotaStats method returns information about a service's used limits.

Parameters

None

Call Returns

Name

Required

Type

Description

returnValueRequiredBoolean

If the quotaStats method succeeds, returnValue will contain true.

If the quotaStats method fails, returnValue will contain false. The quotaStats method may fail because of:

  • Internal db8 logic broken
resultsRequiredObject: quotaStatsResult

Returns information about a service's quota.

Example

luna-send -n 1 -f luna://com.webos.service.db/quotaStats '{}'

Result of command execution

{

"returnValue": true,

"results": {

"*": {

"size": 10485760,

"used": 1371

},

"com.webos.*": {

"size": 10485760,

"used": 0

},

"com.webos.testapp": {

"size": 52428800,

"used": 0

}

}

}


removeAppData

Description

The removeAppData method removes all data associated with the given owner. In other words, the method removes all Kinds that have specified owner.

Parameters

Name

Required

Type

Description

ownersRequiredString array

Owner(s) of kinds to delete. Kinds having given owners will be removed from the database. 

Call Returns

Name

Required

Type

Description

returnValueRequiredBoolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCodeOptionalString

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3980db: invalid owner for kind

The value specified in owners input parameter is invalid or Kinds associated with the owners do not exist. 

Example

luna-send -n 1 luna://com.webos.service.db/removeAppData '{"owners" : [ "com.webos.service.test:1" ]}'

{

    "returnValue": true

}


reserveIds

Description

When a client service creates objects that have references beetween each other, the service can ask the database through the reserveIds method to pregenerate ids of objects. The client service can use such ids as objects, and db8 will use those ids when objects are inserted into the database.

By default, DB8 configured to reserve maximum [0:1000] ids, but this limit can vary depending on the platform.

Parameters

Name

Required

Type

Description

countRequiredNumberNumber of Ids to reserve.

Call Returns

Name

Required

Type

Description

idsRequiredString array

If the reserveIds method succeeds it will return list of reserverd ids.

If the reserveIds method fails, errorCode will contain reason for its failure.

returnValueRequiredBoolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCodeOptionalNumber

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3968db: malformed id

This message implies that the specified count contains an invalid value. 

-3967cannot reserve more than 1000 ids

Client tries to reserve too many object ids. By default, DB8 is configured to reserve maximum [0:1000] ids, but this limit can vary depend of platform.

Example

luna-send -i -f luna://com.webos.service.db/reserveIds '{ "count" : 3 }'

 

Result of call:

{

"ids": [

"J9FJ12j0Usk",

"J9FJ12j18hJ",

"J9FJ12j1Mic"

],

"returnValue": true

}



stats

Description

The stats method returns detailed information about the storage space used by every service.

Parameters

None

Call Returns

Name

Required

Type

Description

returnValueRequiredBoolean

If the stats method succeeds, returnValue will contain true.

If the stats method fails, returnValue will contain false. The stats method may fail because of:

  • Internal DB8 error (internal stat doesn't exist)
resultsRequiredObject array: statsKindResult

Information about resource usage per kind

Example

luna-send -n 1 -f luna://com.webos.service.db/stats '{}'

 

Result of command exec:

{

"returnValue":true,

"results":{

"com.webos.service.test:1":{

"indexes":{

"barfoo":{

"size":0,

"delmisses":0,

"count":0

},

"foo":{

"size":0,

"delmisses":0,

"count":0

},

"_id":{

"size":0,

"delmisses":0,

"count":0

}

},

"objects":{

"size":0,

"count":0

}

}

}

}


watch

Description

The watch method watches for updates to the database that would change the results of a query.

Parameters

Name

Required

Type

Description

queryRequiredObject: Query

Query whose results the app wants to watch.

Call Returns

Name

Required

Type

Description

firedRequiredBoolean

If the watch method found any object by query, fired will contain true. 

Fired will never return false. 

returnValueRequiredBoolean

Indicates the status of operation. Possible values are:

  • true - Indicates that the operation was successful.
  • false - Indicates that the operation failed. Check the "errorCode" and "errorText" fields for details
errorCodeOptionalNumber

The error code for the failed operation.

errorTextOptionalString

Indicates the reason for the failure of the operation. See the "Error Codes Reference" section of this method for details.

Error References

Error Code

Error Text

Error Description

-3999db: access denied

 This message implies that the app does not have permissions to monitor the database.

Example

luna-send -i -f -a com.webos.service.configurator luna://com.webos.service.db/watch

'{

"query":{

"from":"com.webos.service.test:1",

"where":[

{

"prop":"sample",

"op":"=",

"val":"sample1"

}

]

}

}'

 

When object will found with such criteria, will be returned:

{

"returnValue": true,

"fired": true

}


Objects

BatchOperation

Method and params for batch operation.

Name

Required

Type

Description

methodRequiredString

Database operation to perform.

Allowed values are:

  • del
  • find
  • get
  • merge
  • put
paramsRequiredString

List of parameters for the database operation.

BatchResponse

Response to batch operation.

Name

Required

Type

Description

returnValueRequiredBoolean
  • If the method succeeds, returnValue will contain true.
  • If the method fails, returnValue will contain false. 

The method may fail because of one the error conditions described in the Error Codes Reference table of this method. See the Error Code Reference table for more information.

responsesRequiredArray

Array of responses for each of the operations in the batch.

errorCodeOptionalNumber

errorCode contains the error code if the method fails. The method will return errorCode only if it fails.

See the Error Codes Reference of this method for more details.

errorTextOptionalString

errorText contains the error text if the method fails. The method will return errorText only if it fails.

See the Error Codes Reference of this method for more details.

Query

Defines a db8 query.

Name

Required

Type

Description

selectOptionalString arrayArray of property names to return.
fromRequiredStringName of kind to retrieve results from.
whereOptionalObject array: WhereClause

Array of clauses to test.

orderByOptionalStringOrder results on this property.
descOptionalBoolean

To display query results in decending order, set desc to true.
To display query results in ascending, set desc to false.

The default value of desc is false.

incDelOptionalBoolean

To display query results with deleted objects, set incDel to true.
To display query as is, set incDel to false.

The default value of incDel is false.

Note: You can only request this if the incDel field was true when you created your indexes during a putKind operation. Otherwise, the query fails with a "no index for this query" message.

limitOptionalNumber

Specifies maximum number of results to return (0-500). Default is 500

pageOptionalString

Page key returned by previous query.

filterOptionalObject array: FilterClause

Array of clauses - works only in the search method - identical to WhereClause. Can be used along with where to perform a range search.

PutResponse

Indicates success of operation and returns id and rev fields for each object.

Name

Required

Type

Description

returnValueRequiredBoolean
  • If the method succeeds, returnValue will contain true.
  • If the method fails, returnValue will contain false

The method may fail because of one the error conditions described in the Error Codes Reference table of this method. See the Error Code Reference table for more information. 

resultsRequiredObject array: PutResult

Array of objects containing the id and rev of each object that was put.

FindResponse

Response to a find objects operation.

Name

Required

Type

Description

resultsRequiredAnyArray of db8 kind data objects. What is returned depends on the query and what is stored.
countOptionalNumberNumber of results that would have been returned if a limit had not been specified.
nextOptionalStringKey to pass as query's "page" property when retrieving next page of results.

NotificationResponse

Notifies caller of change in query results returned from a "find" call.

Name

Required

Type

Description

firedRequiredBoolean

Change notification flag.

GetResponse

Parameters for get objects operation response.

Name

Required

Type

Description

resultsRequiredObject array

Returns array of stored db8 data objects.

IndexClause

Used in the putKind call for creating kind object indexes. Note that indexes determine the type of queries your app can make. See Queries and Indexing for more information. Set the incDel flag to true if you want future queries to return marked as deleted objects. Objects are not completely deleted until an administrative purge operation takes place.

Name

Required

Type

Description

nameRequiredStringIndex name
propsRequiredObject array: IndexPropClause

Array of properties to index together.

incDelOptionalBoolean

To display query results with deleted objects, set incDel to true.
To display query results without deleted objects, set incDel to false.

The default value of incDel is false.

Note: You can only request this if the incDel field was true when you created your indexes during a putKind operation. Otherwise, the query fails with a "no index for this query" message.

RevSetClause

Defines a revision set—subset of an object's properties that your app can be notified about when one of the properties is modified.

Name

Required

Type

Description

nameRequiredStringName of the revision set (unique to this kind).
propsRequiredObject array: RevSetPropClause

Array of properties to include in revision set.

operation

Object used to represent a batch operation to run.
(This object has different format as target. Following object example is for the target.)

Name

Required

Type

Description

methodRequiredStringoperation being requested.
paramsRequiredAny arrayParams will depend on the type of operation being requested.

putQuotas

Represent Kind owner and maximum allowed DB8 storage usage.

Name

Required

Type

Description

ownerRequiredString

Name of service

sizeRequiredNumber

Size in bytes of allowed quota

quotaStatsResult

Information about used quotas.

Name

Required

Type

Description

sizeRequiredNumber

Size of quotas in bytes

usedRequiredNumber

Used quotas by service in bytes

ReserveIdsResponse

Contains operation success or failure flag and array of reserved db8 IDs returned from "reserveIds" call.

Name

Required

Type

Description

idsOptionalString array

Array of reserved IDs.

statsKindResult

Information about kind usage.

Name

Required

Type

Description

indexesRequiredString

Statistic for each index, created for kind

_idRequiredString

Statistic for each id, created for kind

objectsRequiredString

Statistic about objects, relative to kind

WhereClause

Defines a SQL-like JSON where clause for a db8 Query.

Name

Required

Type

Description

propRequiredStringName of property to test.
opRequiredStringTest operator. Must be one of the following: "<", "<=", "=", ">=", ">", "!=", "%", "?", "%%" (less than, less than or equal, equals, greater than or equal, greater than, not equal, wildcard, and full-text) The "%" operator (aka - the prefix operator) will return all matches beginning with the value specified. The "%%" operator is used to locate substrings or partial string matches.
valRequiredAnyValue to test against.
collateOptionalStringIndicates the string comparison routine used to order the results. See the collate field in the IndexPropClause data structure for more information.

FilterClause

Definition of the Filter clause that is part of the Query object.

Name

Required

Type

Description

propRequiredString

Name of property to test.

opRequiredString

Test operator. Must be one of the following: "<", "<=", "=", ">=", ">", "!=", "?", "%", "%%" (less than, less than or equal, equals, greater than or equal, greater than, not equal, wildcard, full-text, and partial-text) The "%" operator (aka - the prefix operator) will return all matches beginning with the value specified. The "%%" operator is used to locate substrings or partial string matches.

valRequiredAnyValue to test against.
collateOptionalStringIndicates the string comparison routine used to order the results. See the collate field in the IndexPropClause data structure for more information.

PutResult

Contains "id" and "rev" fields in PutResponse for JSON data object.

Name

Required

Type

Description

idRequiredAnyID of the object that was put.
revRequiredAnyObject's revision ID. Every db8 object has this ID field. db8 maintains a global rev id counter that is incremented every time a db8 object is created or updated.

IndexPropClause

Defines index property for IndexClause

Name

Required

Type

Description

nameRequiredString

Name of property being indexed.

collateOptionalString

Indicates the string comparison routine used to order the index. Must be one of the following: default—Does binary comparison. primary—Compares base characters (for example, "a" < "b") without considering accents, case, or tone marks. secondary—Accents in the characters are considered secondary differences (for example, "as" < "às" < "at"). Other differences between letters can also be considered secondary differences, depending on the language. A secondary difference is ignored when there is a primary difference anywhere in the strings. tertiary—Upper and lower case differences in characters are distinguished at the tertiary level (for example, "ao" < "Ao" < "aò"). In addition, a variant of a letter differs from the base form on the tertiary level (such as "A" and "?"). A tertiary difference is ignored when there is a primary or secondary difference anywhere in the strings.

defaultOptionalAnyDefault value to set for this property at insertion time, if not present.
tokenizeOptionalStringIndicates if words in strings should be broken up, i.e., should "Hello World" become "Hello" and "World" for purposes of indexing. Must be one of the following: none—Does not tokenize. default—Use the default for the locale (which may strip stop-words). Stop-words are common words that are stripped for purposes of indexing, i.e., "the", "a", "an", "is", etc. all—Tokenizes all words.
typeRequiredString"single" or "multi". Single property or multiple properties.

RevSetPropClause

A property in a RevSetClause.

Name

Required

Type

Description

nameRequiredStringName of property to include in revision set.

listActiveMedia

List of media devices, registered by db8

Name

Required

Type

Description

deviceIdRequiredString

UUID of device

deviceUriRequiredString

The physical device path. For example: /tmp/usb/sda/sda1

mountPathRequiredString

Path to device pount point

shardIdRequiredString

Base64 encoded Id of shard

activity

Information about registered Activity in ActivityManager for calling DB8 internal/scheduledPurge API call

Name

Required

Type

Description

activityIdRequiredNumber

ID of Activity, that registered in ActivityManager


Except as noted, this content is licensed under Creative Commons Attribution 4.0 and sample code is licensed under Apache License 2.0.