Aller au contenu principal
Version: 20 R5 BETA

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

Sommaire

.cancelTransaction()
cancels the transaction
.clearAllRemoteContexts()
clears all the attributes for all the active contexts in the datastore
.dataclassName : 4D.DataClass
contient la description de la dataclass
.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

Historique
ReleaseModifications
18Prise en charge du paramètre localID
17Ajout

ds { ( localID : Text ) } : cs.DataStore

ParamètresTypeDescription
localIDText->Identifiant local du datastore distant
Résultatcs.DataStore<-Nouvelle référence de datastore

Description

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). L'identifiant local est défini lors de l'utilisation de cette commande.

La portée de l'identifiant local est la base de données dans laquelle le datastore a été ouvert.

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.

Exemple 1

Utilisation du datastore principal de la base 4D :

 $result:=ds.Employee.query("firstName = :1";"S@")

Exemple 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

Historique
ReleaseModifications
18Ajout

Open datastore( connectionInfo : Object ; localID : Text ) : cs.DataStore

ParamètresTypeDescription
connectionInfoObject->Propriétés de connexion utilisées pour joindre le datastore distant
localIDText->Identifiant à affecter au datastore ouvert sur l'application locale (obligatoire)
Résultatcs.DataStore<-Objet datastore

Description

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.:

note

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.

Une fois la session ouverte, les instructions suivantes deviennent équivalentes et renvoient une référence sur le même objet datastore :

 $myds:=Open datastore(connectionInfo;"myLocalId")
$myds2:=ds("myLocalId")
//$myds et $myds2 sont équivalents

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):

PropriétéTypeDescription
hostnameTextNom ou adresse IP de la base de données distante + " :" + numéro de port (le numéro de port est obligatoire)
userTextNom d'utilisateur
passwordTextMot de passe de l'utilisateur
idleTimeoutLongintDélai d'inactivité de la session (exprimé en minutes), au terme duquel la session est automatiquement fermée par 4D. Si cette propriété est omise, la valeur par défaut est 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.
tlsBooleanUtilisez une connexion sécurisée(*). Si cette propriété est omise, "false" par défaut. L'utilisation d'une connexion sécurisée est recommandée dans la mesure du possible.
typeTextDoit être "4D Server"

(*) Si tls est vrai, le protocole HTTPS est utilisé si :

  • HTTPS est activé sur le datastore distant
  • Le port donné correspond au port HTTPS configuré dans les propriétés
  • Un certificat valide et une clé de chiffrement privée sont installés dans la base. Sinon, l'erreur "1610 - Une requête vers l’hôte: "{xxx}" a échoué" est générée

Exemple 1

Connexion à un datastore distant sans utilisateur/mot de passe :

 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")

Exemple 2

Connexion à un datastore distant avec utilisateur/mot de passe/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")

Exemple 3

Travailler avec plusieurs datastores distants :

 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")

Gestion des erreurs

In case of error, the command returns Null. Si le datastore distant ne peut pas être joint (adresse incorrecte, web serveur non lancé, http et https non activés, etc.), l'erreur 1610 "Une requête vers l’hôte: {xxx} a échoué" est générée. You can intercept this error with a method installed by ON ERR CALL.

.dataclassName

Historique
ReleaseModifications
17Ajout

.dataclassName : 4D.DataClass

Description

Each dataclass in a datastore is available as a property of the DataStore objectdata. L'objet retourné contient la description de la dataclass.

Exemple

 var $emp : cs.Employee
var $sel : cs.EmployeeSelection
$emp:=ds.Employee //$emp contient la dataclass Employee
$sel:=$emp.all() //obtient une entity selection de tous les employés

//vous poubez également saisir directement :
$sel:=ds.Employee.all()

.cancelTransaction()

Historique
ReleaseModifications
18Ajout

.cancelTransaction()

ParamètresTypeDescription
Ne requiert aucun paramètre

Description

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.

Vous pouvez imbriquer plusieurs transactions (sous-transactions). If the main transaction is cancelled, all of its sub-transactions are also cancelled, even if they were validated individually using the .validateTransaction() function.

Exemple

See example for the .startTransaction() function.

