Nova postagem

Pesquisar

Artigo
· Abr. 22 4min de leitura

Consideraciones al migrar de Oracle, MSSQL, etc. a IRIS

Migrar desde Oracle, MSSQL u otros sistemas de bases de datos puramente relacionales a un sistema multimodelo como InterSystems IRIS es una decisión estratégica que requiere una planificación y ejecución cuidadosas. Aunque esta transición ofrece beneficios significativos, como un mejor rendimiento, escalabilidad y soporte para arquitecturas modernas, también conlleva desafíos. En este artículo destacaré algunas de las consideraciones relacionadas con la codificación para asegurar una migración exitosa. Dejaré fuera del alcance de este artículo todo lo relacionado con la migración real de estructuras y datos.

Primero, cuando estáis considerando migrar a un sistema de base de datos diferente, necesitáis comprender vuestra lógica de negocio, ya sea del lado de la aplicación (servidor de aplicaciones) o del servidor de bases de datos. Básicamente, ¿dónde tenéis vuestras sentencias SQL que potencialmente tendréis que reescribir?

Cuando vuestra lógica de aplicación depende en gran medida de SQL ejecutado directamente dentro del código de la aplicación (en lugar de procedimientos almacenados o triggers en la base de datos), migrar desde una base de datos relacional a InterSystems IRIS requiere un examen cuidadoso de vuestras sentencias SQL. Veamos algunos de los factores más importantes que debéis tener en cuenta.

  1. Diferencias en el dialecto SQL. SQL de IRIS admite el estándar SQL-92. Esto no significa que no estén implementadas algunas funcionalidades más modernas. Simplemente significa que necesitáis comprobarlo de antemano. Por ejemplo, las funciones de ventana aparecieron en SQL:2003, pero aún así podéis escribirlas en IRIS.
--window function
select id, rating
  from (select a.id, 
               r.rating, 
               avg(r.rating) over () as avg_rating 
          from SQLUSER.Actor a join SQLUser.Review r on a.id = r.Reviews) as sub 
 where rating > avg_rating

Al mismo tiempo, los nuevos tipos de datos complejos, como XML, JSON, Arrays y tipos de datos geográficos, no están soportados. Así que la siguiente consulta:

SELECT a.id, 
       a.firstname, 
       ARRAY_AGG(r.rating) AS ratings 
  FROM SQLUSER.Actor a LEFT JOIN SQLUser.Review r ON a.id = r.Reviews 
GROUP BY  a.firstname

devolverá un error: ERROR #5540: SQLCODE: -359 Message: User defined SQL function 'SQLUSER.ARRAY_AGG' does not exist

Pero no es el fin del mundo. Hay muchas funciones integradas que os permitirán reescribir las consultas para obtener el resultado esperado.

2. Funciones integradas. Los distintos sistemas de gestión de bases de datos tienen diferentes funciones integradas. Por lo tanto, necesitáis comprender cómo se corresponden con las disponibles en IRIS. Aquí tenéis varios ejemplos de lo que os estoy comentando: funciones usadas en Oracle y sus equivalentes en IRIS.

Oracle IRIS
NVL ISNULL(field, default_value)
substr $extract(field, start_pos, end_pos)
instr $find(field, text_to_find)
concat {fn CONCAT(string1,string2)}

Cuando vuestra lógica SQL principal reside dentro de la base de datos (por ejemplo, procedimientos almacenados, triggers, vistas), migrar a InterSystems IRIS requiere un enfoque diferente. Aquí tenéis algunas consideraciones:

  1. Migración de objetos de base de datos
    1. Todos los procedimientos almacenados deben reescribirse usando ObjectScript. Esta también puede ser una buena oportunidad para cambiar al modelo orientado a objetos, ya que obtendréis una tabla igualmente al crear una clase. Sin embargo, trabajar con clases os permitirá escribir métodos (que pueden llamarse como procedimientos almacenados) y usar todo el potencial del paradigma orientado a objetos.
    2. Los triggers, índices y vistas están todos soportados por IRIS. Incluso podéis dejar las vistas tal como están si las columnas de las tablas se mantienen iguales y no utilizan funciones o sintaxis no soportadas (ved el punto anterior).
  2. La migración de definiciones también es importante y puede presentar algunos desafíos. Primero, debéis hacer una correspondencia cuidadosa de los tipos de datos de vuestra base de datos anterior con los de IRIS, especialmente si estáis usando tipos de datos complejos. Además, al tener más flexibilidad con los índices, quizás queráis redefinirlos de forma distinta.

