DataClass
A DataClass provides an object interface to a database table. All dataclasses in a 4D application are available as a property of the ds
datastore.
Summary
.attributeName : object objects that are available directly as properties |
.all ( { settings : Object } ) : 4D.EntitySelection queries the datastore to find all the entities related to the dataclass and returns them as an entity selection |
.clearRemoteCache() empties the ORDA cache of a dataclass |
.fromCollection( objectCol : Collection { ; settings : Object } ) : 4D.EntitySelection updates or creates entities in the dataclass according to the objectCol collection of objects, and returns the corresponding entity selection |
.get( primaryKey : Integer { ; settings : Object } ) : 4D.Entity .get( primaryKey : Text { ; settings : Object } ) : 4D.Entity queries the dataclass to retrieve the entity matching the primaryKey parameter |
.getCount() : Integer returns the number of entities in a dataclass |
.getDataStore() : cs.DataStore returns the datastore for the specified dataclass |
.getInfo() : Object returns an object providing information about the dataclass |
.getRemoteCache() : Object returns an object that holds the contents of the ORDA cache for a dataclass. |
.new() : 4D.Entity creates in memory and returns a new blank entity related to the Dataclass |
.newSelection( { keepOrder : Integer } ) : 4D.EntitySelection creates a new, blank, non-shareable entity selection, related to the dataclass, in memory |
.query( queryString : Text { ; ...value : any } { ; querySettings : Object } ) : 4D.EntitySelection .query( formula : Object { ; querySettings : Object } ) : 4D.EntitySelection searches for entities that meet the search criteria specified in queryString or formula and (optionally) value(s) |
.setRemoteCacheSettings(settings : Object) sets the timeout and maximum size of the ORDA cache for a dataclass. |
.attributeName
History
Release | Changes |
---|---|
19 R3 | Added .exposed attribute |
17 | Added |
.attributeName : object
Description
The attributes of dataclasses are objects that are available directly as properties of these classes.
The returned objects have properties that you can read to get information about your dataclass attributes.
Dataclass attribute objects can be modified, but the underlying database structure will not be altered.
Returned object
Returned attribute objects contain the following properties:
Property | Type | Description |
---|---|---|
autoFilled | Boolean | True if the attribute value is automatically filled by 4D. Corresponds to the following 4D field properties: "Autoincrement" for numeric type fields and "Auto UUID" for UUID (alpha) fields. Not returned if .kind = "relatedEntity" or "relatedEntities". |
exposed | Boolean | True if the attribute is exposed in REST |
fieldNumber | integer | Internal 4D field number of the attribute. Not returned if .kind = "relatedEntity" or "relatedEntities". |
fieldType | Integer | 4D database field type of the attribute. Depends on the attribute kind . Possible values: .kind = "storage": corresponding 4D field type, see Value type .kind = "relatedEntity": 38 (is object ).kind = "relatedEntities": 42 (is collection ).kind = "calculated" or "alias" = same as above, depending on the resulting value (field type, relatedEntity or relatedEntities) |
indexed | Boolean | True if there is a B-tree or a Cluster B-tree index on the attribute. Not returned if .kind = "relatedEntity" or "relatedEntities". |
inverseName | Text | Name of the attribute which is at the other side of the relation. Returned only when .kind = "relatedEntity" or "relatedEntities". |
keywordIndexed | Boolean | True if there is a keyword index on the attribute. Not returned if .kind = "relatedEntity" or "relatedEntities". |
kind | Text | Category of the attribute. Possible values:get function |
mandatory | Boolean | True if null value input is rejected for the attribute. Not returned if .kind = "relatedEntity" or "relatedEntities". Note: This property corresponds to the "Reject NULL value input" field property at the 4D database level. It is unrelated to the existing "Mandatory" property which is a data entry control option for a table. |
name | Text | Name of the attribute as string |
path | Text | Path of an alias attribute based upon a relation |
readOnly | Boolean | True if the attribute is read-only. For example, computed attributes without set function are read-only. |
relatedDataClass | Text | Name of the dataclass related to the attribute. Returned only when .kind = "relatedEntity" or "relatedEntities". |
type | Text | Conceptual value type of the attribute, useful for generic programming. Depends on the attribute kind . Possible values: .kind = "storage": "blob", "bool", "date", "image", "number", "object", or "string". "number" is returned for any numeric types including duration; "string" is returned for uuid, alpha and text attribute types; "blob" attributes are blob objects..kind = "relatedEntity": related dataClass name.kind = "relatedEntities": related dataClass name + "Selection" suffix.kind = "calculated" or "alias": same as above, depending on the result |
unique | Boolean | True if the attribute value must be unique. Not returned if .kind = "relatedEntity" or "relatedEntities". |
For generic programming, use Bool(attributeName.property)
, Num(attributeName.property)
or String(attributeName.property)
(depending on the property type) to get a valid value even if the property is not returned.
Example 1
$salary:=ds.Employee.salary //returns the salary attribute in the Employee dataclass
$compCity:=ds.Company["city"] //returns the city attribute in the Company dataclass
Example 2
Considering the following database structure:
var $firstnameAtt;$employerAtt;$employeesAtt : Object
$firstnameAtt:=ds.Employee.firstname
//{name:firstname,kind:storage,fieldType:0,type:string,fieldNumber:2,indexed:true,
//keyWordIndexed:false,autoFilled:false,mandatory:false,unique:false}
$employerAtt:=ds.Employee.employer
//{name:employer,kind:relatedEntity,relatedDataClass:Company,
//fieldType:38,type:Company,inverseName:employees}
//38=Is object
$employeesAtt:=ds.Company.employees
//{name:employees,kind:relatedEntities,relatedDataClass:Employee,
//fieldType:42,type:EmployeeSelection,inverseName:employer}
//42=Is collection
Example 3
Considering the following table properties:
var $sequenceNumberAtt : Object
$sequenceNumberAtt=ds.Employee.sequenceNumber
//{name:sequenceNumber,kind:storage,fieldType:0,type:string,fieldNumber:13,
//indexed:true,keyWordIndexed:false,autoFilled:true,mandatory:false,unique:true}
.all()
History
Release | Changes |
---|---|
17 R5 | Support of the settings parameter |
17 | Added |
.all ( { settings : Object } ) : 4D.EntitySelection
Parameter | Type | Description | |
---|---|---|---|
settings | Object | -> | Build option: context |
Result | 4D.EntitySelection | <- | References on all entities related to the Dataclass |
Description
The .all()
function queries the datastore to find all the entities related to the dataclass and returns them as an entity selection.
The entities are returned in the default order, which is initially the order in which they were created. Note however that, if entities have been deleted and new ones added, the default order does not reflect the creation order anymore.
If no corresponding entity is found, an empty entity selection is returned.
Lazy loading is applied.
settings
In the optional settings parameter, you can pass an object containing additional options. The following property is supported:
Property | Type | Description |
---|---|---|
context | Text | Label for the optimization context applied to the entity selection. This context will be used by the code that handles the entity selection so that it can benefit from the optimization. This feature is designed for ORDA client/server processing. |
To know the total number of entities in a dataclass, it is recommended to use the
getCount()
function which is more optimized than theds.myClass.all().length
expression.
Example
var $allEmp : cs.EmployeeSelection
$allEmp:=ds.Employee.all()
.clearRemoteCache()
History
Release | Changes |
---|---|
19 R5 | Added |
.clearRemoteCache()
Parameter | Type | Description | |
---|---|---|---|
Does not require any parameters |
Description
The .clearRemoteCache()
function empties the ORDA cache of a dataclass.
This function does not reset the
timeout
andmaxEntries
values.
Example
var $ds : 4D.DataStoreImplementation
var $persons : cs.PersonsSelection
var $p : cs.PersonsEntity
var $cache : Object
var $info : Collection
var $text : Text
$ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")
$persons:=$ds.Persons.all()
$text:=""
For each ($p; $persons)
$text:=$p.firstname+" lives in "+$p.address.city+" / "
End for each
$cache:=$ds.Persons.getRemoteCache()
$ds.Persons.clearRemoteCache()
// Cache of the Persons dataclass = {timeout:30;maxEntries:30000;stamp:255;entries:[]}
####See also
.fromCollection()
History
Release | Changes |
---|---|
17 R5 | Support of the settings parameter |
17 | Added |
.fromCollection( objectCol : Collection { ; settings : Object } ) : 4D.EntitySelection
Parameter | Type | Description | |
---|---|---|---|
objectCol | Collection | -> | Collection of objects to be mapped with entities |
settings | Object | -> | Build option: context |
Result | 4D.EntitySelection | <- | Entity selection filled from the collection |
Description
The .fromCollection()
function updates or creates entities in the dataclass according to the objectCol collection of objects, and returns the corresponding entity selection.
In the objectCol parameter, pass a collection of objects to create new or update existing entities of the dataclass. The property names must be the same as attribute names in the dataclass. If a property name does not exist in the dataclass, it is ignored. If an attribute value is not defined in the collection, its value is null.
The mapping between the objects of the collection and the entities is done on the attribute names and matching types. If an object's property has the same name as an entity's attribute but their types do not match, the entity's attribute is not filled.
Create or update mode
For each object of objectCol:
- If the object contains a boolean property "__NEW" set to false (or does not contain a boolean "__NEW" property), the entity is updated or created with the corresponding values of the properties from the object. No check is performed in regards to the primary key:
- If the primary key is given and exists, the entity is updated. In this case, the primary key can be given as is or with a "__KEY" property (filled with the primary key value).
- If the primary key is given (as is) and does not exist, the entity is created
- If the primary key is not given, the entity is created and the primary key value is assigned with respect to standard database rules.
- If the object contains a boolean property "__NEW" set to true, the entity is created with the corresponding values of the attributes from the object. A check is performed in regards to the primary key:
- If the primary key is given (as is) and exists, an error is sent
- If the primary key is given (as is) and does not exist, the entity is created
- If the primary is not given, the entity is created and the primary key value is assigned with respect to standard database rules.
The "__KEY" property containing a value is taken into account only when the "__NEW" property is set to false (or is omitted) and a corresponding entity exists. In all other cases, the "__KEY" property value is ignored, primary key value must be passed "as is".
Related entities
The objects of objectCol may contain one or more nested object(s) featuring one or more related entities, which can be useful to create or update links between entities.
The nested objects featuring related entities must contain a "__KEY" property (filled with the primary key value of the related entity) or the primary key attribute of the related entity itself. The use of a __KEY property allows independence from the primary key attribute name.
The content of the related entities cannot be created / updated through this mechanism.
Stamp
If a __STAMP attribute is given, a check is performed with the stamp in the datastore and an error can be returned ("Given stamp does not match current one for record# XX of table XXXX"). For more information, see Entity locking.
settings
In the optional settings parameter, you can pass an object containing additional options. The following property is supported:
Property | Type | Description |
---|---|---|
context | Text | Label for the optimization context applied to the entity selection. This context will be used by the code that handles the entity selection so that it can benefit from the optimization. This feature is designed for ORDA client/server processing. |
Example 1
We want to update an existing entity. The __NEW property is not given, the employee primary key is given and exists:
var $empsCollection : Collection
var $emp : Object
var $employees : cs.EmployeeSelection
$empsCollection:=New collection
$emp:=New object
$emp.ID:=668 //Existing PK in Employee table
$emp.firstName:="Arthur"
$emp.lastName:="Martin"
$emp.employer:=New object("ID";121) //Existing PK in the related dataClass Company
// For this employee, we can change the Company by using another existing PK in the related dataClass Company
$empsCollection.push($emp)
$employees:=ds.Employee.fromCollection($empsCollection)
Example 2
We want to update an existing entity. The __NEW property is not given, the employee primary key is with the __KEY attribute and exists:
var $empsCollection : Collection
var $emp : Object
var $employees : cs.EmployeeSelection
$empsCollection:=New collection
$emp:=New object
$emp.__KEY:=1720 //Existing PK in Employee table
$emp.firstName:="John"
$emp.lastName:="Boorman"
$emp.employer:=New object("ID";121) //Existing PK in the related dataClass Company
// For this employee, we can change the Company by using another existing PK in the related dataClass Company
$empsCollection.push($emp)
$employees:=ds.Employee.fromCollection($empsCollection)
Example 3
We want to simply create a new entity from a collection:
var $empsCollection : Collection
var $emp : Object
var $employees : cs.EmployeeSelection
$empsCollection:=New collection
$emp:=New object
$emp.firstName:="Victor"
$emp.lastName:="Hugo"
$empsCollection.push($emp)
$employees:=ds.Employee.fromCollection($empsCollection)
Example 4
We want to create an entity. The __NEW property is True, the employee primary key is not given:
var $empsCollection : Collection
var $emp : Object
var $employees : cs.EmployeeSelection
$empsCollection:=New collection
$emp:=New object
$emp.firstName:="Mary"
$emp.lastName:="Smith"
$emp.employer:=New object("__KEY";121) //Existing PK in the related dataClass Company
$emp.__NEW:=True
$empsCollection.push($emp)
$employees:=ds.Employee.fromCollection($empsCollection)
Example 5
We want to create an entity. The __NEW property is omitted, the employee primary key is given and does not exist:
var $empsCollection : Collection
var $emp : Object
var $employees : cs.EmployeeSelection
$empsCollection:=New collection
$emp:=New object
$emp.ID:=10000 //Unexisting primary key
$emp.firstName:="Françoise"
$emp.lastName:="Sagan"
$empsCollection.push($emp)
$employees:=ds.Employee.fromCollection($empsCollection)
Example 6
In this example, the first entity will be created and saved but the second will fail since they both use the same primary key:
var $empsCollection : Collection
var $emp; $emp2 : Object
var $employees : cs.EmployeeSelection
$empsCollection:=New collection
$emp:=New object
$emp.ID:=10001 // Unexisting primary key
$emp.firstName:="Simone"
$emp.lastName:="Martin"
$emp.__NEW:=True
$empsCollection.push($emp)
$emp2:=New object
$emp2.ID:=10001 // Same primary key, already existing
$emp2.firstName:="Marc"
$emp2.lastName:="Smith"
$emp2.__NEW:=True
$empsCollection.push($emp2)
$employees:=ds.Employee.fromCollection($empsCollection)
//first entity is created
//duplicated key error for the second entity
See also
.get()
History
Release | Changes |
---|---|
17 | Added |
.get( primaryKey : Integer { ; settings : Object } ) : 4D.Entity
.get( primaryKey : Text { ; settings : Object } ) : 4D.Entity
Parameter | Type | Description | |
---|---|---|---|
primaryKey | Integer OR Text | -> | Primary key value of the entity to retrieve |
settings | Object | -> | Build option: context |
Result | 4D.Entity | <- | Entity matching the designated primary key |
Description
The .get()
function queries the dataclass to retrieve the entity matching the primaryKey parameter.
In primaryKey, pass the primary key value of the entity to retrieve. The value type must match the primary key type set in the datastore (Integer or Text). You can also make sure that the primary key value is always returned as Text by using the .getKey()
function with the dk key as string
parameter.
If no entity is found with primaryKey, a Null entity is returned.
Lazy loading is applied, which means that related data is loaded from disk only when it is required.
settings
In the optional settings parameter, you can pass an object containing additional options. The following property is supported:
Property | Type | Description |
---|---|---|
context | Text | Label for the automatic optimization context applied to the entity. This context will be used by the subsequent code that loads the entity so that it can benefit from the optimization. This feature is designed for ORDA client/server processing. |
When you call the .get()
function without settings parameter, a request for attribute values is directly sent to the server (the ORDA cache is not used). On the other hand, when you call the .get()
function with a context
passed in the settings parameter, attribute values are retrieved from the ORDA cache corresponding to the context. It may be advisable in this case to call reload()
to make sure the most recent data is retrieved from the server.
Example 1
var $entity : cs.EmployeeEntity
var $entity2 : cs.InvoiceEntity
$entity:=ds.Employee.get(167) // return the entity whose primary key value is 167
$entity2:=ds.Invoice.get("DGGX20030") // return the entity whose primary key value is "DGGX20030"
Example 2
This example illustrates the use of the context property:
var $e1; $e2; $e3; $e4 : cs.EmployeeEntity
var $settings; $settings2 : Object
$settings:=New object("context";"detail")
$settings2:=New object("context";"summary")
$e1:=ds.Employee.get(1;$settings)
completeAllData($e1) // In completeAllData method, an optimization is triggered and associated to context "detail"
$e2:=ds.Employee.get(2;$settings)
completeAllData($e2) // In completeAllData method, the optimization associated to context "detail" is applied
$e3:=ds.Employee.get(3;$settings2)
completeSummary($e3) //In completeSummary method, an optimization is triggered and associated to context "summary"
$e4:=ds.Employee.get(4;$settings2)
completeSummary($e4) //In completeSummary method, the optimization associated to context "summary" is applied
.getCount()
History
Release | Changes |
---|---|
19 R5 | Added |
.getCount() : Integer
Parameter | Type | Description | |
---|---|---|---|
result | Integer | <- | Number of entities in the dataclass |
Description
The .getCount()
function returns the number of entities in a dataclass.
If this function is used within a transaction, entities created during the transaction will be taken into account.
Example
var $ds : 4D.DataStoreImplementation
var $number : Integer
$ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")
$number:=$ds.Persons.getCount()
.getDataStore()
History
Release | Changes |
---|---|
17 R5 | Added |
.getDataStore() : cs.DataStore
Parameter | Type | Description | |
---|---|---|---|
Result | cs.DataStore | <- | Datastore of the dataclass |
Description
The .getDataStore()
function returns the datastore for the specified dataclass.
The datastore can be:
- the main datastore, as returned by the
ds
command. - a remote datastore, opened using the
Open datastore
command.
Example
The SearchDuplicate project method searches for duplicated values in any dataclass.
var $pet : cs.CatsEntity
$pet:=ds.Cats.all().first() //get an entity
SearchDuplicate($pet;"Dogs")
// SearchDuplicate method
// SearchDuplicate(entity_to_search;dataclass_name)
#DECLARE ($pet : Object ; $dataClassName : Text)
var $dataStore; $duplicates : Object
$dataStore:=$pet.getDataClass().getDataStore()
$duplicates:=$dataStore[$dataClassName].query("name=:1";$pet.name)
.getInfo()
History
Release | Changes |
---|---|
19 R3 | Added exposed property |
17 R5 | Added |
.getInfo() : Object
Parameter | Type | Description | |
---|---|---|---|
Result | Object | <- | Information on the dataclass |
Description
The .getInfo()
function returns an object providing information about the dataclass. This function is useful for setting up generic code.
Returned object
Property | Type | Description |
---|---|---|
exposed | Boolean | True if the dataclass is exposed in REST |
name | Text | Name of the dataclass |
primaryKey | Text | Name of the primary key of the dataclass |
tableNumber | Integer | Internal 4D table number |
Example 1
#DECLARE ($entity : Object)
var $status : Object
computeEmployeeNumber($entity) //do some actions on entity
$status:=$entity.save()
if($status.success)
ALERT("Record updated in table "+$entity.getDataClass().getInfo().name)
End if
Example 2
var $settings : Object
var $es : cs.ClientsSelection
$settings:=New object
$settings.parameters:=New object("receivedIds";getIds())
$settings.attributes:=New object("pk";ds.Clients.getInfo().primaryKey)
$es:=ds.Clients.query(":pk in :receivedIds";$settings)
Example 3
var $pk : Text
var $dataClassAttribute : Object
$pk:=ds.Employee.getInfo().primaryKey
$dataClassAttribute:=ds.Employee[$pk] // If needed the attribute matching the primary key is accessible
.getRemoteCache()
History
Release | Changes |
---|---|
19 R5 | Added |
.getRemoteCache() : Object
Parameter | Type | Description | |
---|---|---|---|
result | Object | <- | Object describing the contents of the ORDA cache for the dataclass. |
Advanced mode: This function is intended for developers who need to customize ORDA default features for specific configurations. In most cases, you will not need to use it.
Description
The .getRemoteCache()
function returns an object that holds the contents of the ORDA cache for a dataclass..
Calling this function from a 4D single-user application returns Null
.
The returned object has the following properties:
Property | Type | Description |
---|---|---|
maxEntries | Integer | Maximum number of entries collection. |
stamp | Integer | Stamp of the cache. |
timeout | Integer | Time remaining before the new entries in the cache are marked as expired. |
entries | Collection | Contains an entry object for each entity in the cache. |
Each entry object in the entries
collection has the following properties:
Property | Type | Description |
---|---|---|
data | Object | Object holding data on the entry. |
expired | Boolean | True if the entry has expired. |
key | Text | Primary key of the entity. |
The data
object in each entry contains the following properties:
Property | Type | Description |
---|---|---|
__KEY | String | Primary key of the entity |
__STAMP | Longint | Timestamp of the entity in the database |
__TIMESTAMP | String | Stamp of the entity in the database (format is YYYY-MM-DDTHH:MM:SS:ms:Z) |
dataClassAttributeName | Variant | If there is data in the cache for a dataclass attribute, it is returned in a property with the same type as in the database. |
Data concerning related entities is stored in the cache of the data object.
Example
In the following example, $ds.Persons.all()
loads the first entity with all its attributes. Then, the request optimization is triggered, so only firstname
and address.city
are loaded.
Note that address.city
is loaded in the cache of the Persons
dataclass.
Only the first entity of the Address
dataclass is stored in the cache. It is loaded during the first iteration of the loop.
var $ds : 4D.DataStoreImplementation
var $persons : cs.PersonsSelection
var $p : cs.PersonsEntity
var $cachePersons; $cacheAddress : Object
var $text : Text
$ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")
$persons:=$ds.Persons.all()
$text:=""
For each ($p; $persons)
$text:=$p.firstname+" lives in "+$p.address.city+" / "
End for each
$cachePersons:=$ds.Persons.getRemoteCache()
$cacheAddress:=$ds.Adress.getRemoteCache()
See also
.setRemoteCacheSettings()
.clearRemoteCache()
.new()
History
Release | Changes |
---|---|
17 | Added |
.new() : 4D.Entity
Parameter | Type | Description | |
---|---|---|---|
Result | 4D.Entity | <- | New entity matching the Dataclass |
Description
The .new()
function creates in memory and returns a new blank entity related to the Dataclass.
The entity object is created in memory and is not saved in the database until the .save( )
function is called. If the entity is deleted before being saved, it cannot be recovered.
4D Server: In client-server, if the primary key of the corresponding table is auto-incremented, it will be calculated when the entity is saved on the server.
All attributes of the entity are initialized with the null value.
Attributes can be initialized with default values if the Map NULL values to blank values option is selected at the 4D database structure level.
Example
This example creates a new entity in the "Log" Dataclass and records information in the "info" attribute:
var $entity : cs.LogEntity
$entity:=ds.Log.new() //create a reference
$entity.info:="New entry" //store some information
$entity.save() //save the entity
.newSelection()
History
Release | Changes |
---|---|
17 | Added |
.newSelection( { keepOrder : Integer } ) : 4D.EntitySelection
Parameter | Type | Description | |
---|---|---|---|
keepOrder | Integer | -> | dk keep ordered : creates an ordered entity selection,dk non ordered : creates an unordered entity selection (default if omitted) |
Result | 4D.EntitySelection | <- | New blank entity selection related to the dataclass |
Description
The .newSelection()
function creates a new, blank, non-shareable entity selection, related to the dataclass, in memory.
For information on non-shareable entity selections, please refer to this section.
If you want to create an ordered entity selection, pass the dk keep ordered
selector in the keepOrder parameter. By default if you omit this parameter, or if you pass the dk non ordered
selector, the method creates an unordered entity selection. Unordered entity selections are faster but you cannot rely on entity positions. For more information, please see Ordered vs Unordered entity selections.
When created, the entity selection does not contain any entities (mySelection.length
returns 0). This method lets you build entity selections gradually by making subsequent calls to the add()
function.
Example
var $USelection; $OSelection : cs.EmployeeSelection
$USelection:=ds.Employee.newSelection() //create an unordered empty entity selection
$OSelection:=ds.Employee.newSelection(dk keep ordered) //create an ordered empty entity selection
.query()
History
Release | Changes |
---|---|
17 R6 | Support of Formula parameters |
17 R5 | Support of placeholders for values |
17 | Added |
.query( queryString : Text { ; ...value : any } { ; querySettings : Object } ) : 4D.EntitySelection
.query( formula : Object { ; querySettings : Object } ) : 4D.EntitySelection
Parameter | Type | Description | |
---|---|---|---|
queryString | Text | -> | Search criteria as string |
formula | Object | -> | Search criteria as formula object |
value | any | -> | Value(s) to use for indexed placeholder(s) |
querySettings | Object | -> | Query options: parameters, attributes, args, allowFormulas, context, queryPath, queryPlan |
Result | 4D.EntitySelection | <- | New entity selection made up of entities from dataclass meeting the search criteria specified in queryString or formula |
Description
The .query()
function searches for entities that meet the search criteria specified in queryString or formula and (optionally) value(s), for all the entities in the dataclass, and returns a new object of type EntitySelection
containing all the entities that are found. Lazy loading is applied.
If no matching entities are found, an empty EntitySelection
is returned.
queryString parameter
The queryString parameter uses the following syntax:
attributePath|formula comparator value
{logicalOperator attributePath|formula comparator value}
{order by attributePath {desc | asc}}
where:
- attributePath: path of attribute on which you want to execute the query. This parameter can be a simple name (for example "country") or any valid attribute path (for example "country.name".) In case of an attribute path whose type is
Collection
,[]
notation is used to handle all the occurences (for examplechildren[].age
).
You cannot use directly attributes whose name contains special characters such as ".", "[ ]", or "=", ">", "#"..., because they will be incorrectly evaluated in the query string. If you need to query on such attributes, you must consider using placeholders, which allow an extended range of characters in attribute paths (see Using placeholders below).
-
formula: a valid formula passed as
Text
orObject
. The formula will be evaluated for each processed entity and must return a boolean value. Within the formula, the entity is available through theThis
object.- Text: the formula string must be preceeded by the
eval()
statement, so that the query parser evaluates the expression correctly. For example: "eval(length(This.lastname) >=30)" - Object: the formula object is passed as a placeholder (see below). The formula must have been created using the
Formula
orFormula from string
command.
- Text: the formula string must be preceeded by the
- Keep in mind that 4D formulas only support
&
and|
symbols as logical operators.- If the formula is not the only search criteria, the query engine optimizer could prior process other criteria (e.g. indexed attributes) and thus, the formula could be evaluated for only a subset of entities.
Formulas in queries can receive parameters through $1. This point is detailed in the formula parameter paragraph below.
- You can also pass directy a
formula
parameter object instead of thequeryString
parameter (recommended when formulas are more complex). See formula parameter paragraph below.- For security reasons, formula calls within
query()
functions can be disallowed. SeequerySettings
parameter description.
- comparator: symbol that compares attributePath and value. The following symbols are supported:
Comparison | Symbol(s) | Comment |
---|---|---|
Equal to | =, == | Gets matching data, supports the wildcard (@), neither case-sensitive nor diacritic. |
===, IS | Gets matching data, considers the @ as a standard character, neither case-sensitive nor diacritic | |
Not equal to | #, != | Supports the wildcard (@). Equivalent to "Not condition applied on a statement" (see below). |
!==, IS NOT | Considers the @ as a standard character | |
Not condition applied on a statement | NOT | Parenthesis are mandatory when NOT is used before a statement containing several operators. Equivalent to "Not equal to" (see below). |
Less than | < | |
Greater than | > | |
Less than or equal to | <= | |
Greater than or equal to | >= | |
Included in | IN | Gets data equal to at least one of the values in a collection or in a set of values, supports the wildcard (@) |
Contains keyword | % | Keywords can be used in attributes of string or picture type |
- value: the value to compare to the current value of the property of each entity in the entity selection. It can be a placeholder (see Using placeholders below) or any expression matching the data type property.
When using a constant value, the following rules must be respected:
- text type constant can be passed with or without simple quotes (see Using quotes below). To query a string within a string (a "contains" query), use the wildcard symbol (@) in value to isolate the string to be searched for as shown in this example: "@Smith@". The following keywords are forbidden for text constants: true, false.
- boolean type constants: true or false (case sensitive).
- numeric type constants: decimals are separated by a '.' (period).
- date type constants: "YYYY-MM-DD" format
- null constant: using the "null" keyword will find null and undefined properties.
- in case of a query with an IN comparator, value must be a collection, or values matching the type of the attribute path between [ ] separated by commas (for strings,
"
characters must be escaped with\
).
- logicalOperator: used to join multiple conditions in the query (optional). You can use one of the following logical operators (either the name or the symbol can be used):
Conjunction | Symbol(s) |
---|---|
AND | &, &&, and |
OR | |,||, or |
- order by attributePath: you can include an order by attributePath statement in the query so that the resulting data will be sorted according to that statement. You can use multiple order by statements, separated by commas (e.g., order by attributePath1 desc, attributePath2 asc). By default, the order is ascending. Pass 'desc' to define a descending order and 'asc' to define an ascending order.
If you use this statement, the returned entity selection is ordered (for more information, please refer to Ordered vs Unordered entity selections).
Using quotes
When you use quotes within queries, you must use single quotes ' ' inside the query and double quotes " " to enclose the whole query, otherwise an error is returned. For example:
"employee.name = 'smith' AND employee.firstname = 'john'"
Single quotes (') are not supported in searched values since they would break the query string. For example "comp.name = 'John's pizza' " will generate an error. If you need to search on values with single quotes, you may consider using placeholders (see below).