Nova postagem

Pesquisar

Artigo
· jan 26 8min de leitura

Pyhon Embutido no InterSystems IRIS Parte - 2

No artigo anterior. Práticas de membros de classe e sua execução dentro do Python embutido. Agora voltaremos nossa atenção para o processo de alternância de espaços de nomes, acesso a variáveis globais, travessia e execução de rotinas dentro do Python embutido.

Antes de prosseguir para as outras funções. vamos revisar brevemente a função executedentro do pacote iris. Esta função é excepcionalmente benéfica para executar funções ObjectScript arbitrárias e invocação de classe.

>>> b = iris.execute('return $Piece("test^aaaa","^",2)')
>>> b
'aaaa'
>>> b = iris.execute('return $Extract("123456",2,5)')
>>> b
'2345'
>>> b = iris.execute('return $Length(123456)')
>>> iris.execute('write ##Class(%SYSTEM.SYS).NameSpace()')
LEARNING>>>
>>> b = iris.execute('return ##Class(%SYSTEM.SYS).NameSpace()')
>>> b
'LEARNING'

 

Vamos começar!

4. Mudar Namespaces

A troca de espaços de nomes durante a execução é frequentemente necessária. No entanto, diferentemente do IRIS, a troca direta de espaços de nomes dentro do Python embutido não é viável. Portanto, é essencial utilizar definições de classe existentes ou criar um método wrapper para facilitar a troca de namespaces.

ClassMethod SwitchNM() [ Language = python ]
{
    import iris
    print(iris.cls('%SYSTEM.SYS').NameSpace())
    print(iris.system.Process.SetNamespace("USER"))
    try:
        iris.cls('User.EmbeddedPython').pyGetTemplateString()
    except RuntimeError as e:
        print("Wrong NameSpace",e)
}

 

5. Global

Para utilizar as capacidades de global para travessia de dados ou para recuperar informações de sistemas globais legados diretamente, em vez de usar SQL ou objetos dentro do Python embutido, é possível acessá-lo diretamente empregando a função gref do pacote iris. Para definir ou obter valores globais, a função gref pode ser utilizada para estabelecer uma referência à variável global e atribuir valores diretamente dentro do Python.

 
iris.gref

5.1 Definir valores de global

ClassMethod SetGlobal() [ Language = python ]
{
import iris
#create a global reference
g = iris.gref('^mygbl') 
g[1],g[2]='Mon','Tue'
g["95752455",1]=iris.execute('return $LFS("Ashok,55720,9639639639,test@gmail.com",",")')
g["85752400",1]=iris.execute('return $LB("Test","9517539635","t@gmail.com")')
g["test","c1"]=iris.execute('return ##Class(MyLearn.EmbeddedPython).executeAndGetResult()') # method wil return some listbuild values
# declare values by using set function
g.set([3],'Wed')
g.set([3,1,1],'Test multilevel')
}

5.2 Buscar valores de global

 Obtenha os valores globais do Python diretamente usando os subscritos ou o método get.

ClassMethod GetGlobal() [ Language = python ]
{
    import iris
    #gets a global reference
    g = iris.gref('^mybgl') 
    # get values
    print(g[3,1,1])
    print(g.get([2,1]))
    print(g["95752455",1])
}

5.3 Travessia

order - Travessia do global é essencial para coletar múltiplos níveis de dados do global. Esta função order do Python embutido funciona de forma semelhante ao comando $Order, utilizando a função order do iris.gref. Inicialmente, é necessário estabelecer uma referência à entidade global que requer travessia.

Travessia de nível de subscrito único

ClassMethod DollarOrder() [ Language = python ]
{
    import iris
    g = iris.gref('^MyLearn.EmbeddedPythonD') # I use my persistent class global
    key = ''
    while True:
        key = g.order([key])
        if key == None:
            break
        print(f'{key} {g.get([key])}')
}

Percurso em níveis com múltiplos índices

 
global
ClassMethod DollarOrderMultiLevel() [ Language = python ]
{
 import iris
 g = iris.gref('^mygbl')
 key1= ''
 while True:
 	key1 = g.order([key1])
 	if key1== None:
 		break
 	key2 = ''
 	while True:
 		key2 = g.order([key1,key2])
 		if key2 == None:
 			break
 		value = g.get([key1,key2])
 		print(key1,key2,value)
}

query - Função de consulta a partir do iris.gref semelhante a$query. sta função coleta todos os valores globais em tuplas. O resultado da tupla contém os IDs em uma lista e os valores na próxima tupla. Você pode consultar o exemplo de tupla abaixo.

 
tuple
ClassMethod DollarQuery() [ Language = python ]
{
 	import iris
 	g = iris.gref('^mygbl')
 	key = g.query()#this will return tuples of all the subscripts
 	for x in key:
 		print(x) # output (['3', '1', '1'], 'Test multilevel')
}

data - Esta funçãodata verifica se o subscrito fornecido existe no escopo global e retorna os valores de $data usando a própria função de dados.

ClassMethod DollarData() [ Language = python ]
{
    import iris
    g = iris.gref('^mygbl')
    key1= ''
    print(g.data([1]))
}

 

6. Rotinas