Aquí tenéis algunas cosas que debéis considerar al decidir migrar a InterSystems IRIS desde otra base de datos relacional. Es una decisión estratégica que puede desbloquear beneficios significativos, incluyendo una mayor escalabilidad, rendimiento y eficiencia. Sin embargo, una planificación cuidadosa es crucial para asegurar una transición fluida y abordar necesidades de compatibilidad, transformación de datos y refactorización de la aplicación.

Discussão (0)1
Entre ou crie uma conta para continuar
Artigo
· Abr. 22 4min de leitura

Testing Metadata Inconsistencies in InterSystems IRIS Using the DATATYPE_SAMPLE Database

When using standard SQL or the object layer in InterSystems IRIS, metadata consistency is usually maintained through built-in validation and type enforcement. However, legacy systems that bypass these layers—directly accessing globals—can introduce subtle and serious inconsistencies.

Understanding how drivers behave in these edge cases is crucial for diagnosing legacy data issues and ensuring application reliability.

The DATATYPE_SAMPLE database is designed to help analyze error scenarios where column values do not conform to the data types or constraints defined in the metadata. The goal is to evaluate how InterSystems IRIS and its drivers (JDBC, ODBC, .NET) and different tools behave when such inconsistencies occur. In this post, I’ll focus on the JDBC driver.


What's the Problem?

Some legacy applications write directly to globals. If a relational model (created via CREATE TABLE or manually defined using a global mapping) is used to expose this data, the mapping defines the underlying values conform to the declared metadata for each column.

When this assumption is broken, different types of problems may occur:

  1. Access Failure: A value cannot be read at all, and an exception is thrown when the driver tries to access it.
  2. Silent Corruption: The value is read successfully but does not match the expected metadata.
  3. Undetected Mutation: The value is read and appears valid, but was silently altered by the driver to fit the metadata, making the inconsistency hard to detect.

Simulating the Behavior

To demonstrate these scenarios, I created the DATATYPE_SAMPLE database, available on the InterSystems Open Exchange:
🔗 Package page
🔗 GitHub repo

The table used for the demonstration:

CREATE TABLE SQLUser.Employee (
   ID              BIGINT          NOT NULL AUTO_INCREMENT,
   Age             INTEGER,
   Company         BIGINT,
   DOB             DATE,
   FavoriteColors  VARCHAR(4096),
   Name            VARCHAR(50)     NOT NULL,
   Notes           LONGVARCHAR,
   Picture         LONGVARBINARY,
   SSN             VARCHAR(50)     NOT NULL,
   Salary          INTEGER,
   Spouse          BIGINT,
   Title           VARCHAR(50),
   Home_City       VARCHAR(80),
   Home_State      VARCHAR(2),
   Home_Street     VARCHAR(80),
   Home_Zip        VARCHAR(5),
   Office_City     VARCHAR(80),
   Office_State    VARCHAR(2),
   Office_Street   VARCHAR(80),
   Office_Zip      VARCHAR(5)
);

Example 1: Access Failure

To simulate an inconsistency, I injected invalid values into the DOB (Date of Birth\Datatype DATE) column using direct global access. Specifically, the rows with primary keys 101, 180, 181, 182, 183, 184, and 185 were populated with values that do not represent valid dates.

The values looks like this now:
 
As you can see, a string was appended to the end of a $H (Horolog) value. According to the table's metadata, this column is expected to contain a date—but the stored value clearly isn't one.

So what happens when you try to read this data? Well, it depends on the tool you're using. I tested a few different tools to compare how they handle this kind of inconsistency.

1) SquirrelSQL (SQuirreL SQL Client Home Page)

When SquirrelSQL attempts to access the data, an error occurs. It tries to read all rows and columns, and any cell that contains invalid data is simply marked as "ERROR". Unfortunately, I couldn't find any additional details or error messages explaining the cause.

  

2) SQLWorkbench/J (SQL Workbench/J -  Home)
SQL Workbench/J stops processing the result set as soon as it encounters the first invalid cell. It displays an error message like "Invalid date", but unfortunately, it doesn't provide any information about which row caused the issue.

 
3) DBVisualizer (dbvis) &  DBeaver (dbeaver)

DBVisualizer and DBeaver behave similarly. Both tools continue reading the result set and provide detailed error messages for each affected cell. This makes it easy to identify the corresponding row that caused the issue.

   

4) SQL DATA LENS (SQL Data Lens - a powerful tool for InterSystems IRIS and Caché)