.clearAllRemoteContexts()

Historique
ReleaseModifications
19 R5Ajout

.clearAllRemoteContexts()

ParamètresTypeDescription
Ne requiert aucun paramètre

Description

The .clearAllRemoteContexts() function clears all the attributes for all the active contexts in the datastore.

Cette fonction est utile principalement dans le contexte du débogage. Gardez à l'esprit que lorsque vous ouvrez le débogueur, il envoie des requêtes au serveur et récupère tous les attributs de la dataclass pour les afficher. Cela peut surcharger vos contextes avec des données inutiles.

In such cases, you can use .clearAllRemoteContexts() to clear your contexts and keep them clean.

Voir également

.getRemoteContextInfo()
.getAllRemoteContexts()
.setRemoteContextInfo()

.encryptionStatus()

Historique
ReleaseModifications
17 R5Ajout

.encryptionStatus(): Object

ParamètresTypeDescription
RésultatObject<-Informations sur le chiffrement du datastore courant et de chaque table

Description

The .encryptionStatus() function returns an object providing the encryption status for the current data file (i.e., the data file of the ds datastore). Le statut de chiffrement pour chaque table est également fourni.

Use the Data file encryption status command to determine the encryption status of any other data file.

Valeur retournée

L'objet retourné contient les propriétés suivantes :

PropriétéTypeDescription
isEncryptedBooleanVrai si le fichier de données est chiffré
keyProvidedBooleanVrai si la clé de chiffrement correspondant au fichier de données chiffré est fournie(*).
tablesObjectObjet contenant autant de propriétés que de tables chiffrables ou chiffrées.
tableNameObjectTable chiffrable ou chiffrée
nameTextNom de la table
numNumberNuméro de la table
isEncryptableBooleanVrai si la table est déclarée chiffrable dans le fichier de structure
isEncryptedBooleanVrai si les enregistrements de la table sont chiffrés dans le fichier de données

(*) La clé de chiffrement peut être fournie :

  • with the .provideDataKey() command,
  • à la racine d'un appareil connecté avant l'ouverture du datastore,
  • with the Discover data key command.

Exemple

Vous souhaitez connaitre le nombre de tables chiffrées dans le fichier de données courant :

 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()

Historique
ReleaseModifications
20Ajout

.flushAndLock()

ParamètresTypeDescription
Ne requiert aucun paramètre

Description

The .flushAndLock() function flushes the cache of the local datastore and prevents other processes from performing write operations on the database. Le datastore est placé dans un état cohérent et figé. L'appel de cette fonction est nécessaire avant l'exécution d'un instantané d'application (snapshot), par exemple.

info

Cette fonction ne peut être appelée que :

  • on the local datastore (ds).
  • dans un environnement client/serveur, sur la machine serveur.

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.

Le datastore est déverrouillé lorsque :

  • 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), .

caution

Other 4D features and services including backup, vss, and MSC can also lock the datastore. Before calling .flushAndLock(), make sure no other locking action is being used, in order to avoid any unexpected interaction.

Exemple

Vous voulez créer une copie du dossier de données avec son fichier journal courant :

$destination:=Folder(fk documents folder).folder("Archive") 
$destination.create()

ds.flushAndLock() //Bloque les opérations d'écriture des autres process

$dataFolder:=Folder(fk data folder)
$dataFolder.copyTo($destination) //Copie le dossier de données

$oldJournalPath:=New log file //Ferme le journal et en créer un nouveau
$oldJournal:=File($oldJournalPath; fk platform path)
$oldJournal.moveTo($destination) //Sauvegarde l'ancien journal avec les données

ds.unlock() //Notre copie est terminée, nous pouvons maintenant déverrouiller le datastore

Voir également

.locked()
.unlock()

.getAllRemoteContexts()

Historique
ReleaseModifications
19 R5Ajout

.getAllRemoteContexts() : Collection

ParamètresTypeDescription
RésultatCollection<-Collection d'objets contextes d'optimisation

Advanced mode: This function is intended for developers who need to customize ORDA default features for specific configurations. Dans la plupart des cas, vous n'aurez pas besoin de l'utiliser.

Description

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.

Exemple

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