Além disso, é essencial implementar os membros da classe. Devemos executar as rotinas como parte da implementação para sistemas com base de código legado e outras situações relacionadas. Consequentemente, existe uma função dedicada dentro do pacote da biblioteca iris que permite a invocação de rotinas a partir do Python embutido através do uso da função routine.

 
myirispython.mac
ClassMethod RunRoutines() [ Language = python ]
{
    import iris
    iris.routine('^myirispython')
    iris.routine('add^myirispython',1,2) # same as write $$add^myirispython(1,2)
}

Além disso, você também pode executar a rotina usando a função execute. iris.execute('do ^myirispython')

note: If the routine is not found 
>>> iris.routine('^myirispythonT')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
RuntimeError: Routine not found

Continuaremos os outros tópicos no próximo artigo.

Discussão (0)1
Entre ou crie uma conta para continuar
Artigo
· jan 25 2min de leitura

第七章 C - D 开头的术语

第七章 C - D 开头的术语

当前设备 (current device)

系统

处理 I/O 命令的设备。当你登录时,当前设备是你的主设备,通常是你登录时使用的终端或个人计算机。

当前目录 (current directory)

通用

你当前工作的目录。

基于游标的 SQL (cursor-based SQL)

SQL

一种嵌入式 SQL 查询类型,打开一个游标来处理查询。当你的应用程序需要访问多行数据时,必须使用游标。游标像一个指针——它专注于访问和处理一行数据,然后移动到序列中的下一行。

游标 (cursor)

SQL

在多行数据中向前移动的迭代器。

自定义存储 (custom storage)

对象(Objects)

Discussão (0)1
Entre ou crie uma conta para continuar
Resumo
· jan 25

Join the InterSystems Technical Article Contest

Dear member of the Developer Community!

We'd like to invite you to participate in our latest article writing contest:

✍️ InterSystems Technical Article Contest ✍️

Duration: February 3rd - March 2nd, 2025

🎁 Gifts for everyone + main prizes!

🔍 What’s the challenge? Write an article on any topic related to the InterSystems products and services.

>> Full details here

Get ready to shine and inspire others with your tech skills! We can't wait to see what you come up with. ✨

Pergunta
· jan 24

Connect to iris from Visual Studio

I am a volunteer at a nonprofit that is attempting to connect to a product that uses InterSystems Cache (Clinisys LIMS). I have not used this database before, but I have used many others (MS-SQL, Oracle, etc.). I am hoping IRIS is compatible enough with Cache for this project. 

I downloaded IRIS. I learned about Terminal [IRIS]. Using it I was able to create a new table, insert data, and retrieve it. I also used the Management Portal to query the new table. It also returned the data.

Next I attempted to connect with Visual Studio (MS VS 2022 Profesional). I downloaded the InterSystems.Data.IRISClient through NuGet. It was published 1/22/2025. It has only 21 downloads. (Quite strange!) 

I am using this C# code:

   var IRISConnect = new IRISADOConnection();
   IRISConnect.ConnectionString = cs.CreateCs();
   IRISConnect.Open();

I have tried many connection strings. This one seems the most promising:

var IRISConnect = new IRISADOConnection(host: "localhost", port: "1972", nsp: "USER", username: "username1234", password: "abcd1234");
IRISConnect.Open();

String queryString = "SELECT * FROM Test.Employee";
IRISCommand cmd4 = new IRISCommand(queryString, IRISConnect);
IRISDataReader Reader = cmd4.ExecuteReader();
while (Reader.Read())
    Console.WriteLine(Reader.GetValue(0).ToString());

Reader.Close();
cmd4.Dispose();
IRISConnect.Close();

The error occurs on the line, IRISConnect.Open(). It read, "IRIS Security Error". 

I am able to login to both the terminal and management portal with the username and password. The namespace "USER" appears in the management portal, so I believe it is okay as well. The port is listed under the "iris all" terminal command.

The SuperUser roles are "%All" in the Management Portal: System > Security Management > Users > Edit User - (security settings): Roles tab: Role Name.

The "Last Reason for Failing to Login" is "ERROR #5002: ObjectScript error: &lt;READ&gt;Logon+118^%SYS.DBSRV.1". 

How can I login to IRIS with .NET?

 

References: 

1) https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls...

2) https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls...

3) https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls...

4 Comments
Discussão (4)2
Entre ou crie uma conta para continuar
Artigo
· jan 24 2min de leitura

第六章 C 开头的术语

第六章 C 开头的术语

计算机名称 (computer name)

系统

分配给一个处理器、其外围设备及所有相关数据集的名称。这个名称在整个网络中必须唯一。另见系统名称。

并发模式 (concurrency mode)

对象(Objects

并发模式决定在打开和保存对象时执行何种类型的锁定。IRIS 支持五种并发模式(0-4),允许你指定不锁定、原子锁定、共享锁定、共享保留锁定和独占锁定。

并发 (concurrency)

对象(Objects)

并发通过锁定机制控制数据完整性。IRIS 支持五种并发模式,从不锁定到在对象加载到内存直到保存期间持有独占锁。默认情况下,IRIS 对所有对象使用原子锁定。

并发备份 (concurrent backup)

系统

Discussão (0)1
Entre ou crie uma conta para continuar