With the latest release of SQL DATA LENS, you get detailed information about the error, the affected row, and the actual database value. As shown in the screenshot, the internal value for the first row in columns DOB is "39146<Ruined>", which cannot be cast to a valid DATE.

SQL DATA LENS also allows you to configure whether result processing should stop at the first erroneous cell or continue reading to retrieve all available data.
 


The next part of this article will shows details about:

Silent Corruption: The value is read successfully but does not match the expected metadata.

Undetected Mutation: The value is read and appears valid, but was silently altered by the driver to fit the metadata, making the inconsistency hard to detect.



Andreas

Discussão (0)2
Entre ou crie uma conta para continuar
Anúncio
· Abr. 22

Programa de Acceso Anticipado: mejoras en OAuth2

InterSystems IRIS 2025.2.0 introduce varias funcionalidades para mejorar la experiencia de configuración de OAuth2.

- OAuth2 es ahora un tipo de autenticación nativo y puede activarse fácilmente para vuestros servicios y aplicaciones web. Anteriormente, OAuth2 era un tipo de autenticación delegada.

- Ahora podéis crear servidores de recursos con la nueva clase OAuth2.ResourceServer, lo que simplifica considerablemente la configuración. Antes, los servidores de recursos eran instancias de OAuth2.Client.

- La clase OAuth2.ResourceServer proporciona un autenticador de ejemplo para determinar los permisos de usuario que, en configuraciones simples, no requiere código personalizado (anteriormente se necesitaba una implementación personalizada de ZAUTHENTICATE). Este autenticador sencillo se puede extender y personalizar según vuestras necesidades. OAuth2.ResourceServer admite múltiples audiencias.

- Ahora podéis usar JDBC y ODBC para autenticaros en InterSystems IRIS con tokens de acceso.

Nos interesa conocer vuestra opinión sobre estos nuevos cambios y si funcionan como esperáis.

Podéis descargar el software y la nueva documentación de estas funcionalidades usando este Linkhttps://evaluation.intersystems.com/Eval/early-access/OAuth2

Para enviar comentarios, usad la página del EAP y haced clic en el botón de feedback en la parte derecha.

Discussão (0)1
Entre ou crie uma conta para continuar
Artigo
· Abr. 22 5min de leitura

ADO.NET Managed Provider を使用してクラスクエリを実行し、結果セットを取得するサンプル

先日、お客様よりタイトルのご質問をいただき、サンプルコードを作成しました。せっかくですので、こちらでも共有したいと思います。

今回は、データベースの空き容量情報を取得する、%SYS.DatabaseQueryクラスのFreeSpaceクエリを使用したサンプルとします。

C#.Net と VB.Net で作成してみました。


★C#.Net

using System;
using InterSystems.Data.IRISClient;
{
    class Program
    {
        static void Main(string[] args)
        {
            IRISConnection IRISConnect = new IRISConnection();
            IRISConnect.ConnectionString = "Server=localhost;Port=1972;Namespace=USER;User ID=_SYSTEM;Password=SYS";
            IRISConnect.Open();
            String queryString = "select * from %SYS.DatabaseQuery_FreeSpace(?)";  // call %SYS.DatabaseQuery_FreeSpace(?) でもOK
            IRISCommand cmd = new IRISCommand(queryString, IRISConnect);
            IRISParameter p1 = new IRISParameter("Mask", IRISDbType.NVarChar);
            p1.Value = "*";
            cmd.Parameters.Add(p1);
            IRISDataReader Reader = cmd.ExecuteReader();
            while (Reader.Read())
            {
                // Select values : DatabaseName:0, Directory:1, MaxSize:2, Size:3, ExpansionSize:4, Available:5, %Free:6, DiskFreeSpace:7, Status:8, SizeInt:9, AvailableNum:10, DiskFreeSpaceNum:11, ReadOnly:12
                Console.WriteLine(Reader.GetValue(0).ToString() + ", " + Reader.GetValue(3).ToString() + ", " + Reader.GetValue(5).ToString());
            }
            Reader.Close();
            cmd.Dispose();
            IRISConnect.Close(); 
        }
    }
}


★VB.Net

Imports System
Imports InterSystems.Data.IRISClient