// Accès datastore distant
$ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")

// définition contexte 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

// définition contexte B
$contextB:=New object("context"; "contextB")
$addresses:=$ds.Address.all($contextB)
$text:=""
For each ($a; $addresses)
$text:=$a.zipCode
End for each

// récupérer tous les contextes distants (ici contextA et contextB)
$info:=$ds.getAllRemoteContexts()
//$info = [{name:"contextB"; dataclass:"Address"; main:"zipCode"},
{name:"contextA";dataclass:"Persons";main:"firstname,address.city"}]

Cet exemple est à but de démonstration, il n'est pas destiné à une implémentation réelle.

Voir également

.getRemoteContextInfo()
.setRemoteContextInfo()
.clearAllRemoteContexts()

.getGlobalStamp()

Historique
ReleaseModifications
20 R3Ajout

.getGlobalStamp() : Real

ParamètresTypeDescription
RésultatReal<-Valeur courante du marqueur de modification global

Description

The .getGlobalStamp() function returns the current value of the global modification stamp of the datastore.

info

Cette fonction ne peut être appelée que :

  • on the local datastore (ds).
  • dans un environnement client/serveur, sur la machine serveur.

For more information on global stamp and data change tracking, please refer to the Using the Global Stamp page.

Exemple

var $currentStamp : Real
var $hasModifications : Boolean

