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
Resumo
.cancelTransaction() cancels the transaction |
.clearAllRemoteContexts() clears all the attributes for all the active contexts in the datastore |
.dataclassName : 4D.DataClass contains a description of the 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
História
Release | Mudanças |
---|---|
18 | Suporte do parámetro localID |
17 | Adicionado |
ds { ( localID : Text ) } : cs.DataStore
Parâmetro | Tipo | Descrição | |
---|---|---|---|
localID | Text | -> | ID local del armazém de dados remoto a devolver |
Resultados | cs. DataStore | <- | Referencia ao armazém de dados |
Descrição
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). A identificação local se define quando se utilizar este comando.
O escopo do id local do banco de dados no qual o armazen de dados foi aberto.
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.
Exemplo 1
Usar a datastore principal do banco de dados 4D:
$result:=ds. Employee.query("firstName = :1";"S@")
Exemplo 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
História
Release | Mudanças |
---|---|
18 | Adicionado |
Open datastore( connectionInfo : Object ; localID : Text ) : cs.DataStore
Parâmetro | Tipo | Descrição | |
---|---|---|---|
connectionInfo | Object | -> | Propriedades de conexão utilizadas para alcançar o armazém de datos remoto |
localID | Text | -> | Id para assignar ao armazém de dados aberto na aplicação local (obrigatorio) |
Resultados | cs. DataStore | <- | Objeto do armazém de dados |
Descrição
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.:
- seu servidor web deve ser lançado com http ou https ativado,
- 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.
Quando abrir a sessão, as sentenças abaixo são equivalentes e devolvem uma referência sobre o mesmo objeto datastore:
$myds:=Open datastore(connectionInfo;"myLocalId")
$myds2:=ds("myLocalId")
//$myds e $myds2 são 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):
Propriedade | Tipo | Descrição |
---|---|---|
hostname | Text | Nome ou endereço IP da database remota + ":" + número de porta (o numero de porta é obrigatório) |
user | Text | Nome de usuario |
senha | Text | senha de usuario |
idleTimeout | Longint | Tempo de espera da sessão de inatividade (em minutos) depois do qual a sessão é fechada automaticamente por 4D. Se omitido, o valor por defeito é 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 | Parâmetros | Utilize uma conexão segura(*). Se omitido, false por defeito. Se for omitido, o normal é falso Usar uma conexão segura é recomendado sempre que possível. |
type | Text | Deve ser "4D Server" |
(*) Se tls for true, se utiliza o protocolo HTTPS se:
- HTTPS for ativado no armazém de dados remoto
- o número de porto especificado coincide com o porto HTTPS configurado nos ajustes do banco de dados
- um certificado válido e uma chave privada de criptografia estão instalados no banco de dados. Senão é mostrado o erro "1610 - A remote request to host xxx has failed"
Exemplo 1
Conexão a uma datastore remota com usuário/ senha/ timetou/ tls
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")
Exemplo 2
Conexão a uma datastore remota sem usuário ou senha:
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")
Exemplo 3
Trabalhando com várias datastores remotas:
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")
Gestão de erros
In case of error, the command returns Null. Se não for possível acessar o armazem de dados remotos (endereço incorreto, servidor web não inciiado, http e https não habilitados...), se produz o erro 1610 " Uma petição remota ao host XXX falhou". You can intercept this error with a method installed by ON ERR CALL
.
.dataclassName
História
Release | Mudanças |
---|---|
17 | Adicionado |
.dataclassName : 4D.DataClass
Descrição
Each dataclass in a datastore is available as a property of the DataStore objectdata. The returned object contains a description of the dataclass.
Exemplo
var $emp : cs. Employee
var $sel : cs. EmployeeSelection
$emp:=ds. Employee //$emp contains the Employee dataclass
$sel:=$emp.all() //gets an entity selection of all employees
//you could also write directly:
$sel:=ds. Employee.all()
.cancelTransaction()
História
Release | Mudanças |
---|---|
18 | Adicionado |
.cancelTransaction()
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Não exige nenhum parâmetro |
Descrição
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.
Pode aninhar várias transações (subtransações). If the main transaction is cancelled, all of its sub-transactions are also cancelled, even if they were validated individually using the .validateTransaction()
function.
Exemplo
See example for the .startTransaction()
function.
.clearAllRemoteContexts()
História
Release | Mudanças |
---|---|
19 R5 | Adicionado |
.clearAllRemoteContexts()
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Não exige nenhum parâmetro |
Descrição
The .clearAllRemoteContexts()
function clears all the attributes for all the active contexts in the datastore.
Esta função é utilizada principalmente no contexto da depuração. Deve lembrar que quando abrir o depurador ele envia petições ao servidor e pesquisa todos os atributos de dataclasse para exibi-los Isso pode sobrecarregar seus contextos com dados desnecessários. Isso pode sobrecarregar seus contextos com dados desnecessários.
In such cases, you can use .clearAllRemoteContexts()
to clear your contexts and keep them clean.
Veja também
.getRemoteContextInfo()
.getAllRemoteContexts()
.setRemoteContextInfo()
.encryptionStatus()
História
Release | Mudanças |
---|---|
17 R5 | Adicionado |
.encryptionStatus(): Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Resultados | Object | <- | Informação sobre o cifrado do armazém de dados atual e de cada tabela |
Descrição
The .encryptionStatus()
function returns an object providing the encryption status for the current data file (i.e., the data file of the ds
datastore). Também se proporciona o estado de cada tabela.
Use the
Data file encryption status
command to determine the encryption status of any other data file.
Valor retornado
O objeto retornado contém as propriedades abaixo:
Propriedade | Tipo | Descrição | ||
---|---|---|---|---|
isEncrypted | Parâmetros | True se o arquivo de dados estiver criptografado | ||
keyProvided | Parâmetros | True se proporcionar a chave de encriptação que coincide com o arquivo de dados encriptados(*). | ||
tabelas | Object | Objeto que contém tantas propriedades como tabelas encriptadas ou codificadas. | ||
tableName | Object | Tabla encriptada ou cifrada | ||
name | Text | Nombre da tabela | ||
num | Number | Número de tabela | ||
isEncryptable | Parâmetros | Verdadero se a tabela estiver declarada como encriptada no arquivo de estrutura | ||
isEncrypted | Parâmetros | True se os registros da tabela estiverem encriptados no arquivo de dados |
(*) a chave de criptografia pode ser fornecida:
- with the
.provideDataKey()
command, - na raíz de um dispositivo conectado antes de abrir o datastore,
- with the
Discover data key
command.
Exemplo
Se quiser saber o número de tabelas criptografadas no arquivo de dados atual:
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()
História
Release | Mudanças |
---|---|
20 | Adicionado |
.flushAndLock()
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Não exige nenhum parâmetro |
Descrição
The .flushAndLock()
function flushes the cache of the local datastore and prevents other processes from performing write operations on the database. O datastore é definido para um estado consistente e congelado. É necessário chamar esta função antes de executar um instantâneo da aplicação, por exemplo.
Esta função só pode ser chamada:
- on the local datastore (
ds
). - no ambiente cliente/servidor, na máquina do 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.
O datastore é desbloqueado quando:
- 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), .
Exemplo
Se quiser criar uma cópia da pasta de dados juntamente com o seu arquivo de diário actual:
$destination:=Folder(fk documents folder).folder("Archive")
$destination.create()
ds.flushAndLock() //Bloqueia operações write de outros processos
$dataFolder:=Folder(fk data folder)
$dataFolder.copyTo($destination) //Copia a pasta de dados
$oldJournalPath:=New log file //Fecha o diário e cria um novo
$oldJournal:=File($oldJournalPath; fk platform path)
$oldJournal.moveTo($destination) //Salva o diário antigo com dados
ds.unlock() //Nossa cópia terminou, podemos desbloquear a datastore
Veja também
.getAllRemoteContexts()
História
Release | Mudanças |
---|---|
19 R5 | Adicionado |
.getAllRemoteContexts() : Collection
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Resultados | Collection | <- | Colecção de objectos de contexto de optimização |
Advanced mode: This function is intended for developers who need to customize ORDA default features for specific configurations. Na maioria dos casos, não necessitará de o utilizar.
Descrição
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.
Exemplo
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 exemplo serve como uma demonstração, não se destina a uma implementação real.
Veja também
.getRemoteContextInfo()
.setRemoteContextInfo()
.clearAllRemoteContexts()
.getGlobalStamp()
História
Release | Mudanças |
---|---|
20 R3 | Adicionado |
.getGlobalStamp() : Real
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Resultados | Real | <- | Valor atual do marcador de modificação global |
Descrição
The .getGlobalStamp()
function returns the current value of the global modification stamp of the datastore.
Esta função só pode ser chamada:
- on the local datastore (
ds
). - no ambiente cliente/servidor, na máquina do servidor.
For more information on global stamp and data change tracking, please refer to the Using the Global Stamp page.
Exemplo
var $currentStamp : Real
var $hasModifications : Boolean
$currentStamp:=ds.getGlobalStamp()
methodWhichCouldModifyEmployees //chamar algum código
$hasModifications:=($currentStamp # ds.getGlobalStamp())
Veja também
.getInfo()
História
Release | Mudanças |
---|---|
17 | Adicionado |
.getInfo(): Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Resultados | Object | <- | Propiedades de datastore |
Descrição
The .getInfo()
function returns an object providing information about the datastore. Esta função é útil para configurar o código genérico.
Returned object
Propriedade | Tipo | Descrição | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
type | string | ||||||||||||||||
networked | boolean | ||||||||||||||||
localID | text | ID do armazém de dados na máquina. Corresponds to the localId string given with the Open datastore command. String vazia ("") para o datastore principal. | |||||||||||||||
connection | object | Objeto descrevendo a conexão remota da datastore (não retornado para datastore principal) Propriedades disponiveis: Propriedades disponiveis: 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
Exemplo 1
var $info : Object
$info:=ds.getInfo() //Executado em 4D Server ou 4D
//{"type":"4D","networked":false,"localID":""}
$info:=ds.getInfo() // Executado em 4D remoto
//{"type":"4D","networked":true,"localID":""}
Exemplo 2
Em um armazém de dados 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()
História
Release | Mudanças |
---|---|
19 R5 | Adicionado |
.getRemoteContextInfo(contextName : Text) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
contextName | Text | -> | Nome do contexto |
Resultados | Object | <- | Descrição do contexto de optimização |
Advanced mode: This function is intended for developers who need to customize ORDA default features for specific configurations. Na maioria dos casos, não necessitará de o utilizar.
Descrição
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 devolvido
O objeto retornado tem as propriedades abaixo:
Propriedade | Tipo | Descrição |
---|---|---|
name | Text | Nome do contexto |
main | Text | Atributo(s) associado(s) ao contexto (os nomes dos atributos são separados por uma vírgula) |
dataclass | Text | Nome do dataclass |
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.
Exemplo
See the example from the .setRemoteContextInfo() section.
Veja também
.setRemoteContextInfo()
.getAllRemoteContexts()
.clearAllRemoteContexts()
.getRequestLog()
História
Release | Mudanças |
---|---|
17 R6 | Adicionado |
.getRequestLog() : Collection
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Resultados | Collection | <- | Coleção de objetos onde cada objeto descreve uma petição |
Descrição
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 função deve ser chamada em um 4D remoto, do contrário devolve uma coleção vazia. Foi criado para depuração em configurações de cliente/servidor.
Valor retornado
Coleção de objetos de petição empilhados. A petição mais recente tem indice 0.
For a description of the ORDA request log format, please refer to the ORDA client requests section.
Exemplo
See Example 2 of .startRequestLog()
.
.isAdminProtected()
História
Release | Mudanças |
---|---|
18 R6 | Adicionado |
.isAdminProtected() : Boolean
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Resultados | Parâmetros | <- | True se o acesso ao Explorador de Dados estiver desativado, False se estiver ativado (por padrão) |
Descrição
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).
Veja também
.locked()
História
Release | Mudanças |
---|---|
20 | Adicionado |
.locked() : Boolean
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Resultados | Parâmetros | <- | Verdadeiro se trancado |
Descrição
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()).
Veja também
.makeSelectionsAlterable()
História
Release | Mudanças |
---|---|
18 R5 | Adicionado |
.makeSelectionsAlterable()
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Não exige nenhum parâmetro |
Descrição
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()
História
Release | Mudanças |
---|---|
17 R5 | Adicionado |
.provideDataKey( curPassPhrase : Text ) : Object
.provideDataKey( curDataKey : Object ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
curPassPhrase | Text | -> | Frase de cifrado atual |
curDataKey | Object | -> | Chave de criptografia de dados atual |
Resultados | Object | <- | Resultado da coincidência da chave de criptografia |
Descrição
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 função pode ser utilizada ao abrir um banco de dados criptografado, ou ao executar qualquer operação de criptografia que precise da chave de criptografia, como por exemplo voltar a criptografar o arquivo de dados.
- 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. Quando usar este parâmetro, uma chave de criptografia é gerada.
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 as modificações de dados nas tabelas encriptadas são cifradas no disco (.4DD, .journal. 4Dindx)
- todos os dados carregados desde tabelas criptografadas são descifradas na memória
Resultado
O resultado da ordem se descreve no objeto devolvido:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | True se a chave da criptografia proporcionada coincide com os dados encriptados, False em caso contrário | |
Properties below are returned only if success is FALSE | |||
status | Number | Código de erro (4 se a chave de encriptação fornecida for errada) | |
statusText | Text | Mensagem de erro | |
errors | Collection | Pilha de erros. O primeiro erro tem o índice mais alto | |
[ ].componentSignature | Text | Nome do componente interno | |
[ ].errCode | Number | Número de erro | |
[ ].message | Text | Mensagem de erro |
If no curPassphrase or curDataKey is given, .provideDataKey()
returns null (no error is generated).
Exemplo
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()
História
Release | Mudanças |
---|---|
18 R6 | Adicionado |
.setAdminProtection( status : Boolean )
Parâmetro | Tipo | Descrição | |
---|---|---|---|
status | Parâmetros | -> | True to disable Data Explorer access to data on the webAdmin port, False (default) to grant access |
Descrição
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. Quando esta função for executada, o arquivo de dados é protegido imediatamente e o estado é armazenado no disco: o arquivo de dados é protegido mesmo se a aplicação for restaurada.
Exemplo
You create a protectDataFile project method to call before deployments for example:
ds.setAdminProtection(True) //Desativa o acesso aos dados do Explorador de Dados
Veja também
.setGlobalStamp()
História
Release | Mudanças |
---|---|
20 R3 | Adicionado |
.setGlobalStamp( newStamp : Real)
Parâmetro | Tipo | Descrição | |
---|---|---|---|
newStamp | Real | -> | Novo valor do marcador de modificação global |
Essa função é destinada a desenvolvedores que precisam modificar o valor atual do marcador global. Ele deve ser usado com cuidado.
Descrição
The .setGlobalStamp()
function sets newStamp as new value for the current global modification stamp for the datastore.
Esta função só pode ser chamada:
- on the local datastore (
ds
). - no ambiente cliente/servidor, na máquina do servidor.
For more information on global stamp and data change tracking, please refer to the Using the Global Stamp page.
Exemplo
O código a seguir define o carimbo global de modificação:
var $newValue: Real
$newValue:=ReadValueFrom //obtém um novo valor para atribuir
ds.setGlobalStamp($newValue)
Veja também
.setRemoteContextInfo()
História
Release | Mudanças |
---|---|
19 R5 | Adicionado |
.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âmetro | Tipo | Descrição | |
---|---|---|---|
contextName | Text | -> | Nome do contexto |
dataClassName | Text | -> | Nome da dataclass |
dataClassObject | 4D. DataClass | -> | dataclass object (e.g datastore. Employee) |
attributes | Text | -> | Lista de atributos separada por vírgulas |
Atributos do tipo BLOB não são gerenciados na datastore. | Collection | -> | Coleção de nomes de atributos (text) |
contextType | Text | -> | Se fornecido, o valor deve ser "main" ou "currentItem" |
pageLength | Integer | -> | Duração da página da selecção da entidade ligada ao contexto (por padrão é 80) |
Advanced mode: This function is intended for developers who need to customize ORDA default features for specific configurations. Na maioria dos casos, não necessitará de o utilizar.
Descrição
The .setRemoteContextInfo()
function links the specified dataclass attributes to the contextName optimization context. Se já existir um contexto de optimização para os atributos especificados, este comando substitui-o.
Quando se passa um contexto para as funções da classe ORDA, a optimização do pedido REST é desencadeada imediatamente:
- a primeira entidade não é carregada totalmente, como no 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. Se passar um atributo que não existir na dataclass, a função a ignora e um erro é enviado.
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.
- Se definido para "currentItem", os atributos passados são colocados no contexto do item 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).
Exemplo 1
var $ds : 4D. DataStoreImplementation
var $persons : cs. PersonsSelection
var $p : cs. PersonsEntity
var $contextA : Object
var $info : Object
var $text : Text
// Open remote datastore
$ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")
// Set context info
$contextA:=New object("context"; "contextA")
$ds.setRemoteContextInfo("contextA"; $ds. Persons; "firstname, lastname")
// Send requests to the server using a loop
$persons:=$ds. Persons.all($contextA)
$text:="" For each ($p; $persons)
$text:=$p.firstname + " " + $p.lastname End for each
// Check contents of the context
$info:=$ds.getRemoteContextInfo("contextA")
// $info = {name:"contextA";dataclass:"Persons";main:"firstname, lastname"}
Este exemplo serve como uma demonstração, não se destina a uma implementação real.
Exemplo 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)
Exemplo 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"
Veja também
.getRemoteContextInfo()
.getAllRemoteContexts()
.clearAllRemoteContexts()
.startRequestLog()
História
Release | Mudanças |
---|---|
20 | Server side support, new options parameter |
17 R6 | Adicionado |
.startRequestLog()
.startRequestLog( file : 4D.File )
.startRequestLog( file : 4D.File ; options : Integer )
.startRequestLog( reqNum : Integer )
Parâmetro | Tipo | Descrição | |
---|---|---|---|
file | 4D. File | -> | Objeto File |
options | Integer | -> | Opção de registo de resposta (apenas servidor) |
reqNum | Integer | -> | Número de pedidos a manter na memória (apenas cliente) |
Descrição
The .startRequestLog()
function starts the logging of ORDA requests on the client side or on the server side. Foi criado para depuração em configurações de cliente/servidor.
For a description of the ORDA request log format, please refer to the ORDA requests section.
Do lado do cliente
Para criar um registo de pedidos ORDA do lado do cliente, chame esta função numa máquina remota. O registro pode ser enviado para um arquivo ou para a memória, dependendo do 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 uma petição.
Se o arquivo não existir, será criado. No caso contrário, ou seja, se o arquivo já existir, os novos dados de registro serão adicionados a ele. If.startRequestLog()
is called with a file while a logging was previously started in memory, the memory log is stopped and emptied.
Deve adicionar manualmente um caractere \N ao final do arquivo para realizar uma validação 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.Se não tiver passado nenhum parâmetro, o registro se inicia na memória. 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.
Do lado do servidor
Para criar um registro de pedidos ORDA no lado do servidor, chame essa função no máquina servidor. The log data is written in a file in .jsonl
format. Cada objeto representa um pedido. Se o ficheiro ainda não existir, é criado. No caso contrário, ou seja, se o arquivo já existir, os novos dados de registro serão adicionados a ele.
- 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 padrão, quando o parâmetro é omisso, a resposta completa é registrada. As seguintes constantes podem ser utilizadas neste parâmetro:
|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|
Exemplo 1
Se quiser registras as petições dos clientes ORDA em um arquivo e usar o número de sequencia do 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)
Exemplo 2
Se quiser registrar as petições dos clientes ORDA na memória:
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")
Exemplo 3
Você deseja registrar as peticiones do servidor ORDA em um arquivo específico e ativar o número de sequência do registro e a duração:
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()
História
Release | Mudanças |
---|---|
18 | Adicionado |
.startTransaction()
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Não exige nenhum parâmetro |
Descrição
The .startTransaction()
function starts a transaction in the current process on the database matching the datastore to which it applies. Quaisquer alterações feitas às entidades do datastore no processo da transacção são armazenadas temporariamente até que a transacção seja validada ou cancelada.
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.
Pode aninhar várias transações (subtransações). Cada transação ou subtransação deve ser eventualmente cancelada ou 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.
Exemplo
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()
História
Release | Mudanças |
---|---|
20 | Suporte do lado do servidor |
17 R6 | Adicionado |
.stopRequestLog()
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Não exige nenhum parâmetro |
Descrição
The .stopRequestLog()
function stops any logging of ORDA requests on the machine it is called (client or server).
Fecha efetivamente o documento aberto no disco. No lado do cliente, se o registo tiver sido iniciado na memória, é interrompido.
Esta função não faz nada se o registo dos pedidos ORDA não tiver sido iniciado na máquina.
Exemplo
See examples for .startRequestLog()
.
.unlock()
História
Release | Mudanças |
---|---|
20 | Adicionado |
.unlock()
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Não exige nenhum parâmetro |
Descrição
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.
Se a fechadura actual era a única fechadura no datastore, as operações de escrita são imediatamente activadas. 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.
Veja também
.validateTransaction()
História
Release | Mudanças |
---|---|
18 | Adicionado |
.validateTransaction()
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Não exige nenhum parâmetro |
Descrição
The .validateTransaction()
function accepts the transaction that was started with .startTransaction()
at the corresponding level on the specified datastore.
A função salva as mudanças nos dados do datastore que se produziram durante a transação.
Pode aninhar várias transações (subtransações). Se a transação principal for cancelada, todas suas subtransações também são canceladas, mesmo se validadas individualmente usando esta função.
Exemplo
See example for .startTransaction()
.