When I worked on the hospital's information-system assessment, its hospital information system (HIS) data had already been synchronized into the platform's TiDB database. The assessment documents still used Caché SQL for the source system. I remember the migration of those reporting queries to the synchronized database had already been delayed for at least several years. Colleagues in the hospital data center said they didn't know how the tables related. They had to ask the HIS supplier, Donghua, to send an engineer to explain the relationships and guide them through rewriting the queries.
While looking into Donghua's system, I read a Beijing Friendship Hospital case study. The hospital used Donghua's iMedical and worked with Donghua to agree on how to exchange encounter information using FHIR.1 My pathology statistics also needed encounter data, but what I had was business tables in TiDB. To tell which pathology requests originated in outpatient or emergency care, I first needed to know which encounter a medical order belonged to.
I thought we could start by investigating ourselves. If existing queries could follow a field to another table, I wanted to discover where Caché defined that relationship, then verify the corresponding tables and columns in the synchronized database and rewrite the queries in TiDB SQL using the original reporting definitions.
One expression in the outpatient and emergency pathology calculation was OEORD_Adm_DR->PAADM_Type. I asked Cursor how to rewrite it, and its join introduced a table called PA_Adm. My follow-up question was: the original query never mentioned that table. How did you know?
Three names matter: the field storing a reference in the current record, the table to which it points, and the field you want to read there. The expression names only the first and third. A two-table example shows how to discover the missing middle.
Which table does the arrow leave implicit?
Suppose a request belongs to an encounter. Open the request class, Demo.Request.cls, and you'll see a property named Encounter:
Class Demo.Request Extends %Persistent
{
Property Encounter As Demo.Visit;
}
As Demo.Visit names the encounter class. Open Demo.Visit.cls to find Kind, representing encounter type:
Class Demo.Visit Extends %Persistent
{
Property Kind As %String;
}
In the SQL tables corresponding to these classes, the request's Encounter column stores the encounter record's ID, and the encounter's Kind stores its type. Caché SQL lets you write:2
SELECT r.ID, r.Encounter->Kind AS VisitKind
FROM Demo.Request r
Starting from a request, read its Encounter, look up the corresponding encounter, then retrieve that row's Kind. Why look up Visit? The property declares As Demo.Visit. Its own name can perfectly well be Encounter. Suppose the synchronized TiDB tables are called request_copy and visit_copy, with the encounter ID in the latter's id column. The same lookup expands to:
SELECT r.id, v.kind AS VisitKind
FROM request_copy AS r
LEFT JOIN visit_copy AS v ON v.id = r.encounter
There are two mappings. The source class definition tells you which kind of object Encounter references. The synchronized schema tells you where that object is stored and which column preserves its original ID. Even if both databases happen to use the same table name, check both fields in the join condition.
Why start with LEFT JOIN? When can INNER JOIN work?
InterSystems is explicit: “Arrow syntax performs a left outer join.”2 Suppose encounter 7 has type O and two requests should appear in a detailed report:
| Request ID | Encounter ID in request | Encounter type with LEFT JOIN | Encounter type with INNER JOIN |
|---|---|---|---|
| 101 | 7 | O | O |
| 102 | NULL | Request retained, type NULL | Entire row disappears |
If the report asks how many requests came from outpatient or emergency care, the situation changes. A post-join WHERE v.kind IN ('O', 'E') filters out 102: its null encounter type cannot satisfy the condition. Both joins count one request in this query. Move the same condition to the ON of the LEFT JOIN and request 102 remains, so COUNT(*) returns two. Whether you can simplify to an inner join depends on how the whole query handles unmatched rows.3
What is a Caché .cls file, and how do you read it?
A .cls file contains a Caché class definition. Start with the first line of the sample request class: Class Demo.Request Extends %Persistent. The class is Demo.Request; Extends %Persistent gives it inherited capabilities for saving and retrieving objects. In its body, Property Encounter As Demo.Visit; names the request property Encounter and identifies its referenced encounter class after As. For understanding an SQL arrow, these two lines already show where to begin and which class to read next.45
I also asked what Extends %RegisteredObject in a class header means. An ordinary class inheriting directly from it can define properties and methods. Calling %New() returns an OREF, a reference to the instance in memory. The reference alone doesn't imply a corresponding database row. To trace a class to a table, I'd follow its Extends hierarchy. If there's an intervening business class, continue upward to see whether it inherits persistence from %Persistent.65
When I'd read Java business classes, seeing a property's type made me think about what application code could do with it. I no longer remember exactly which classes housed business methods in the source system. Caché persistent classes can define both methods and properties, and Caché executes server-side ObjectScript methods.47 For our request class, application code can read the encounter type via request.Encounter.Kind. What was new to me was that Caché also projects this class to an SQL table when compiled. The same Encounter property can be written as r.Encounter->Kind in a report.52
Modeling with SQL CREATE TABLE starts on the table side: declare the columns and use FOREIGN KEY to specify which table's key a column references. Here I wrote Property Encounter As Demo.Visit; on the class side. Business code knows which object type it points to, and the database knows where the reference leads. Caché supports both entry points. Creating a table with CREATE TABLE automatically creates its corresponding persistent class.8
I remember this set of source queries using arrows, and the code repository containing the original .cls definitions. I once asked an authorized engineer to check for me. One look identified the table name. I don't remember exactly which field I asked him to search for. I suspect realizing that business-class source could explain relationships used by reports led me to search on June 10 for “where are Caché database cls definition files stored?” I opened gy_jerry's Caché Database Study Notes (2) and a Zhihu article on basic Caché development and debugging.910
Gy_jerry listed two options in Studio's New dialog:9
cache class definition(.cls)
cache objectScript routine(.mac/.int)
The first creates a class. After entering the package and class name, the corresponding Package.Class.cls appears in the project. He also gave this property declaration:9
Property RevisionInfo As Cm.RevisionInfo;
The names differ only by a package, but play separate roles. Look for property RevisionInfo in the current class. To inspect its type's fields, open the Cm.RevisionInfo class named after As.
By then I already had explicit joins locally for comparison. An orders query saved May 28 contained OE_Order.OEORD_Adm_DR = PA_Adm.PAADM_RowID. On June 6 I wrote this join in the outpatient and emergency pathology query too. On June 9 I was still asking why another join used the target table's row ID.
If all you have is the synchronized database, tables and column lists can narrow the search. I scripted lookups for candidate tables by field name in table.json, then rewrote queries individually. Finding PAADM_Type in a table only establishes that the column exists. To write an ON condition, you must also discover which right-side key matches the reference value on the left. Asking AI for a plausible class declaration can illustrate the notation. Verify the actual relationship against the business database.
Where do I add a column, and where do I change a business method?
A method's declaration and calls tell you which file holds the work. For instance, gy_jerry's patient plan example defines ClassMethod SetData in the .cls file, but the body calls $$SetData^Ps.Plan(...). The code that opens or creates a plan, fills its properties, and saves the object lives in the Ps.Plan.mac routine.9
Inheritance is another way to organize it. The diagram extends the request and encounter example with a request subclass responsible for review. Hollow triangles point to parent classes. Follow the arrow labeled Encounter to navigate from a request to an encounter.
classDiagram
direction LR
ReviewRequest --|> Request : 继承
Request --> Visit : Encounter
class ReviewRequest {
Review()
}
class Visit {
Kind
}
To change a review rule, edit the review method of Demo.ReviewRequest and recompile that subclass. To add a “review note” column to every request, add this line to the body of the parent Demo.Request.cls:
Property ReviewNote As %String;
Save and compile this persistent class in the namespace of the business database and recompile affected subclasses according to dependencies. Once compilation succeeds, SELECT ReviewNote FROM Demo.Request can read the new column. The class compiler handles the path from class change to table change without a separate ALTER TABLE ADD COLUMN.45
Caché 2018.1 also supports ALTER TABLE. Handwritten persistent classes default to maintenance through class source. If the declaration explicitly enables [ DdlAllowed ], appropriately privileged users can also alter the table with SQL. Classes created using CREATE TABLE enable this by default. Our sample Demo.Request does not declare that keyword, so add the review note by editing and compiling the .cls.1112
Tracing a query to its class definitions and related tables
Take the outpatient and emergency pathology query. Retain its original FROM and the condition being traced to see the starting table:
SELECT COUNT(1) FROM DHC_AppPisArc a, DHC_AppPisMaster b
WHERE a.AP_ParRef_Dr = b.AP_RowID
AND a.AP_OrdItem->OEORI_OEORD_ParRef->OEORD_Adm_DR->PAADM_Type IN ('O', 'E')
a is the alias of DHC_AppPisArc, the pathology request detail table. Follow its AP_OrdItem along the first line to OEORI_RowID on OE_OrdItem to write the first join condition. Then look at OEORI_OEORD_ParRef in that same table. The second line starts there.
I drew the diagram from the saved pathology query. Each line connects fields whose values must match in the JOIN. FK marks a reference that acts as a foreign key in the query. Check table definitions to see whether the database declares a foreign key constraint. The last line ends at PAADM_RowID on PA_Adm. The query filters encounter rows by PAADM_Type IN ('O', 'E') on that same row.
In Caché Studio, switch to the business database namespace. Open Find in Files and limit file types to *.cls. Double-click a result to open its class definition. Watch three locations: SqlFieldName is the column name visible to reports, the reference property's As identifies the target class, and the target class header can use SqlTableName to specify its projected SQL table. If no SQL name is explicit, check the default mapping. Studio's Class Inspector also shows these keywords.1314
The following class definitions are illustrative. Table and field names with underscores come from the saved query. In practice, open the classes your search actually matched.
Step one: find which table the request detail references. Start with the simplest spelling of the chain. Suppose the source retains the class and property names. The first segment is a.APOrdItem->… in SQL. Searching Studio for Property APOrdItem might immediately turn up this line in the request detail class:
Property APOrdItem As User.OrderItem;
As User.OrderItem tells you to open User.OrderItem.cls to follow the second arrow. This example uses default SQL projection: the User package maps to schema SQLUser, and the class name OrderItem doubles as the table name. The full name is SQLUser.OrderItem.5
The actual original query spells the column AP_OrdItem. Caché class and property names cannot contain underscores, but SQL column names can. Search Studio for the exact AP_OrdItem, underscore and all, and inspect the matching property declaration.14 In the class projecting to DHC_AppPisArc, it might look like this:
Class User.PathologyLine Extends %Persistent [ SqlTableName = DHC_AppPisArc ]
{
Property OrderItem As User.OrderItem [ SqlFieldName = AP_OrdItem ];
}
Read As User.OrderItem and open User.OrderItem.cls. Finding SqlTableName = OE_OrdItem in its class header, shown next, identifies the first related table as OE_OrdItem.
Step two: search the newly opened class for OEORI_OEORD_ParRef. This was the name to the right of the first arrow in the original query. It now becomes the reference field for the next step:
Class User.OrderItem Extends %Persistent [ SqlTableName = OE_OrdItem ]
{
Property ParentOrder As User.OrderHeader [ SqlFieldName = OEORI_OEORD_ParRef ];
}
The property type is User.OrderHeader. Open User.OrderHeader.cls and read the second related table name, OE_Order, from its header.
Step three: search the order class for OEORD_Adm_DR. This answers my original question: when the query doesn't mention PA_Adm, how do we know to go there?
Class User.OrderHeader Extends %Persistent [ SqlTableName = OE_Order ]
{
Property Admission As User.Admission [ SqlFieldName = OEORD_Adm_DR ];
}
As User.Admission tells me to open User.Admission.cls. Two things in this file matter:
Class User.Admission Extends %Persistent [ SqlTableName = PA_Adm ]
{
Property VisitType As %String [ SqlFieldName = PAADM_Type ];
}
First, SqlTableName = PA_Adm in the header supplies the third related table. Second, the property found by searching the current class for PAADM_Type provides the encounter type passed to IN ('O', 'E'). The chain is complete. Searching the whole namespace for PAADM_Type might have revealed the table quickly, but tracing from the left also explains which order links this particular request to the encounter.
Finally, match table names to join keys. As identifies the class a reference points to. To write ON in TiDB, you must also know which synchronized column holds the target object ID. The three steps in my saved pathology query used OEORI_RowID, OEORD_RowID, and PAADM_RowID respectively. Omitting synchronized table prefixes and unrelated conditions, that path looks like this:
SELECT COUNT(*)
FROM DHC_AppPisArc AS a
JOIN OE_OrdItem AS item ON item.OEORI_RowID = a.AP_OrdItem
JOIN OE_Order AS ord ON ord.OEORD_RowID = item.OEORI_OEORD_ParRef
JOIN PA_Adm AS adm ON adm.PAADM_RowID = ord.OEORD_Adm_DR
WHERE adm.PAADM_Type IN ('O', 'E')
OEORD_Adm_DR is the order field pointing to the encounter. The final join matches it against PA_Adm.PAADM_RowID, after which PAADM_Type filters for outpatient and emergency encounters. A missing match anywhere in the chain means the last type cannot satisfy the condition, which explains why this rewrite could use inner joins. To verify the reporting definition, I'd choose one record with a complete chain and one missing an intermediate reference, checking which should count. Also establish that target keys are unique in the synchronized tables. If a key matches two rows, COUNT(*) counts the same request twice.
Can we look up all reference fields and their target tables at once?
With a whole batch of reports, searching Studio afresh for every arrow invites looking up the same fields repeatedly. I asked DeepSeek if we could list persistent classes and properties, then identify the fields acting as foreign keys and their target tables. I also asked about fetching a sample row for each class. A sample shows what values the reference column contains, but an ID in an order alone cannot tell you its target table.
The source database exposes Caché's class dictionary, a catalog of compiled class and property definitions. ClassType on %Dictionary.CompiledClass helps find persistent classes. The parent, SqlFieldName, and Type properties on %Dictionary.CompiledProperty identify the owning class, projected SQL column, and property type. Finding that OEORD_Adm_DR has type User.Admission still requires a second lookup for that class's SQL mapping to get PA_Adm. The resulting relationships can expand arrows. Check the target table definition separately for an actual foreign key constraint.1516
The batch transpiler I committed June 25 used SQLGlot to turn Oracle SQL into MySQL and replace synchronized table names. When preparing this article, I passed the complete Caché query above to this version. The first Oracle syntax check failed. Calling the conversion function alone turned the three arrows into three nested JSON_EXTRACT() calls. The parser interpreted the arrow as JSON extraction, so naturally the output contained no PA_Adm.
How can a configuration expand a chain of arrows into JOINs?
One table can have several reference fields pointing to different tables, and two tables can have fields with the same name. The program must key its configuration lookup by both current source table name and reference field name. Here is a JSON design for this pathology query. Like the SQL above, the example uses a single source schema and omits synchronized table prefixes.
{
"tables": {
"DHC_AppPisArc": {
"tidb_table": "DHC_AppPisArc",
"references": { "AP_OrdItem": "OE_OrdItem" }
},
"OE_OrdItem": {
"tidb_table": "OE_OrdItem",
"tidb_id_column": "OEORI_RowID",
"references": { "OEORI_OEORD_ParRef": "OE_Order" }
},
"OE_Order": {
"tidb_table": "OE_Order",
"tidb_id_column": "OEORD_RowID",
"references": { "OEORD_Adm_DR": "PA_Adm" }
},
"PA_Adm": {
"tidb_table": "PA_Adm",
"tidb_id_column": "PAADM_RowID",
"columns": { "PAADM_Type": "PAADM_Type" }
}
}
}
The keys of tables are Caché table names, and tidb_table names each actual synchronized table. references maps the current table's reference field to the next Caché table. At that next table, tidb_id_column names the column holding the object ID in the synchronized database. Thus even if five fields point to the encounter table, we only need to specify PAADM_RowID once under PA_Adm. The columns mapping records source names and synchronized names, with a convention that unchanged names may be omitted. The example spells out the final value column.
The program starts at FROM DHC_AppPisArc a to identify the source table for alias a. Each -> triggers a lookup in references. By the third hop the current table is OE_Order, aliased ord. Looking up references["OEORD_Adm_DR"] gives PA_Adm. Read its synchronized table and ID column, assign alias adm, and the program can generate:
LEFT JOIN PA_Adm AS adm ON ord.OEORD_Adm_DR = adm.PAADM_RowID
There is no arrow after the final PAADM_Type. Emit adm.PAADM_Type using the current table's column mapping, leaving the original IN ('O', 'E') in the WHERE. Query semantics determine the join type. Default to LEFT JOIN when expanding an arrow. The statistical query above filters unmatched rows, permitting a further simplification to inner joins. For an arrow missing from the configuration, report the source table and field so the class definition can be checked.2
With the database fully mapped, this rule can be reused for chains of references joined through single-column object IDs. Converting arbitrary Caché SQL also requires parsing its dialect, resolving aliases at each query level, and writing rules for functions and syntax that differ between systems. That June, I made the Caché relationships explicit in SQL. For a separate batch of Oracle queries, recurring date functions and table replacements went into the batch transpiler.
Footnotes
-
InterSystems. (2019). Promoting interoperability standards and accelerating FHIR localization: InterSystems and partners support a Beijing Friendship Hospital research project. Customer case study. Page 1, iMedical, Health Connect, and project partners; page 3, encounter information. ↩
-
InterSystems. (n.d.). Implicit joins (arrow syntax). Using Caché SQL, Caché & Ensemble 2018.1. Opening paragraph. “Property Reference” in the same chapter compares the property declaration, arrow query, and explicit left join. ↩ ↩2 ↩3 ↩4
-
InterSystems. (n.d.). JOIN. Caché SQL Reference. Left Outer Join. ↩
-
InterSystems. (n.d.). Defining and compiling classes. Using Caché Objects. Inheritance and Compiling Classes. ↩ ↩2 ↩3
-
InterSystems. (n.d.). Introduction to persistent objects. Using Caché Objects. Introduction to the Default SQL Projection. ↩ ↩2 ↩3 ↩4 ↩5
-
InterSystems. (n.d.). Working with registered objects. Using Caché Objects. OREF Basics, the in-memory reference returned on creation. ↩
-
InterSystems. (n.d.). Introduction to Caché programming. Caché Programming Orientation Guide. Introduction, server processes, classes, and persistent data. ↩
-
InterSystems. (n.d.). CREATE TABLE. Caché SQL Reference. First paragraph of Description, persistent class corresponding to the table. ↩
-
gy_jerry. (2016, October 12). Caché Database Study Notes (2). CNBlogs. Creating a class, New dialog options and project view, original property declaration, and adding the SetData method. ↩ ↩2 ↩3 ↩4
-
Basic Development and Debugging with Caché. (n.d.). Zhihu. Original article. ↩
-
InterSystems. (n.d.). ALTER TABLE. Caché SQL Reference. Privileges and Locking, DDL restrictions on persistent classes. ↩
-
InterSystems. (n.d.). DdlAllowed. Caché Class Definition Reference. Default and Note. ↩
-
InterSystems. (n.d.). Studio menu reference. Using InterSystems Studio. Find in Files, searching the current namespace and opening matches. ↩
-
InterSystems. (n.d.). Adding SQL triggers and foreign keys to a class. Using InterSystems Studio. SqlTableName and SqlFieldName in Class Inspector. ↩ ↩2
-
InterSystems. (n.d.). %Dictionary.CompiledClass. Caché Class Reference. ClassType, SqlSchemaName, and SqlTableName in Property Inventory. ↩
-
InterSystems. (n.d.). %Dictionary.CompiledProperty. Caché Class Reference. parent, SqlFieldName, and Type in Property Inventory. ↩