$currentStamp:=ds.getGlobalStamp()
methodWhichCouldModifyEmployees //exécuter du code
$hasModifications:=($currentStamp # ds.getGlobalStamp())

Voir également

.setGlobalStamp()

.getInfo()

Historique
ReleaseModifications
17Ajout

.getInfo(): Object

ParamètresTypeDescription
RésultatObject<-Propriétés du datastore

Description

The .getInfo() function returns an object providing information about the datastore. Cette fonction est utile pour l'écriture de code générique.

Returned object

PropriétéTypeDescription
typestring
  • "4D": main datastore, available through ds
  • "4D Server": remote datastore, open with Open datastore
  • networkedboolean
  • True: the datastore is reached through a network connection.
  • False: the datastore is not reached through a network connection (local database)
  • localIDtextIdentifiant du datastore sur la machine. Corresponds to the localId string given with the Open datastore command. Chaîne vide ("") pour le datastore principal.
    connectionobjectObjet décrivant la connexion au datastore distant (non retourné pour le datastore principal). Available properties:
    PropertyTypeDescription
    hostnametextIP address or name of the remote datastore + ":" + port number
    tlsbooleanTrue if secured connection is used with the remote datastore
    idleTimeoutnumberSession inactivity timeout (in minutes)
    usertextUser authenticated on the remote datastore
    • 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

    Exemple 1

     var $info : Object

    $info:=ds.getInfo() //Exécuté sur 4D Server ou 4D
    //{"type":"4D","networked":false,"localID":""}

    $info:=ds.getInfo() // Exécuté sur 4D distant
    //{"type":"4D","networked":true,"localID":""}

    Exemple 2

    Sur un datastore distant :

      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()

    Historique
    ReleaseModifications
    19 R5Ajout

    .getRemoteContextInfo(contextName : Text) : Object

    ParamètresTypeDescription
    contextNameText->Nom du contexte
    RésultatObject<-Description du contexte

    Advanced mode: This function is intended for developers who need to customize ORDA default features for specific configurations. Dans la plupart des cas, vous n'aurez pas besoin de l'utiliser.

    Description

    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.

    Objet retourné

    L'objet retourné contient les propriétés suivantes :

    PropriétéTypeDescription
    nameTextNom du contexte
    mainTextAttribut(s) associé(s) au contexte (les noms d'attributs sont séparés par des virgules)
    dataclassTextNom de la dataclass
    currentItem (optionnel)TextThe 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.

    Exemple

    See the example from the .setRemoteContextInfo() section.

    Voir également

    .setRemoteContextInfo()
    .getAllRemoteContexts()
    .clearAllRemoteContexts()

    .getRequestLog()

    Historique
    ReleaseModifications
    17 R6Ajout

    .getRequestLog() : Collection

    ParamètresTypeDescription
    RésultatCollection<-Collection d'objets décrivant les requêtes

    Description

    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.

    Cette fonction doit être appelée sur un client 4D distant, sinon elle retourne une collection vide. Elle est conçue à des fins de débogage dans les configurations client/serveur.

    Valeur retournée

    Collection d'objets requête empilés. La requête la plus récente porte l'indice 0.

    For a description of the ORDA request log format, please refer to the ORDA client requests section.

    Exemple

    See Example 2 of .startRequestLog().

    .isAdminProtected()

    Historique
    ReleaseModifications
    18 R6Ajout

    .isAdminProtected() : Boolean

    ParamètresTypeDescription
    RésultatBoolean<-Vrai si l'accès au Data Explorer est désactivé, Faux s'il est activé (défaut)

    Description

    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).

    Voir également

    .setAdminProtection()

    .locked()

    Historique
    ReleaseModifications
    20Ajout

    .locked() : Boolean

    ParamètresTypeDescription
    RésultatBoolean<-Vrai si verrouillé

    Description

    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.

    caution

    The function will also return True if the datastore was locked by another administration feature such as backup or vss (see .flushAndLock()).

    Voir également

    .flushAndLock()
    .unlock()

    .makeSelectionsAlterable()

    Historique
    ReleaseModifications
    18 R5Ajout

    .makeSelectionsAlterable()

    ParamètresTypeDescription
    Ne requiert aucun paramètre

    Description

    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() or OB Copy when the explicit ck 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()

    Historique
    ReleaseModifications
    17 R5Ajout

    .provideDataKey( curPassPhrase : Text ) : Object
    .provideDataKey( curDataKey : Object ) : Object

    ParamètresTypeDescription
    curPassPhraseText->Phrase secrète courante
    curDataKeyObject->Clé de chiffrement des données courante
    RésultatObject<-Résultat de la mise en correspondance de la clé de chiffrement

    Description

    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. Cette fonction peut être utilisée à l'ouverture d'une base chiffrée, ou à l'exécution de n'importe quelle opération de chiffrement qui nécessite la clé de chiffrement, telle que le re-chiffrement du fichier de données.

    • 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 the Data 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. Lorsque vous utilisez ce paramètre, une clé de chiffrement est générée.

    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:

    • toutes les modifications de données apportées dans les tables chiffrables sont chiffrées sur le disque (fichiers .4DD, .journal, . 4Dindx).
    • toutes les données chargées à partir de tables chiffrables sont déchiffrées dans la mémoire

    Result

    Le résultat de la commande est décrit dans l'objet retourné :

    PropriétéTypeDescription
    successBooleanVrai si la clé de chiffrement fournie correspond aux données chiffrées, sinon Faux
    Properties below are returned only if success is FALSE
    statusNumberCode d'erreur (4 si la clé de chiffrement fournie est erronée)
    statusTextTextMessage d'erreur
    errorsCollectionPile d'erreurs. La première erreur possède l'indice le plus élevé.
    [ ].componentSignatureTextNom du composant interne
    [ ].errCodeNumberNuméro de l'erreur
    [ ].messageTextMessage d'erreur

    If no curPassphrase or curDataKey is given, .provideDataKey() returns null (no error is generated).

    Exemple

     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()

    Historique
    ReleaseModifications
    18 R6Ajout

    .setAdminProtection( status : Boolean )

    ParamètresTypeDescription
    statusBoolean->True to disable Data Explorer access to data on the webAdmin port, False (default) to grant access

    Description

    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. Lorsque cette fonction est exécutée, le fichier de données est immédiatement protégé et le statut est sauvegardé sur disque : le fichier de données sera protégé même si l'application est redémarrée.

    Exemple

    You create a protectDataFile project method to call before deployments for example:

     ds.setAdminProtection(True) //Désactive l'accès aux données de l'Explorateur de données

    Voir également

    .isAdminProtected()

    .setGlobalStamp()

    Historique
    ReleaseModifications
    20 R3Ajout

    .setGlobalStamp( newStamp : Real)

    ParamètresTypeDescription
    newStampReal->Nouvelle valeur du marqueur de modification global
    Mode avancé

    Cette fonction est destinée aux développeurs qui ont besoin de modifier la valeur courante du marqueur global. Elle doit être utilisée avec précaution.

    Description

    The .setGlobalStamp() function sets newStamp as new value for the current global modification stamp for the datastore.

    info

    Cette fonction ne peut être appelée que :

    • on the local datastore (ds).
    • dans un environnement client/serveur, sur la machine serveur.

    For more information on global stamp and data change tracking, please refer to the Using the Global Stamp page.

    Exemple

    Le code suivant définit le marqueur de modification global:

    var $newValue: Real
    $newValue:=ReadValueFrom //on obtient une valeur à assigner
    ds.setGlobalStamp($newValue)

    Voir également

    .getGlobalStamp()

    .setRemoteContextInfo()

    Historique
    ReleaseModifications
    19 R5Ajout

    .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 }} )

    ParamètresTypeDescription
    contextNameText->Nom du contexte
    dataClassNameText->Nom de la dataclass
    dataClassObject4D.DataClass->Objet dataclass (e.g datastore.Employee)
    attributesText->Liste d'attributs séparés par des virgules
    attributesCollCollection->Collection de noms d'attributs (text)
    contextTypeText->Si passé, "main" ou "currentItem"
    pageLengthInteger->Taille de page de l'entity selection associée au contexte (80 par défaut)

    Advanced mode: This function is intended for developers who need to customize ORDA default features for specific configurations. Dans la plupart des cas, vous n'aurez pas besoin de l'utiliser.

    Description

    The .setRemoteContextInfo() function links the specified dataclass attributes to the contextName optimization context. Si un contexte d'optimisation existe déjà pour les attributs spécifiés, la commande le remplace.

    Lorsque vous passez un contexte aux fonctions de classe ORDA, l'optimisation des requêtes REST est déclenchée immédiatement :

    • la première entité n'est pas chargée intégralement, à la différence du mode automatique
    • 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 vous passez un attribut qui n'existe pas dans la dataclass, la fonction l'ignore et une erreur est générée.

    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 sa valeur est "currentItem", les attributs passés sont intégrés dans le contexte de l'élément courant. 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).

    Exemple 1

    var $ds : 4D.DataStoreImplementation
    var $persons : cs.PersonsSelection
    var $p : cs.PersonsEntity
    var $contextA : Object
    var $info : Object
    var $text : Text

    // Ouvrir datastore distant
    $ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")

    // définir le contexte
    $contextA:=New object("context"; "contextA")
    $ds.setRemoteContextInfo("contextA"; $ds.Persons; "firstname, lastname")

    // envoi de requêtes au serveur dans une boucle
    $persons:=$ds.Persons.all($contextA)
    $text:=""
    For each ($p; $persons)
    $text:=$p.firstname + " " + $p.lastname
    End for each

    // vérifier le contenu du contexte
    $info:=$ds.getRemoteContextInfo("contextA")
    // $info = {name:"contextA";dataclass:"Persons";main:"firstname, lastname"}

    Cet exemple est à but de démonstration, il n'est pas destiné à une implémentation réelle.

    Exemple 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)

    Example 3 - Listbox

    // Au chargement du formulaire
    Case of
    : (Form event code=On Load)

    Form.ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")

    // définir les attributs du contexte de page
    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 est affiché dans une list box
    End case

    // vous récupérez les attributs dans le contexte de l'élément courant:
    Form.currentItemLearntAttributes:=Form.selectedPerson.getRemoteContextAttributes()
    // Form.currentItemLearntAttributes = "age, gender, children"

    Voir également

    .getRemoteContextInfo()
    .getAllRemoteContexts()
    .clearAllRemoteContexts()

    .startRequestLog()

    Historique
    ReleaseModifications
    20Server side support, new options parameter
    17 R6Ajout

    .startRequestLog()
    .startRequestLog( file : 4D.File )
    .startRequestLog( file : 4D.File ; options : Integer )
    .startRequestLog( reqNum : Integer )

    ParamètresTypeDescription
    file4D.File->Objet File
    optionsInteger->Option d'enregistrement de réponse (serveur uniquement)
    reqNumInteger->Nombre de requêtes à conserver en mémoire (client seulement)

    Description

    The .startRequestLog() function starts the logging of ORDA requests on the client side or on the server side. Elle est conçue à des fins de débogage dans les configurations client/serveur.

    info

    For a description of the ORDA request log format, please refer to the ORDA requests section.

    Côté client

    Pour créer un journal des requêtes ORDA côté client, appelez cette fonction sur une machine distante. Le journal peut être envoyé à un fichier ou en mémoire, selon le type de paramètre :

    • 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). Chaque objet représente une requête.
      Si le fichier n'existe pas encore, il est créé. Sinon, s'il existe déjà, les nouvelles données d'enregistrement y sont ajoutées. If .startRequestLog() is called with a file while a logging was previously started in memory, the memory log is stopped and emptied.

    Un caractère ] doit être ajouté manuellement à la fin du fichier pour effectuer une validation 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 vous n'avez passé aucun paramètre, l'enregistrement est lancé dans la mémoire. 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.

    Côté serveur

    Pour créer un journal des requêtes ORDA côté serveur, appelez cette fonction sur la machine serveur. The log data is written in a file in .jsonl format. Chaque objet représente une requête. Si le fichier n'existe pas encore, il est créé. Sinon, s'il existe déjà, les nouvelles données d'enregistrement y sont ajoutées.

    • 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. Par défaut, lorsque le paramètre est omis, la réponse complète est enregistrée. Les constantes suivantes peuvent être utilisées dans ce paramètre :

    |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|

    Exemple 1

    Vous souhaitez enregistrer des requêtes ORDA clientes dans un fichier et utiliser le numéro de séquence de l'enregistrement :

     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)

    Exemple 2

    Vous souhaitez enregistrer des requêtes ORDA clientes dans la mémoire :

     var $es : cs.PersonsSelection
    var $log : Collection

    ds.startRequestLog(3) //garde 3 requêtes dans la mémoire

    $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")

    Exemple 3

    Vous souhaitez enregistrer les requêtes du serveur ORDA dans un fichier spécifique et activer le numéro de séquence du log et la durée :

    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()

    Historique
    ReleaseModifications
    18Ajout

    .startTransaction()

    ParamètresTypeDescription
    Ne requiert aucun paramètre

    Description

    The .startTransaction() function starts a transaction in the current process on the database matching the datastore to which it applies. Toute modification apportée aux entités du datastore dans le process de la transaction est temporairement stockée jusqu'à ce que la transaction soit validée ou annulée.

    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.

    Vous pouvez imbriquer plusieurs transactions (sous-transactions). Chaque transaction ou sous-transaction doit être annulée ou validée. 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.

    Exemple

     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()

    Historique
    ReleaseModifications
    20Server side support
    17 R6Ajout

    .stopRequestLog()

    ParamètresTypeDescription
    Ne requiert aucun paramètre

    Description

    The .stopRequestLog() function stops any logging of ORDA requests on the machine it is called (client or server).

    It actually closes the opened document on disk. On the client side, if the log was started in memory, it is stopped.

    This function does nothing if logging of ORDA requests was not started on the machine.

    Exemple

    See examples for .startRequestLog().

    .unlock()

    Historique
    ReleaseModifications
    20Ajout

    .unlock()

    ParamètresTypeDescription
    Ne requiert aucun paramètre

    Description

    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 le verrou courant était le seul verrou sur le datastore, les opérations d'écriture sont immédiatement réactivées. 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.

    Voir également

    .flushAndLock()
    .locked()

    .validateTransaction()

    Historique
    ReleaseModifications
    18Ajout

    .validateTransaction()

    ParamètresTypeDescription
    Ne requiert aucun paramètre

    Description

    The .validateTransaction() function accepts the transaction that was started with .startTransaction() at the corresponding level on the specified datastore.

    La fonction sauvegarde les modifications apportées aux données sur le datastore durant la transaction.

    Vous pouvez imbriquer plusieurs transactions (sous-transactions). Si la transaction principale est annulée, toutes ses sous-transactions sont également annulées, même si elles ont été validées individuellement à l'aide de cette fonction.

    Exemple

    See example for .startTransaction().