DataStore
A Datastore is the interface object provided by ORDA to reference and access a database. Datastore
objects are returned by the following commands:
- ds: a shortcut to the main datastore
- Open datastore: to open any remote datastore
Resumen
.cancelTransaction() cancels the transaction |
.clearAllRemoteContexts() clears all the attributes for all the active contexts in the datastore |
.dataclassName : 4D.DataClass contiene una descripción de la clase de datos |
.encryptionStatus(): Object returns an object providing the encryption status for the current data file |
.flushAndLock() flushes the cache of the local datastore and prevents other processes from performing write operations on the database |
.getAllRemoteContexts() : Collection returns a collection of objects containing information on all the active optimization contexts in the datastore |
.getGlobalStamp() : Real returns the current value of the global modification stamp of the datastore |
.getInfo(): Object returns an object providing information about the datastore |
.getRemoteContextInfo(contextName : Text) : Object returns an object that holds information on the contextName optimization context in the datastore. |
.getRequestLog() : Collection returns the ORDA requests logged in memory on the client side |
.locked() : Boolean returns True if the local datastore is currently locked |
.makeSelectionsAlterable() sets all entity selections as alterable by default in the current application datastores |
.provideDataKey( curPassPhrase : Text ) : Object .provideDataKey( curDataKey : Object ) : Object allows providing a data encryption key for the current data file of the datastore and detects if the key matches the encrypted data |
| .setAdminProtection( status : Boolean ) allows disabling any data access on the web admin port, including for the Data Explorer in WebAdmin
sessions |
| .setGlobalStamp( newStamp : Real) sets newStamp as new value for the current global modification stamp for the datastore |
| .setRemoteContextInfo( contextName : Text ; dataClassName : Text ; attributes : Text {; contextType : Text { ; pageLength : Integer}})
.setRemoteContextInfo( contextName : Text ; dataClassName : Text; attributesColl : Collection {; contextType : Text { ; pageLength : Integer }} )
.setRemoteContextInfo( contextName : Text ; dataClassObject : 4D.DataClass ; attributes : Text {; contextType : Text { ; pageLength : Integer }})
.setRemoteContextInfo( contextName : Text ; dataClassObject : 4D.DataClass ; attributesColl : Collection {; contextType : Text { ; pageLength : Integer }} ) links the specified dataclass attributes to the contextName optimization context |
| .startRequestLog()
.startRequestLog( file : 4D.File )
.startRequestLog( file : 4D.File ; options : Integer )
.startRequestLog( reqNum : Integer ) starts the logging of ORDA requests on the client side or on the server side |
| .startTransaction() starts a transaction in the current process on the database matching the datastore to which it applies |
| .stopRequestLog() stops any logging of ORDA requests on the machine it is called (client or server) |
| .unlock() removes the current lock on write operations in the datastore, if it has been set in the same process |
| .validateTransaction() accepts the transaction |
ds
Historia
Lanzamiento | Modificaciones |
---|---|
18 | Soporte del parámetro localID |
17 | Añadidos |
ds { ( localID : Text ) } : cs.DataStore
Parámetros | Tipo | Descripción | |
---|---|---|---|
localID | Text | -> | ID local del almacén de datos remoto a devolver |
Result | cs.DataStore | <- | Referencia al almacén de datos |
Descripción
The ds
command returns a reference to the datastore matching the current 4D database or the database designated by localID.
If you omit the localID parameter (or pass an empty string ""), the command returns a reference to the datastore matching the local 4D database (or the 4D Server database in case of opening a remote database on 4D Server). The datastore is opened automatically and available directly through ds
.
You can also get a reference on an open remote datastore by passing its local id in the localID parameter. The datastore must have been previously opened with the Open datastore
command by the current database (host or component). La identificación local se define cuando se utiliza este comando.
El alcance del id local es la base de datos en la que se ha abierto el almacén de datos.
If no localID datastore is found, the command returns Null.
Objects available in the cs.Datastore
are mapped from the target database with respect to the ORDA general rules.
Ejemplo 1
Utilizando el almacén de datos principal de la base 4D:
$result:=ds.Employee.query("firstName = :1";"S@")
Ejemplo 2
var $connectTo; $firstFrench; $firstForeign : Object
var $frenchStudents; $foreignStudents : cs.DataStore
$connectTo:=New object("type";"4D Server";"hostname";"192.168.18.11:8044")
$frenchStudents:=Open datastore($connectTo;"french")
$connectTo.hostname:="192.168.18.11:8050"
$foreignStudents:=Open datastore($connectTo;"foreign")
//...
//...
$firstFrench:=getFirst("french";"Students")
$firstForeign:=getFirst("foreign";"Students")
//getFirst method
//getFirst(localID;dataclass) -> entity
#DECLARE( $localId : Text; $dataClassName : Text ) -> $entity : 4D.Entity
$0:=ds($localId)[$dataClassName].all().first()
Open datastore
Historia
Lanzamiento | Modificaciones |
---|---|
18 | Añadidos |
Open datastore( connectionInfo : Object ; localID : Text ) : cs.DataStore
Parámetros | Tipo | Descripción | |
---|---|---|---|
connectionInfo | Object | -> | Propiedades de conexión utilizadas para alcanzar el almacén de datos remoto |
localID | Text | -> | Id para asignar al almacén de datos abierto en la aplicación local (obligatorio) |
Result | cs.DataStore | <- | Objeto del almacén de datos |
Descripción
The Open datastore
command connects the application to the 4D database identified by the connectionInfo parameter and returns a matching cs.DataStore
object associated with the localID local alias.
The connectionInfo 4D database must be available as a remote datastore, i.e.:
- su servidor web debe ser lanzado con http y/o https activado,
- the datastore must be exposed (Expose as REST server option checked) as well as dataclasses and attributes.
Open datastore
requests rely on the 4D REST API and can require a 4D Client license to open the connection. Refer to the user login mode section to know how to configure the authentication depending on the selected current user login mode.
If no matching database is found, Open datastore
returns Null.
localID is a local alias for the session opened on remote datastore. If localID already exists on the application, it is used. Otherwise, a new localID session is created when the datastore object is used.
Objects available in the cs.Datastore
are mapped from the target database with respect to the ORDA general rules.
Una vez abierta la sesión, las siguientes sentencias son equivalentes y devuelven una referencia sobre el mismo objeto datastore:
$myds:=Open datastore(connectionInfo;"myLocalId")
$myds2:=ds("myLocalId")
//$myds y $myds2 son equivalentes
Pass in connectionInfo an object describing the remote datastore you want to connect to. It can contain the following properties (all properties are optional except hostname):
Propiedad | Tipo | Descripción |
---|---|---|
hostname | Text | Nombre o dirección IP de la base de datos remota + ":" + número de puerto (el número de puerto es obligatorio) |
user | Text | Nombre de usuario |
contraseña | Text | Contraseña del usuario |
idleTimeout | Longint | Tiempo de espera de la sesión de inactividad (en minutos), después del cual la sesión es cerrada automáticamente por 4D. Si se omite, el valor por defecto es 60 (1h). The value cannot be < 60 (if a lower value is passed, the timeout is set to 60). For more information, see Closing sessions. |
tls | Boolean | Utilice una conexión segura(*). Si se omite, es false por defecto. Se recomienda utilizar una conexión segura siempre que sea posible. |
type | Text | Debe ser "4D Server" |
(*) Si tls es true, se utiliza el protocolo HTTPS si:
- HTTPS está activado en el almacén de datos remoto
- el número de puerto especificado coincide con el puerto HTTPS configurado en los ajustes de la base de datos
- un certificado válido y una llave privada de encriptación están instalados en la base de datos. En caso contrario, se produce el error "1610 - Una solicitud remota al host xxx ha fallado"
Ejemplo 1
Conexión a un almacén de datos remoto sin usuario/contraseña:
var $connectTo : Object
var $remoteDS : cs.DataStore
$connectTo:=New object("type";"4D Server";"hostname";"192.168.18.11:8044")
$remoteDS:=Open datastore($connectTo;"students")
ALERT("This remote datastore contains "+String($remoteDS.Students.all().length)+" students")
Ejemplo 2
Conexión a un almacén de datos remoto con usuario/contraseña/ timeout / tls:
var $connectTo : Object
var $remoteDS : cs.DataStore
$connectTo:=New object("type";"4D Server";"hostname";\"192.168.18.11:4443";\
"user";"marie";"password";$pwd;"idleTimeout";70;"tls";True)
$remoteDS:=Open datastore($connectTo;"students")
ALERT("This remote datastore contains "+String($remoteDS.Students.all().length)+" students")
Ejemplo 3
Trabajar con varios almacenes de datos remotos:
var $connectTo : Object
var $frenchStudents; $foreignStudents : cs.DataStore
$connectTo:=New object("hostname";"192.168.18.11:8044")
$frenchStudents:=Open datastore($connectTo;"french")
$connectTo.hostname:="192.168.18.11:8050"
$foreignStudents:=Open datastore($connectTo;"foreign")
ALERT("They are "+String($frenchStudents.Students.all().length)+" French students")
ALERT("They are "+String($foreignStudents.Students.all().length)+" foreign students")
Gestión de errores
In case of error, the command returns Null. Si no se puede acceder al almacén de datos remoto (dirección incorrecta, servidor web no iniciado, http y https no habilitados...), se produce el error 1610 "Ha fallado una petición remota al host XXX". You can intercept this error with a method installed by ON ERR CALL
.
.dataclassName
Historia
Lanzamiento | Modificaciones |
---|---|
17 | Añadidos |
.dataclassName : 4D.DataClass
Descripción
Each dataclass in a datastore is available as a property of the DataStore objectdata. El objeto devuelto contiene una descripción de la clase de datos.
Ejemplo
var $emp : cs.Employee
var $sel : cs.EmployeeSelection
$emp:=ds.Employee //$emp contiene la dataclass Employee
$sel:=$emp.all() //obtiene una selección de entidades de todos los empleados
//también puede escribir directamente:
$sel:=ds.Employee.all()
.cancelTransaction()
Historia
Lanzamiento | Modificaciones |
---|---|
18 | Añadidos |
.cancelTransaction()
Parámetros | Tipo | Descripción | |
---|---|---|---|
No requiere ningún parámetro |
Descripción
The .cancelTransaction()
function cancels the transaction opened by the .startTransaction()
function at the corresponding level in the current process for the specified datastore.
The .cancelTransaction()
function cancels any changes made to the data during the transaction.
Puede anidar varias transacciones (subtransacciones). If the main transaction is cancelled, all of its sub-transactions are also cancelled, even if they were validated individually using the .validateTransaction()
function.
Ejemplo
See example for the .startTransaction()
function.
.clearAllRemoteContexts()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R5 | Añadidos |
.clearAllRemoteContexts()
Parámetros | Tipo | Descripción | |
---|---|---|---|
No requiere ningún parámetro |
Descripción
The .clearAllRemoteContexts()
function clears all the attributes for all the active contexts in the datastore.
Esta función se utiliza principalmente en el contexto de la depuración. Una cosa a tener en cuenta es que cuando se abre el depurador, éste envía peticiones al servidor y consulta todos los atributos de la clase de datos para mostrarlos. Esto puede sobrecargar sus contextos con datos innecesarios.
In such cases, you can use .clearAllRemoteContexts()
to clear your contexts and keep them clean.
Ver también
.getRemoteContextInfo()
.getAllRemoteContexts()
.setRemoteContextInfo()
.encryptionStatus()
Historia
Lanzamiento | Modificaciones |
---|---|
17 R5 | Añadidos |
.encryptionStatus(): Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Object | <- | Información sobre el cifrado del almacén de datos actual y de cada tabla |
Descripción
The .encryptionStatus()
function returns an object providing the encryption status for the current data file (i.e., the data file of the ds
datastore). También se proporciona el estado de cada tabla.
Use the
Data file encryption status
command to determine the encryption status of any other data file.
Valor devuelto
El objeto devuelto contiene las siguientes propiedades:
Propiedad | Tipo | Descripción | ||
---|---|---|---|---|
isEncrypted | Boolean | True si el archivo de datos está encriptado | ||
keyProvided | Boolean | True si se proporciona la llave de encriptación que coincide con el archivo de datos encriptados(*). | ||
tablas | Object | Objeto que contiene tantas propiedades como tablas encriptadas o codificadas. | ||
tableName | Object | Tabla encriptada o cifrada | ||
name | Text | Nombre de la tabla | ||
num | Number | Número de tabla | ||
isEncryptable | Boolean | Verdadero si la tabla está declarada como encriptada en el archivo de estructura | ||
isEncrypted | Boolean | True si los registros de la tabla están encriptados en el archivo de datos |
(*) Se puede suministrar la llave de encriptación:
- with the
.provideDataKey()
command, - en la raíz de un dispositivo conectado antes de abrir el almacén de datos,
- with the
Discover data key
command.
Ejemplo
Quiere saber el número de tablas encriptadas en el archivo de datos actual:
var $status : Object
$status:=ds.encryptionStatus()
If($status.isEncrypted) //the database is encrypted
C_LONGINT($vcount)
C_TEXT($tabName)
For each($tabName;$status.tables)
If($status.tables[$tabName].isEncrypted)
$vcount:=$vcount+1
End if
End for each
ALERT(String($vcount)+" encrypted table(s) in this datastore.")
Else
ALERT("This database is not encrypted.")
End if
.flushAndLock()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Añadidos |
.flushAndLock()
Parámetros | Tipo | Descripción | |
---|---|---|---|
No requiere ningún parámetro |
Descripción
The .flushAndLock()
function flushes the cache of the local datastore and prevents other processes from performing write operations on the database. El datastore se pone en un estado consistente y congelado. Es necesario llamar a esta función antes de ejecutar una instantánea de la aplicación, por ejemplo.
Esta función sólo puede llamarse:
- on the local datastore (
ds
). - en entorno cliente/servidor, en la máquina servidor.
Once this function is executed, write operations such as .save()
or other .flushAndLock()
calls are frozen in all other processes until the datastore is unlocked.
When multiple calls to .flushAndLock()
have been done in the same process, the same number of .unlock()
calls must be executed to actually unlock the datastore.
El datastore se desbloquea cuando:
- the
.unlock()
function is called in the same process, or - the process that called the
.flushAndLock()
function is killed.
If the datastore is already locked from another process, the .flushAndLock()
call is frozen and will be executed when the datastore will be unlocked.
An error is triggered if the .flushAndLock()
function cannot be executed (e.g. it is run on a remote 4D), .
Ejemplo
Desea crear una copia de la carpeta de datos junto con su archivo de historial actual:
$destination:=Folder(fk documents folder).folder("Archive")
$destination.create()
ds.flushAndLock() //Bloquear operaciones de escritura de otros procesos
$dataFolder:=Folder(fk data folder)
$dataFolder.copyTo($destination) //Copiar la carpeta de datos
$oldJournalPath:=New log file //Cerrar el historial y crear uno nuevo
$oldJournal:=File($oldJournalPath; fk platform path)
$oldJournal.moveTo($destination) //Guardar el antiguo historial con datos
ds.unlock() //Nuestra copia ha terminado, ahora podemos desbloquear el datastore
Ver también
.getAllRemoteContexts()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R5 | Añadidos |
.getAllRemoteContexts() : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Collection | <- | Colección de objetos contextos de optimización |
Advanced mode: This function is intended for developers who need to customize ORDA default features for specific configurations. En la mayoría de los casos, no será necesario utilizarla.
Descripción
The .getAllRemoteContexts()
function returns a collection of objects containing information on all the active optimization contexts in the datastore.
For more information on how contexts can be created, see client/server optimization.
Each object in the returned collection has the properties listed in the .getRemoteContextInfo()
section.
Ejemplo
The following code sets up two contexts and retrieves them using .getAllRemoteContexts()
:
var $ds : 4D.DataStoreImplementation
var $persons : cs.PersonsSelection
var $addresses : cs.AddressSelection
var $p : cs.PersonsEntity
var $a : cs.AddressEntity
var $contextA; $contextB : Object
var $info : Collection
var $text : Text
// Open remote datastore
$ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")
// Set context A
$contextA:=New object("context"; "contextA")
$persons:=$ds.Persons.all($contextA)
$text:=""
For each ($p; $persons)
$text:=$p.firstname+" lives in "+$p.address.city+" / "
End for each
// Set context B
$contextB:=New object("context"; "contextB")
$addresses:=$ds.Address.all($contextB)
$text:=""
For each ($a; $addresses)
$text:=$a.zipCode
End for each
// Get all remote contexts (in this case, contextA and contextB)
$info:=$ds.getAllRemoteContexts()
//$info = [{name:"contextB"; dataclass: "Address"; main:"zipCode"},
{name:"contextA";dataclass:"Persons";main:"firstname,address.city"}]
Este ejemplo sirve como demostración, no está pensado para una implementación real.
Ver también
.getRemoteContextInfo()
.setRemoteContextInfo()
.clearAllRemoteContexts()
.getGlobalStamp()
Historia
Lanzamiento | Modificaciones |
---|---|
20 R3 | Añadidos |
.getGlobalStamp() : Real
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Real | <- | Valor actual del marcador de modificación global |
Descripción
The .getGlobalStamp()
function returns the current value of the global modification stamp of the datastore.
Esta función sólo puede llamarse:
- on the local datastore (
ds
). - en entorno cliente/servidor, en la máquina servidor.
For more information on global stamp and data change tracking, please refer to the Using the Global Stamp page.
Ejemplo
var $currentStamp : Real
var $hasModifications : Boolean
$currentStamp:=ds.getGlobalStamp()
methodWhichCouldModifyEmployees //ejecutar código
$hasModifications:=($currentStamp # ds.getGlobalStamp())
Ver también
.getInfo()
Historia
Lanzamiento | Modificaciones |
---|---|
17 | Añadidos |
.getInfo(): Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Object | <- | Propiedades del almacén de datos |
Descripción
The .getInfo()
function returns an object providing information about the datastore. Esta función es útil para configurar el código genérico.
Objeto devuelto
Propiedad | Tipo | Descripción | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
type | string | ||||||||||||||||
networked | boolean | ||||||||||||||||
localID | text | ID del almacén de datos en la máquina. Corresponds to the localId string given with the Open datastore command. Cadena vacía ("") para el almacén de datos principal. | |||||||||||||||
connection | object | Objeto que describe la conexión del almacén de datos remoto (no se devuelve para el almacén de datos principal). Available properties:
|
- If the
.getInfo()
function is executed on a 4D Server or 4D single-user,networked
is False. - If the
.getInfo()
function is executed on a remote 4D,networked
is True
Ejemplo 1
var $info : Object
$info:=ds.getInfo() //Ejecutado en 4D Server o 4D
//{"type":"4D","networked":false,"localID":""}
$info:=ds.getInfo() // Ejecutado en 4D remoto
//{"type":"4D","networked":true,"localID":""}
Ejemplo 2
En un almacén de datos remoto:
var $remoteDS : cs.DataStore
var $info; $connectTo : Object
$connectTo:=New object("hostname";"111.222.33.44:8044";"user";"marie";"password";"aaaa")
$remoteDS:=Open datastore($connectTo;"students")
$info:=$remoteDS.getInfo()
//{"type":"4D Server",
//"localID":"students",
//"networked":true,
//"connection":{hostname:"111.222.33.44:8044","tls":false,"idleTimeout":2880,"user":"marie"}}
.getRemoteContextInfo()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R5 | Añadidos |
.getRemoteContextInfo(contextName : Text) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
contextName | Text | -> | Nombre del contexto |
Result | Object | <- | Descripción del contexto |
Advanced mode: This function is intended for developers who need to customize ORDA default features for specific configurations. En la mayoría de los casos, no será necesario utilizarla.
Descripción
The .getRemoteContextInfo()
function returns an object that holds information on the contextName optimization context in the datastore..
For more information on how optimization contexts can be created, see client/server optimization.
Objeto devuelto
El objeto devuelto tiene las siguientes propiedades:
Propiedad | Tipo | Descripción |
---|---|---|
name | Text | Nombre del contexto |
main | Text | Atributo(s) asociado(s) al contexto (los nombres de atributos están separados por comas) |
dataclass | Text | Nombre de la clase de datos |
currentItem (opcional) | Text | The attributes of the page mode if the context is linked to a list box. Returned as Null or empty text element if the context name is not used for a list box, or if there is no context for the currentItem |
Since contexts behave as filters for attributes, if main is returned empty, it means that no filter is applied, and that the server returns all the dataclass attributes.
Ejemplo
See the example from the .setRemoteContextInfo() section.
Ver también
.setRemoteContextInfo()
.getAllRemoteContexts()
.clearAllRemoteContexts()
.getRequestLog()
Historia
Lanzamiento | Modificaciones |
---|---|
17 R6 | Añadidos |
.getRequestLog() : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Collection | <- | Colección de objetos, donde cada objeto describe una solicitud |
Descripción
The .getRequestLog()
function returns the ORDA requests logged in memory on the client side. The ORDA request logging must have previously been enabled using the .startRequestLog()
function.
Esta función debe ser llamada en un 4D remoto, de lo contrario devuelve una colección vacía. Está diseñado para fines de depuración en configuraciones cliente/servidor.
Valor devuelto
Colección de objetos de petición apilados. La solicitud más reciente tiene el índice 0.
For a description of the ORDA request log format, please refer to the ORDA client requests section.
Ejemplo
See Example 2 of .startRequestLog()
.
.isAdminProtected()
Historia
Lanzamiento | Modificaciones |
---|---|
18 R6 | Añadidos |
.isAdminProtected() : Boolean
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Boolean | <- | True si el acceso al Explorador de Datos está desactivado, False si está activado (por defecto) |
Descripción
The .isAdminProtected()
function returns True
if Data Explorer access has been disabled for the working session.
By default, the Data Explorer access is granted for webAdmin
sessions, but it can be disabled to prevent any data access from administrators (see the .setAdminProtection()
function).
Ver también
.locked()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Añadidos |
.locked() : Boolean
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Boolean | <- | True si bloqueado |
Descripción
The .locked()
function returns True if the local datastore is currently locked.
You can lock the datastore using the .flushAndLock() function before executing a snapshot of the data file, for example.
The function will also return True
if the datastore was locked by another administration feature such as backup or vss (see .flushAndLock()).
Ver también
.makeSelectionsAlterable()
Historia
Lanzamiento | Modificaciones |
---|---|
18 R5 | Añadidos |
.makeSelectionsAlterable()
Parámetros | Tipo | Descripción | |
---|---|---|---|
No requiere ningún parámetro |
Descripción
The .makeSelectionsAlterable()
function sets all entity selections as alterable by default in the current application datastores (including remote datastores). It is intended to be used once, for example in the On Startup
database method.
When this function is not called, new entity selections can be shareable, depending on the nature of their "parent", or how they are created.
This function does not modify entity selections created by
.copy()
orOB Copy
when the explicitck shared
option is used.
Compatibility: This function must only be used in projects converted from 4D versions prior to 4D v18 R5 and containing .add() calls. In this context, using
.makeSelectionsAlterable()
can save time by restoring instantaneously the previous 4D behavior in existing projects. On the other hand, using this method in new projects created in 4D v18 R5 and higher is not recommended, since it prevents entity selections to be shared, which provides greater performance and scalabitlity.
.provideDataKey()
Historia
Lanzamiento | Modificaciones |
---|---|
17 R5 | Añadidos |
.provideDataKey( curPassPhrase : Text ) : Object
.provideDataKey( curDataKey : Object ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
curPassPhrase | Text | -> | Frase de cifrado actual |
curDataKey | Object | -> | Llave de encriptación de datos actual |
Result | Object | <- | Resultado de la coincidencia de la llave de encriptación |
Descripción
The .provideDataKey()
function allows providing a data encryption key for the current data file of the datastore and detects if the key matches the encrypted data. Esta función se puede utilizar al abrir una base encriptada, o al ejecutar cualquier operación de encriptación que requiera la llave de encriptación, como por ejemplo volver a encriptar el archivo de datos.
- The
.provideDataKey()
function must be called in an encrypted database. If it is called in a non-encrypted database, the error 2003 (the encryption key does not match the data.) is returned. Use theData file encryption status
command to determine if the database is encrypted.- The
.provideDataKey()
function cannot be called from a remote 4D or an encrypted remote datastore.
If you use the curPassPhrase parameter, pass the string used to generate the data encryption key. Cuando se utiliza este parámetro, se genera una llave de encriptación.
If you use the curDataKey parameter, pass an object (with encodedKey property) that contains the data encryption key. This key may have been generated with the New data key
command.
If a valid data encryption key is provided, it is added to the keyChain in memory and the encryption mode is enabled:
- todas las modificaciones de datos en las tablas encriptadas se cifran en el disco (.4DD, .journal. 4Dindx)
- todos los datos cargados desde tablas encriptadas se descifran en memoria
Resultado
El resultado de la orden se describe en el objeto devuelto:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la llave de encriptación proporcionada coincide con los datos encriptados, False en caso contrario | |
Properties below are returned only if success is FALSE | |||
status | Number | Código de error (4 si la llave de encriptación suministrada es errónea) | |
statusText | Text | Mensaje de error | |
errors | Collection | Pila de errores. El primer error tiene el índice más alto | |
[ ].componentSignature | Text | Nombre del componente interno | |
[ ].errCode | Number | Número de error | |
[ ].message | Text | Mensaje de error |
If no curPassphrase or curDataKey is given, .provideDataKey()
returns null (no error is generated).
Ejemplo
var $keyStatus : Object
var $passphrase : Text
$passphrase:=Request("Enter the passphrase")
If(OK=1)
$keyStatus:=ds.provideDataKey($passphrase)
If($keyStatus.success)
ALERT("You have provided a valid encryption key")
Else
ALERT("You have provided an invalid encryption key, you will not be able to work with encrypted data")
End if
End if
.setAdminProtection()
Historia
Lanzamiento | Modificaciones |
---|---|
18 R6 | Añadidos |
.setAdminProtection( status : Boolean )
Parámetros | Tipo | Descripción | |
---|---|---|---|
status | Boolean | -> | True to disable Data Explorer access to data on the webAdmin port, False (default) to grant access |
Descripción
The .setAdminProtection()
function allows disabling any data access on the web admin port, including for the Data Explorer in WebAdmin
sessions.
By default when the function is not called, access to data is always granted on the web administration port for a session with WebAdmin
privilege using the Data Explorer. In some configurations, for example when the application server is hosted on a third-party machine, you might not want the administrator to be able to view your data, although they can edit the server configuration, including the access key settings.
In this case, you can call this function to disable the data access from Data Explorer on the web admin port of the machine, even if the user session has the WebAdmin
privilege. Cuando se ejecuta esta función, el archivo de datos se protege inmediatamente y el estado se almacena en el disco: el archivo de datos estará protegido incluso si se reinicia la aplicación.
Ejemplo
You create a protectDataFile project method to call before deployments for example:
ds.setAdminProtection(True) //Desactiva el acceso a los datos del Explorador de datos
Ver también
.setGlobalStamp()
Historia
Lanzamiento | Modificaciones |
---|---|
20 R3 | Añadidos |
.setGlobalStamp( newStamp : Real)
Parámetros | Tipo | Descripción | |
---|---|---|---|
newStamp | Real | -> | Nuevo valor del marcador de modificación global |
Esta función está destinada a los desarrolladores que necesiten modificar el valor actual del marcador global. Debe utilizarse con cuidado.
Descripción
The .setGlobalStamp()
function sets newStamp as new value for the current global modification stamp for the datastore.
Esta función sólo puede llamarse:
- on the local datastore (
ds
). - en entorno cliente/servidor, en la máquina servidor.
For more information on global stamp and data change tracking, please refer to the Using the Global Stamp page.
Ejemplo
El siguiente código define el marcador de modificación global:
var $newValue: Real
$newValue:=ReadValueFrom //obtener un nuevo valor para asignar
ds.setGlobalStamp($newValue)
Ver también
.setRemoteContextInfo()
Historia
Lanzamiento | Modificaciones |
---|---|
19 R5 | Añadidos |
.setRemoteContextInfo( contextName : Text ; dataClassName : Text ; attributes : Text {; contextType : Text { ; pageLength : Integer}})
.setRemoteContextInfo( contextName : Text ; dataClassName : Text; attributesColl : Collection {; contextType : Text { ; pageLength : Integer }} )
.setRemoteContextInfo( contextName : Text ; dataClassObject : 4D.DataClass ; attributes : Text {; contextType : Text { ; pageLength : Integer }})
.setRemoteContextInfo( contextName : Text ; dataClassObject : 4D.DataClass ; attributesColl : Collection {; contextType : Text { ; pageLength : Integer }} )
Parámetros | Tipo | Descripción | |
---|---|---|---|
contextName | Text | -> | Nombre del contexto |
dataClassName | Text | -> | Nombre de la dataclass |
dataClassObject | 4D.DataClass | -> | dataclass object (e.g datastore. Employee) |
attributes | Text | -> | Lista de atributos separados por comas |
attributesColl | Collection | -> | Colección de nombres de atributos (text) |
contextType | Text | -> | Si se suministra, el valor debe ser "main" o "currentItem" |
pageLength | Integer | -> | Longitud de la página de la selección de entidades asociada al contexto (por defecto es 80) |
Advanced mode: This function is intended for developers who need to customize ORDA default features for specific configurations. En la mayoría de los casos, no será necesario utilizarla.
Descripción
The .setRemoteContextInfo()
function links the specified dataclass attributes to the contextName optimization context. Si ya existe un contexto de optimización para los atributos especificados, este comando lo reemplaza.
Cuando se pasa un contexto a las funciones de clase ORDA, la optimización de las peticiones REST se activa inmediatamente:
- la primera entidad no está totalmente cargada como se hace en el modo automático
- pages of 80 entities (or
pageLength
entities) are immediately asked to the server with only the attributes in the context
For more information on how optimization contexts are built, refer to the client/server optimization paragraph
In contextName, pass the name of the optimization context to link to the dataclass attributes.
To designate the dataclass that will receive the context, you can pass a dataClassName or a dataClassObject.
To designate the attributes to link to the context, pass either a list of attributes separated by a comma in attributes (Text), or a collection of attribute names in attributesColl (collection of text).
If attributes is an empty Text, or attributesColl is an empty collection, all the scalar attributes of the dataclass are put in the optimization context. Si se pasa un atributo que no existe en la dataclass, la función lo ignora y se genera un error.
You can pass a contextType to specify if the context is a standard context or the context of the current entity selection item displayed in a list box:
- If set to "main" (default), the contextName designates a standard context.
- Si su valor es "currentItem", los atributos pasados se ponen en el contexto del elemento actual. See Entity selection-based list box.
In pageLength, specify the number of dataclass entities to request from the server.
You can pass a pageLength for a relation attribute which is an entity selection (one to many). The syntax is relationAttributeName:pageLength
(e.g employees:20).
Ejemplo 1
var $ds : 4D.DataStoreImplementation
var $persons : cs.PersonsSelection
var $p : cs.PersonsEntity
var $contextA : Object
var $info : Object
var $text : Text
// Abrir datastore remoto
$ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")
// Definir el contexto
$contextA:=New object("context"; "contextA")
$ds.setRemoteContextInfo("contextA"; $ds.Persons; "firstname, lastname")
// Envía las peticiones al servidor utilizando un bucle
$persons:=$ds.Persons.all($contextA)
$text:=""
For each ($p; $persons)
$text:=$p.firstname + " " + $p.lastname
End for each
// Verificar el contenido del contexto
$info:=$ds.getRemoteContextInfo("contextA")
// $info = {name:"contextA";dataclass:"Persons";main:"firstname, lastname"}
Este ejemplo sirve como demostración, no está pensado para una implementación real.
Ejemplo 2
The following piece of code requests pages of 30 entities of the Address
dataclass from the server. The returned entities only contain the zipCode
attribute.
For each Address
entity, 20 Persons entities are returned, and they only contain the lastname
and firstname
attributes:
var $ds : 4D.DataStoreImplementation
$ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")
$ds.setRemoteContextInfo("contextA"; $ds.Address; "zipCode, persons:20,\
persons.lastname, persons.firstname"; "main"; 30)
Ejemplo 3 - Listbox
// When the form loads
Case of
: (Form event code=On Load)
Form.ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")
// Set the attributes of the page context
Form.ds.setRemoteContextInfo("LB"; Form.ds.Persons; "age, gender,\
children"; "currentItem")
Form.settings:=New object("context"; "LB")
Form.persons:=Form.ds.Persons.all(Form.settings)
// Form.persons is displayed in a list box
End case
// When you get the attributes in the context of the current item: Form.currentItemLearntAttributes:=Form.selectedPerson.getRemoteContextAttributes()
// Form.currentItemLearntAttributes = "age, gender, children"
Ver también
.getRemoteContextInfo()
.getAllRemoteContexts()
.clearAllRemoteContexts()
.startRequestLog()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Server side support, new options parameter |
17 R6 | Añadidos |
.startRequestLog()
.startRequestLog( file : 4D.File )
.startRequestLog( file : 4D.File ; options : Integer )
.startRequestLog( reqNum : Integer )
Parámetros | Tipo | Descripción | |
---|---|---|---|
file | 4D.File | -> | Objeto File |
options | Integer | -> | Opción de registro de respuesta (servidor únicamente) |
reqNum | Integer | -> | Número de peticiones a mantener en memoria (cliente únicamente) |
Descripción
The .startRequestLog()
function starts the logging of ORDA requests on the client side or on the server side. Está diseñado para fines de depuración en configuraciones cliente/servidor.
For a description of the ORDA request log format, please refer to the ORDA requests section.
Del lado del cliente
Para crear un registro de peticiones ORDA del lado del cliente, llame a esta función en una máquina remota. El registro puede enviarse a un archivo o a la memoria, según el tipo de parámetro:
- If you passed a file object created with the
File
command, the log data is written in this file as a collection of objects (JSON format). Cada objeto representa una petición.
Si el archivo no existe ya, se crea. En caso contrario, si el archivo ya existe, los nuevos datos de registro se añaden a él. If.startRequestLog()
is called with a file while a logging was previously started in memory, the memory log is stopped and emptied.
Debe añadirse manualmente un carácter \N al final del archivo para realizar una validación JSON
If you passed a reqNum integer, the log in memory is emptied (if any) and a new log is initialized. It will keep reqNum requests in memory until the number is reached, in which case the oldest entries are emptied (FIFO stack).
If.startRequestLog()
is called with a reqNum while a logging was previously started in a file, the file logging is stopped.Si no ha pasado ningún parámetro, el registro se inicia en la memoria. If
.startRequestLog()
was previously called with a reqNum (before a.stopRequestLog()
), the log data is stacked in memory until the next time the log is emptied or.stopRequestLog()
is called.
Del lado del servidor
Para crear un registro de peticiones ORDA del lado del servidor, llame a esta función en la máquina servidor. The log data is written in a file in .jsonl
format. Cada objeto representa una petición. Si el archivo no existe, se crea. En caso contrario, si el archivo ya existe, los nuevos datos de registro se añaden a él.
- If you passed the file parameter, the log data is written in this file, at the requested location. - If you omit the file parameter or if it is null, the log data is written in a file named ordaRequests.jsonl and stored in the "/LOGS" folder.
- The options parameter can be used to specify if the server response has to be logged, and if it should include the body. Por defecto, cuando se omite el parámetro, se registra la respuesta completa. En este parámetro se pueden utilizar las siguientes constantes:
|Constant|Description| |----|----|---| |srl log all|Log the response entirely (default value)| |srl log no response|Disable the logging of the response| |srl log response without body|Log the response without the body|
Ejemplo 1
Desea registrar las solicitudes de los clientes ORDA en un archivo y utilizar el número de secuencia del registro:
var $file : 4D.File
var $e : cs.PersonsEntity
$file:=File("/LOGS/ORDARequests.txt") //logs folder
SET DATABASE PARAMETER(Client Log Recording;1) //to trigger the global log sequence number
ds.startRequestLog($file)
$e:=ds.Persons.get(30001) //send a request
ds.stopRequestLog()
SET DATABASE PARAMETER(Client Log Recording;0)
Ejemplo 2
Quiere registrar las peticiones de los clientes ORDA en la memoria:
var $es : cs.PersonsSelection
var $log : Collection
ds.startRequestLog(3) //keep 3 requests in memory
$es:=ds.Persons.query("name=:1";"Marie")
$es:=ds.Persons.query("name IN :1";New collection("Marie"))
$es:=ds.Persons.query("name=:1";"So@")
$log:=ds.getRequestLog()
ALERT("The longest request lasted: "+String($log.max("duration"))+" ms")
Ejemplo 3
Desea registrar las peticiones del servidor ORDA en un archivo específico y habilitar el número de secuencia de registro y la duración:
SET DATABASE PARAMETER(4D Server Log Recording;1)
$file:=Folder(fk logs folder).file("myOrdaLog.jsonl")
ds.startRequestLog($file)
...
ds.stopRequestLog()
SET DATABASE PARAMETER(4D Server Log Recording;0)
.startTransaction()
Historia
Lanzamiento | Modificaciones |
---|---|
18 | Añadidos |
.startTransaction()
Parámetros | Tipo | Descripción | |
---|---|---|---|
No requiere ningún parámetro |
Descripción
The .startTransaction()
function starts a transaction in the current process on the database matching the datastore to which it applies. Todos los cambios realizados en las entidades del almacén de datos en el proceso de la transacción se almacenan temporalmente hasta que la transacción se valida o se cancela.
If this method is called on the main datastore (i.e. the datastore returned by the
ds
command), the transaction is applied to all operations performed on the main datastore and on the underlying database, thus including ORDA and classic languages.
Puede anidar varias transacciones (subtransacciones). Cada transacción o sub-transacción debe ser eventualmente cancelada o validada. Note that if the main transaction is cancelled, all of its sub-transactions are also cancelled even if they were validated individually using the .validateTransaction()
function.
Ejemplo
var $connect; $status : Object
var $person : cs.PersonsEntity
var $ds : cs.DataStore
var $choice : Text
var $error : Boolean
Case of
:($choice="local")
$ds:=ds
:($choice="remote")
$connect:=New object("hostname";"111.222.3.4:8044")
$ds:=Open datastore($connect;"myRemoteDS")
End case
$ds.startTransaction()
$person:=$ds.Persons.query("lastname=:1";"Peters").first()
If($person#Null)
$person.lastname:="Smith"
$status:=$person.save()
End if
...
...
If($error)
$ds.cancelTransaction()
Else
$ds.validateTransaction()
End if
.stopRequestLog()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Soporte del lado del servidor |
17 R6 | Añadidos |
.stopRequestLog()
Parámetros | Tipo | Descripción | |
---|---|---|---|
No requiere ningún parámetro |
Descripción
The .stopRequestLog()
function stops any logging of ORDA requests on the machine it is called (client or server).
En realidad, cierra el documento abierto en el disco. Del lado del cliente, si el registro se inició en memoria, se detiene.
Esta función no hace nada si el registro de peticiones ORDA no se inició en la máquina.
Ejemplo
See examples for .startRequestLog()
.
.unlock()
Historia
Lanzamiento | Modificaciones |
---|---|
20 | Añadidos |
.unlock()
Parámetros | Tipo | Descripción | |
---|---|---|---|
No requiere ningún parámetro |
Descripción
The .unlock()
function removes the current lock on write operations in the datastore, if it has been set in the same process. Write operations can be locked in the local datastore using the .flushAndLock()
function.
Si el bloqueo actual era el único bloqueo en el datastore, las operaciones de escritura se activan inmediatamente. If the .flushAndLock()
function was called several times in the process, the same number of .unlock()
must be called to actually unlock the datastore.
The .unlock()
function must be called from the process that called the corresponding .flushAndLock()
, otherwise the function does nothing and the lock is not removed.
If the .unlock()
function is called in an unlocked datastore, it does nothing.
Ver también
.validateTransaction()
Historia
Lanzamiento | Modificaciones |
---|---|
18 | Añadidos |
.validateTransaction()
Parámetros | Tipo | Descripción | |
---|---|---|---|
No requiere ningún parámetro |
Descripción
The .validateTransaction()
function accepts the transaction that was started with .startTransaction()
at the corresponding level on the specified datastore.
La función guarda los cambios en los datos del almacén de datos que se produjeron durante la transacción.
Puede anidar varias transacciones (subtransacciones). Si se cancela la transacción principal, también se cancelan todas sus subtransacciones, aunque se hayan validado individualmente utilizando esta función.
Ejemplo
See example for .startTransaction()
.