Module Program
    Sub Main(args As String())
        Dim conn As New IRISConnection
        conn.ConnectionString = "Server=localhost;Port=1972;Namespace=USER;User ID=_SYSTEM;Password=SYS"
        conn.Open() 
        Dim queryString As String = "select * from %SYS.DatabaseQuery_FreeSpace(?)"   ''call %SYS.DatabaseQuery_FreeSpace(?) でもOK
        Dim cmd As IRISCommand = New IRISCommand(queryString, conn)
        Dim p1 As IRISParameter = New IRISParameter("Mask", "*")
        cmd.Parameters.Add(p1)
        Dim reader As IRISDataReader = cmd.ExecuteReader()
        Do While (reader.Read())
            '' Select values : DatabaseName : 0, Directory:1, MaxSize:2, Size:3, ExpansionSize:4, Available:5, %Free:6, DiskFreeSpace:7, Status:8, SizeInt:9, AvailableNum:10, DiskFreeSpaceNum:11, ReadOnly:12
            Console.WriteLine(reader.GetValue(0).ToString() + ", " + reader.GetValue(3).ToString() + ", " + reader.GetValue(5).ToString())
        Loop 
        reader.Close()
        cmd.Dispose()
        conn.Close()
    End Sub
End Module


※参照の追加手順

Visual Studioの [プロジェクト] > [プロジェクト参照の追加] をクリックします
参照マネージャにて、参照より以下を追加します(.Netのバージョンにあわせて選択してください)
例)C:\InterSystems\IRIS\dev\dotnet\bin\net8.0\InterSystems.Data.IRISClient.dll


なお、ストアドプロシージャ(ストアド)の場合も、同様に実行することが可能です。

ともに、 SqlProc キーワードを指定して、SQL ストアドプロシージャとして呼び出すことができるようにする必要があります。

例(クラスクエリのサンプル):select * from Sample.SP_Sample_By_Name(?)  または  call Sample.SP_Sample_By_Name(?)

Query ByName(name As %String = "") As %SQLQuery(CONTAINID = 1, SELECTMODE = "RUNTIME") [ SqlName = SP_Sample_By_Name, SqlProc ]
{
SELECT ID, Name, DOB, SSN
FROM Sample.Person
WHERE (Name %STARTSWITH :name)
ORDER BY Name
}


例2(ストアドプロシージャのサンプル):call Sample.Stored_Procedure_Test(?,?)

ClassMethod StoredProcTest(name As %String, ByRef response As %String) As %Integer [ SqlName = Stored_Procedure_Test, SqlProc ]
{
    // Set response to the concatenation of name.
    Set response = name _ "||" _ name
    QUIT 29
}

例2 の場合は以下のような C# コードになります(一部省略)

   String queryString = "? = call Sample.Stored_Procedure_Test(?,?)";
   IRISCommand cmd = new IRISCommand(queryString, IRISConnect);
   IRISParameter p1 = new IRISParameter();
   p1.Direction = ParameterDirection.ReturnValue;
   p1.IRISDbType = IRISDbType.Int;
   IRISParameter p2 = new IRISParameter();
   p2.Direction = ParameterDirection.Input;
   p2.Value = "InterSystemsJapan";
   IRISParameter p3 = new IRISParameter();
   p3.Direction = ParameterDirection.Output;
   cmd.Parameters.Add(p1);
   cmd.Parameters.Add(p2);
   cmd.Parameters.Add(p3);
             
   cmd.ExecuteReader();
   Console.WriteLine("Return value = " + p1.Value + ", " + "ByRef response = " + p3.Value);


ご利用の機会がありましたら、ぜひ参考になさってください。

以下のドキュメントもあわせてご覧ください。
ADO.NET Managed Provider の使用法
InterSystems IRIS デモ : ADO.NET を使用した接続

Discussão (0)0
Entre ou crie uma conta para continuar
Resumo
· Abr. 22

Your Invitation to Code Your Way to InterSystems READY 2025

Dear Developer Community member,

We’re excited to invite you to our global developer initiative:

🎯 Code Your Way to InterSystems READY 2025

Task: Upload your side project based on InterSystems IRIS, tell us your story, and you could win a pass to InterSystems READY 2025 and a hotel accommodation!

Duration: April 21 - May 04, 2025

Prizes: hotel accommodation and free passes to the InterSystems READY 2025!

How to enter:

  1. Upload a fun IRIS-based side project to Open Exchange. Be creative - it can be useful, quirky, fun, or just something you’ve always wanted to try.
  2. Record a short inspirational video (up to 5 minutes):
    • Tell us how InterSystems technologies or the Developer Community impacted your project or career.
    • Explain why YOU should get a ticket to the InterSystems READY 2025.
  3. Submit your video and a link to your app via this form.

>> Full details here

Let’s celebrate creativity and community. Show us what you’ve got!