dataservice
Module dataservice
API
ballerina/dataservice Ballerina library
Overview
The ballerina/dataservice package supports the data services that bal persist generates from a persist model. A data service exposes the entities of the model over a protocol such as HTTP, with no hand-written service code.
The package holds the @dataservice:Expose annotation, which selects the entities a data service exposes and the actions each allows, and the protocol-neutral runtime that generated services call.
Key Features
@dataservice:Exposeselects the entities a data service exposes, the actions each allows and their scopes@dataservice:ReadOnly,@dataservice:Immutableand@dataservice:Internalcontrol what the service does with a field- A compiler plugin checks the annotations while the model is edited and when
bal persistgenerates - A protocol-neutral runtime for filters, sorting, paging,
fields, relation reads, value conversions and the error body
Quick start
-
Add the persist entry with a data service to the package:
bal persist add --datastore h2 --dataservice http -
Annotate each entity to expose in
persist/model.bal. A bare annotation allows every action:import ballerina/dataservice; import ballerina/persist as _; @dataservice:Expose type Employee record {| readonly int id; string name; |}; @dataservice:Expose {operations: [dataservice:READ]} type Department record {| readonly int id; string name; |}; -
Build the package. The persist client and the data service are generated into
generated/:bal build
For the details, see the specification.
Functions
attachMany
function attachMany(map<anydata> partial, Entity entity, string relation, map<anydata>[] related, boolean hasMore, string[] fields)Adds the related records of a to-many relation to one narrowed record, as a list with hasMore.
Parameters
- partial map<anydata> - The narrowed record, which is changed in place
- entity Entity - The entity of the record
- relation string - The relation field
- related map<anydata>[] - The records that
toIncludeQueryread, cut to the page bytrimToPage
- hasMore boolean - Whether more related records exist
- fields string[] - The field names to return
attachOne
function attachOne(map<anydata>[] partials, map<anydata>[] sources, Entity entity, string relation, map<anydata>[] related, string[] fields)Adds the related record of a to-one relation to each narrowed record of a page, or nil when it has none.
Parameters
- partials map<anydata>[] - The narrowed records, which are changed in place
- sources map<anydata>[] - The records as read, in the same order
- entity Entity - The entity of the records
- relation string - The relation field
- related map<anydata>[] - The records that
toIncludeQueryread
- fields string[] - The field names to return
bytesFromString
function bytesFromString(string value) returns byte[]|ConversionErrorConverts a base64 string to a byte[] value.
Parameters
- value string - The base64 string, with the standard alphabet and padding
Return Type
- byte[]|ConversionError - The decoded value, or a
ConversionErrorif the string is not base64
bytesToString
function bytesToString(byte[] value) returns stringConverts a byte[] value to a base64 string.
Parameters
- value byte[] - The value
Return Type
- string - The value in base64, with the standard alphabet and padding
checkConstraints
function checkConstraints(record {} value, string entity) returns DataserviceError?Checks the ballerina/constraint annotations of a record that a service converted from its wire type.
Parameters
- value record {} - The record, of a type that carries the model's constraint annotations
- entity string - The name of the entity
Return Type
- DataserviceError? - An
INVALID_INPUTerror body naming the field and the broken constraint, or()if none is broken
checkCreateSize
function checkCreateSize(int count, PageConfig config) returns DataserviceError?Checks that a create holds no more records than a page.
Parameters
- count int - The number of records to create
- config PageConfig - The page sizes of the data service
Return Type
- DataserviceError? - An
INVALID_INPUTerror body when there are too many records
checkFields
function checkFields(Entity entity, string[]? fields, boolean relations) returns DataserviceError?Checks the fields option of a read.
Parameters
- entity Entity - The entity to read
- fields string[]? - The field names to return
- relations boolean (default true) - Whether
fieldscan name the entity's relations and their fields, such asdepartment.name
Return Type
- DataserviceError? - An
INVALID_INPUTerror body whenfieldsis empty or names a field that cannot be returned
checkFiniteKey
function checkFiniteKey(string entity, KeyValue[] key) returns DataserviceError?Checks that every float value of a key is a finite number.
Parameters
- entity string - The name of the entity
- key KeyValue[] - The values of the record's key fields, in key order
Return Type
- DataserviceError? - An
INVALID_INPUTerror body when a value isNaNor infinite
civilFromString
function civilFromString(string value) returns Civil|ConversionErrorConverts an ISO 8601 date-time without an offset, such as 2024-01-02T10:15:30, to a time:Civil value.
Parameters
- value string - The date-time
Return Type
- Civil|ConversionError - The value, or a
ConversionErrorif the string is not a valid date-time without an offset
civilToString
Converts a time:Civil value to an ISO 8601 date-time without an offset, such as 2024-01-02T10:15:30.
Parameters
- value Civil - The value; its offset, if any, is not written
Return Type
- string - The date-time
dateFromString
function dateFromString(string value) returns Date|ConversionErrorConverts an ISO 8601 date, such as 2024-01-02, to a time:Date value.
Parameters
- value string - The date
Return Type
- Date|ConversionError - The value, or a
ConversionErrorif the string is not a valid date
dateToString
Converts a time:Date value to an ISO 8601 date, such as 2024-01-02.
Parameters
- value Date - The value
Return Type
- string - The date
isIncluded
Tells whether fields names a relation, alone or with its fields.
Return Type
- boolean - Whether the related records are included
orderByKeys
Puts records read by toKeysQuery in the order of their keys.
Parameters
- rows map<anydata>[] - The records, which are reordered in place
- entity Entity - The entity of the records
- keys KeyValue[][] - The key values of each record, in the order to put the records in
Return Type
- error? - An error when a record of a key is missing
selectFields
Narrows a record to the named fields and its key fields.
Parameters
- value map<anydata> - The record
- entity Entity - The entity of the record
- fields string[] - The field names to keep
Return Type
- map<anydata> - The narrowed record
timeOfDayFromString
function timeOfDayFromString(string value) returns TimeOfDay|ConversionErrorConverts an ISO 8601 time, such as 10:15:30 or 10:15:30.5, to a time:TimeOfDay value.
Parameters
- value string - The time
Return Type
- TimeOfDay|ConversionError - The value, or a
ConversionErrorif the string is not a valid time
timeOfDayToString
Converts a time:TimeOfDay value to an ISO 8601 time, such as 10:15:30 or 10:15:30.5.
Parameters
- value TimeOfDay - The value
Return Type
- string - The time
toErrorBody
function toErrorBody(error err, string entity, KeyValue[] key, string operation) returns DataserviceErrorMaps an error from the persist client to the data service error body.
Parameters
- err error - The error the persist client returned
- entity string (default "") - The name of the entity
- key KeyValue[] (default []) - The values of the record's key fields, in key order
- operation string (default "") - The name of the operation, which is logged with the error
Return Type
- DataserviceError - The error body for the error's category
toForbiddenError
function toForbiddenError(string entity, string relation, string target) returns DataserviceErrorBuilds the error body for a relation the caller cannot read, because it holds no read scope of the related
entity.
Parameters
- entity string - The name of the entity
- relation string - The relation field
- target string - The name of the related entity
Return Type
- DataserviceError - The
FORBIDDENerror body
toIncludeQuery
function toIncludeQuery(Entity entity, string relation, map<anydata>[] sources, PageConfig config) returns QueryBuilds the query that reads the related records of a relation named in fields: for a to-one relation, those of
every record of a page; for a to-many relation, those of one record, one more than config.size in key order.
Parameters
- entity Entity - The entity of the records
- relation string - The relation field
- sources map<anydata>[] - The records, holding at least the fields that link the relation
- config PageConfig - The page sizes of the data service
Return Type
- Query - The query
toInternalErrorBody
function toInternalErrorBody(error err, string entity, string operation) returns DataserviceErrorLogs an error that the caller is not told about, and builds the INTERNAL error body for it.
Parameters
- err error - The error
- entity string (default "") - The name of the entity
- operation string (default "") - The name of the operation
Return Type
- DataserviceError - The
INTERNALerror body
toKeysQuery
Builds the query that reads records by their keys, in key order.
Parameters
- entity Entity - The entity to read
- keys KeyValue[][] - The key values of each record, in key order
Return Type
- Query - The query
toNoScopeError
function toNoScopeError() returns DataserviceErrorBuilds the error body for a caller that holds no scope of the operation's action.
Return Type
- DataserviceError - The
FORBIDDENerror body
toPageConfig
function toPageConfig(int size, int maxSize) returns PageConfig|errorChecks the page sizes that a data service is configured with.
Parameters
- size int - The value of
dataserviceConfig.pageSize
- maxSize int - The value of
dataserviceConfig.maxPageSize
Return Type
- PageConfig|error - The page sizes, or an error naming the value that is out of range
toQuery
function toQuery(Entity entity, PageConfig config, map<map<anydata>>? filter, string[]? sort, int? size, int? offset) returns Query|DataserviceError|ConversionErrorValidates the query options of a read and builds its query.
Parameters
- entity Entity - The entity to read
- config PageConfig - The page sizes of the data service
- sort string[]? (default ()) - The field names to sort by, each descending when it starts with
-
- size int? (default ()) - The page size
- offset int? (default ()) - The number of records to skip
Return Type
- Query|DataserviceError|ConversionError - The query, an
INVALID_INPUTerror body, or aConversionErrorfor a value that does not parse
toRelatedNotFoundError
function toRelatedNotFoundError(Entity entity, string relation, KeyValue[] key) returns DataserviceErrorBuilds the error body for a to-one relation with no related record.
Parameters
- entity Entity - The entity of the record
- relation string - The relation field
- key KeyValue[] - The values of the record's key fields, in key order
Return Type
- DataserviceError - The
NOT_FOUNDerror body
toRelatedQuery
function toRelatedQuery(Entity entity, string relation, map<anydata> row, PageConfig config, map<map<anydata>>? filter, string[]? sort, int? size, int? offset) returns Query|DataserviceError|ConversionErrorValidates the query options of get related and builds its query, which reads the records related to one record.
Parameters
- entity Entity - The entity of the record
- relation string - The relation field
- row map<anydata> - The record, holding at least the fields that link the relation
- config PageConfig - The page sizes of the data service
- sort string[]? (default ()) - The field names of the related entity to sort by, each descending when it starts with
-
- size int? (default ()) - The page size
- offset int? (default ()) - The number of records to skip
Return Type
- Query|DataserviceError|ConversionError - The query, an
INVALID_INPUTerror body, or aConversionErrorfor a value that does not parse
toUnauthenticatedError
function toUnauthenticatedError() returns DataserviceErrorBuilds the error body for a request without a credential, or with one that no authentication provider accepts.
Return Type
- DataserviceError - The
UNAUTHENTICATEDerror body
trimToPage
Removes the extra row that a query reads beyond its page.
Parameters
- rows anydata[] - The rows the query returned, which are cut to the page in place
- query Query - The query
Return Type
- boolean - Whether records exist after the page
utcFromString
function utcFromString(string value) returns Utc|ConversionErrorConverts an ISO 8601 date-time with an offset, such as 2024-01-02T10:15:30Z, to a time:Utc value.
Parameters
- value string - The date-time; an offset other than
Zis converted to UTC
Return Type
- Utc|ConversionError - The value, or a
ConversionErrorif the string is not a valid date-time with an offset
utcToString
Converts a time:Utc value to an ISO 8601 date-time in UTC, such as 2024-01-02T10:15:30Z.
Parameters
- value Utc - The value
Return Type
- string - The date-time
Constants
dataservice: INTERNAL_MESSAGE
The message of the INTERNAL error body.
Enums
dataservice: Datastore
The SQL datastore of an entity.
Members
dataservice: ErrorCode
The category of a data service error.
Members
dataservice: FieldType
The type of an entity field.
Members
dataservice: Operation
An action that a data service allows on an entity.
Members
Annotations
dataservice: Expose
Exposes a persist entity in the generated data service.
dataservice: Immutable
Marks a field that is set on create and never changed.
dataservice: Internal
Marks a field that is never returned or accepted. On a relation field, withholds that direction of the relation.
dataservice: ReadOnly
Marks a field that is returned but never written. A value sent on create or update is ignored.
Records
dataservice: Config
The runtime settings that every protocol's configuration includes.
Fields
- port int(default 9090) - The port of the listener
- pageSize int(default 100) - The number of records in a page when the caller gives no size
- maxPageSize int(default 1000) - The largest page, and the most records one create can hold
dataservice: ConversionErrorDetail
The detail of a ConversionError.
Fields
- format string - The format the value is not in, such as
an ISO 8601 date
- 'field? string -
dataservice: DataserviceError
The body of an error that a data service returns.
Fields
- code ErrorCode - The error category
- message string - A description of the error
dataservice: Entity
The description of an entity that queries are built from.
Fields
- name string - The entity name
- collection string - The collection name of the entity in the service
- 'resource string -
- datastore Datastore - The datastore of the entity
- fields Field[] - The fields that callers can see, in model order
- relations Relation[](default []) - The relations that callers can read
dataservice: ExposeConfig
Configures the Expose annotation.
Fields
- operations [Operation, Operation...](default [READ, CREATE, UPDATE, DELETE]) - The actions the entity allows; every action by default
- scopes? Scopes - The scopes each action requires when the data service has auth
dataservice: Field
A field of an entity.
Fields
- name string - The field name in the model
- column string - The column name in the database
- 'type FieldType -
- nullable boolean(default false) - Whether the field can be nil
- key boolean(default false) - Whether the field is a key field
- generated boolean(default false) - Whether the database generates the field's value
dataservice: FieldRuleConfig
Configures a field rule.
Fields
- value? anydata - The value the service sets on create, which must be a constant of the field's type
dataservice: PageConfig
The page sizes of a data service.
Fields
- size int - The number of records in a page when the caller gives no size
- maxSize int - The largest page, and the most records one create can hold
dataservice: Query
The clauses of a query for the persist SQL client.
Fields
- whereClause ParameterizedQuery - The
WHEREclause
- orderByClause ParameterizedQuery - The
ORDER BYclause
- limitClause ParameterizedQuery - The
LIMITclause, one row more than the page to tell whether more records exist
- offsetClause ParameterizedQuery - The number of rows to skip
- size int - The page size
dataservice: Relation
A relation of an entity that callers can read.
Fields
- 'field string -
- many boolean - Whether the relation is to-many
- fields string[] - The fields of this entity that link it, in key order
- targetFields string[] - The fields of the related entity that they match, in the same order
- target Entity - The related entity, with its own fields and no relations
dataservice: Scopes
The scopes that each action of an entity requires when the data service has auth. A caller needs any one scope of the list; an empty list requires only an authenticated caller.
Fields
- read? string[] - The scopes of
read;<resource>:readwhen not given
- create? string[] - The scopes of
create;<resource>:createwhen not given
- update? string[] - The scopes of
update;<resource>:updatewhen not given
- delete? string[] - The scopes of
delete;<resource>:deletewhen not given
Errors
dataservice: ConversionError
Represents a value that is not in the JSON format of its type.
Union types
Import
import ballerina/dataservice;Other versions
0.1.0
Metadata
Released date: about 19 hours ago
Version: 0.1.0
License: Apache-2.0
Security
No known vulnerabilities in libraries
Checked on 2026-11-20 via OSV.dev
Compatibility
Platform: java25
Ballerina version: 2201.14.0
GraalVM compatible: Yes
Pull count
Total: 13
Current verison: 13
Weekly downloads
Keywords
dataservice
persist
data
Type/Library
Area/Database
Name/Data Service
Contributors
Dependents