Reading Caché ObjectScript: From q:condition to Saving and Querying Patient Objects

April 15, 2025

Caché was widely used in North American healthcare information systems. Epic’s electronic medical records in the United States are one example.1

The first time I read Caché code, a statement barely a dozen characters long stopped me. On April 15, 2025, I searched : colon in objectscript. This is how I recorded it:

    q:ResRowId="" ""  // if ResRowId == "": return ""

There are two empty strings here. If ResRowId is 42, which one gets returned? Neither: this line does not execute a return at all. Read the command to the left of the colon first, then separate the condition on the right from the argument.

How far does the colon reach?

I remember seeing these one-liners throughout the business system. I read the command in three pieces. q is the action (Quit), the attached :ResRowId="" is its execution condition, and "" after the space is the return value.2 An empty row ID makes the method return an empty string. A row ID of 42 skips this q and continues with the following commands. The IRIS 2025.1 manual calls this a postconditional. The colon touches the command, and a space separates the condition from the return value.34

A colon governs the command to which it is attached. A line can first assign a value and then decide whether to quit. The row ID below comes in as an argument. Each variable is spelled consistently. Commands can be written in upper or lower case, while variable names are case-sensitive.3

    s ResRowId=rowId q:ResRowId="" ""

For an unfamiliar one-letter command, consult the abbreviation table. The s, q and w used here mean SET, QUIT and WRITE.5

Read the s (Set) on the left first. This step always executes. Then read q: on the right. Treating the whole line as conditional would mistakenly put the first assignment under the colon too.

Caché is InterSystems’ database platform. ObjectScript is a language for server-side methods. It extends M, also called MUMPS, retaining single-letter commands and postconditionals while supporting classes and methods. Thus a single file can contain both terse s (Set) and q (Quit) commands and a ClassMethod resembling other object-oriented languages.6

How can one s write to the database?

In Caché name is a local variable, whereas ^DemoPatient(42,"Name") points to a database node. A structure prefixed by ^ is a global. Think of a persistent tree, with the subscripts in parentheses forming the path down to a node. Here the first level is the patient ID and the second the field name. Assigning to the node directly changes a stored value that remains after this program exits.78

Suppose a method receives id and name, with a business rule to update only a nonempty name. Here is a custom teaching global. In the comments, db denotes the persistent tree:

    q:id=""                  // if id == "": return
    s:name'="" ^DemoPatient(id,"Name")=name  // if name != "": db[id, "Name"] = name

The first line returns early from a method with no return value. Read the second left to right. s assigns, :name'="" is the condition and '= means “not equal.” ^DemoPatient(id,"Name") on the left of the assignment is the destination. With ID 42 and name “示例甲” (Example A), the node is ^DemoPatient(42,"Name"). Passing an empty name skips the entire s and preserves the old value.

A node on the right of the equals sign is read instead. For example, after validating the ID, a method returning the name can do this:

    s name=$g(^DemoPatient(id,"Name")) q:name="" ""  // name = db.get((id, "Name"), ""); if name == "": return ""
    q name

$g abbreviates $GET. It reads the node’s value, using an empty string as the default here when there is no value. Thus one line first reads the database, then decides whether to exit from that result. In my original note, q:ResRowId="" "" was also preceded by a read from a node with ^ and multiple subscripts. Knowing q means return gets you only halfway. Follow the subscripts to see which node it just read.9

This was a Caché selling point. In the Multidimensional Data Model section of its technology guide, InterSystems wrote: “The built-in Caché scripting languages support direct access to the multidimensional structures”. The s: command above is a concrete example: a business condition and database write fit in one ObjectScript command. The guide presents objects, SQL and direct multidimensional access as three interfaces.1011

How do you save a patient object and open it again by ID?

MyApp.Patient in the slides illustrates another interface, wrapping a patient record in a persistent class. I kept its name property and rewrote saving and reopening by ID in the one-line style familiar from the business code. Look first at the save line: %Save() runs on the left, and the right checks the resulting status before deciding whether to exit.

Class MyApp.Patient Extends %Persistent
{
Property Name As %String(MAXLEN = 50);

ClassMethod SaveAndRead(name As %String) As %Status
{
    s patient=..%New(),patient.Name=name
    s sc=patient.%Save() q:$SYSTEM.Status.IsError(sc) sc
    s id=patient.%Id()
    k patient
    s patient=..%OpenId(id,,.sc)
    w:$IsObject(patient) patient.Name,!
    q sc
}
}

With Extends %Persistent, the patient class inherits methods for saving and opening objects. .. denotes the current class, while patient. accesses the instance in hand. Follow the lines to see two different uses of the colon:12

  • q:$SYSTEM.Status.IsError(sc) sc returns the error status if saving fails, skipping ID retrieval and reading. On success it passes over q and gets the record ID from %Id(). %Save() returns a status, which cannot be used as an ID.
  • w:$IsObject(patient) patient.Name,! reads like the Python pseudocode if is_object(patient): print(patient.Name). w means Write and does not add a newline by default. Commas separate output items. patient.Name prints the name and ! emits a newline. The condition governs the entire w, so a false condition prints no blank line either.13

The earlier k patient (Kill) clears the local variable, leaving the saved record intact. %OpenId(id,,.sc) omits the second optional argument and returns the read status through the third, sc. The final q sc runs regardless of whether the name was printed.12

After compiling the class in the same namespace, you can use another one-liner in the terminal. On success the method prints “示例甲.” On failure the trailing d: (conditional Do) displays the error:

    s sc=##class(MyApp.Patient).SaveAndRead("示例甲") d:$SYSTEM.Status.IsError(sc) $SYSTEM.Status.DisplayError(sc)

If another application needs patients by ID, expose the read operation as a REST endpoint. For example, define GET /patients/42 to look up patient 42. In Caché, a dispatch class extending %CSP.REST can map the GET method and path /patients/:id to a class method in XData UrlMap. The method takes the path’s id, reads the existing record with %OpenId, and writes the result to the HTTP response.14

Does SQL query another copy of the patient data?

Under the class’s default mapping, the saved patient is already available through SQL. In a SQL query tool in the same namespace, run:

SELECT ID, Name
FROM MyApp.Patient
WHERE Name = '示例甲'

The ID of the newly inserted row is the same value returned by patient.%Id(). The object documentation says: “The table contains one record for each saved object”. The compiler generates an SQL table definition for the persistent class, with scalar property Name as a column. Report authors can query patients by condition, while business methods can open one by ID. Both access the same persistent data.15

External analytics tools can use this SQL interface too. In an Alteryx community discussion I opened on April 15, MSPOLAP12 read Caché data via ODBC (Open Database Connectivity) with Alteryx’s Input Data tool. They wrote “The connection is working fine for SQL queries.” For calling a stored procedure on the same connection, they said only that there appeared to be a limitation.16

One distinction matters here. MyApp.Patient has a class definition so the compiler knows how to map properties to columns. Our hand-written ^DemoPatient establishes just a two-level subscript convention. As an independent global, each node’s meaning is interpreted by the program. To make the tree available to reports, provide a corresponding mapping.7

When a property references another persistent object, SQL can follow it to read that object’s fields too. I encountered this later while migrating hospital reports: Which table does -> point to in Caché SQL, and how do you write an explicit JOIN?

Looking back at my idea for developing AI features on an existing hospital system, the patient class had a modest purpose. Save one record, obtain its ID and retrieve it through both objects and SQL. Completing those steps gives “development on an existing database” a testable starting point.

Further experience and discussion

Can Oracle, SAP and IBM also run business logic in a database?

Yes. Oracle7, released in 1992, already supported PL/SQL stored procedures and triggers. A stored procedure is a program stored in the database and callable by an application. For example, to deduct inventory the caller sends a product and quantity. The database checks conditions, updates records and returns a result, avoiding several round trips. IBM Db2 SQL PL and SAP ASE (formerly Sybase ASE) Transact-SQL also support procedures. SAP HANA calls its language SQLScript and emphasizes keeping data-intensive filters, joins and aggregations beside the data.1718

The line s:name'="" ^DemoPatient(id,"Name")=name adds another dimension: the language treats a database node itself as an assignment target. In a relational procedure the same condition might govern an UPDATE against a table. Here the two subscripts already specify the destination. For a closer syntactic parallel, YottaDB shares the M tradition and also uses ^ for persistent globals shared across processes.19

When is direct global access faster, and why did Epic add SQL?

Suppose transactions are stored as ^Txn(account,date,transactionNo). For one account on one day, the first two subscripts already narrow the range to a branch. Use $ORDER to retrieve successive transaction numbers. For one merchant across all accounts, the same tree helps less unless you also maintain a merchant index. Anil Mathew reported that his team tested several approaches in 2013 on Caché 2010. For those reports $ORDER traversal was fastest, followed by SQL, with opening individual objects slowest. For inserts and updates, he valued SQL’s maintenance of indexes and calculated fields. The post gave neither volumes nor timings, so the ranking belongs to that test alone.20

Where do you start when you do not even know the subscript order? I looked into that on July 3. In Aleksandar Kovacevic’s example, only the namespace USER, global ^Persons and keyword Email were known. His SQL directly invokes Caché’s built-in search.21

CALL %Library.Global_Find('USER','^Persons','Email')

The result lists node names and values. For example, ^Persons(1,"Email","Home") and ^Persons(1,"Email","Work") share the first two subscripts. The third distinguishes home and work email. With an unfamiliar global, this shows where the data is actually stored before deciding where to start traversal.21

Jean Millette’s team encountered a slow SQL query. Two tables each had about 160,000 records. Adding an index cut test-environment time from 35 seconds to under one second. The index also existed in production, but the query stayed slow. Tracing execution revealed that an upgrade had frozen the old query plan. For each record needing a match, the program still scanned the second table.22

Early Epic faced another requirement. Aaron Cornelius, who worked on Cohort Lab, recalled that around 1993–94 customers wanted to query Chronicles data alongside other systems. Epic integrated KB-SQL, compiling SQL queries into MUMPS routines and retaining direct global access where possible. Report authors could express what they wanted directly when joining several datasets.23

Can new reports miss records written directly to globals by old programs?

A developer maintaining a legacy Caché 2018.1 system later asked whether old programs could keep writing globals while new programs queried an SQL class mapped to the same data. Stephen Canzano pointed out that direct node writes bypass the new class’s index maintenance. A new record readable by ID may be missing in an indexed query. In his projects, mapped classes were read-only and the original write path remained. Any new index still had to be maintained by that path.24

An official teaching example I opened contains such an index. In Lookup3.cls, the DOB method uses $order(^PersonI("DOB", intdob, id)) for the next person ID under a particular birth date. Reading the subscripts explains why multiple people born the same day can be found and why changing a birth date without its index produces incorrect queries.25

Why can a trigger check pass while committed data violates the rule?

A trigger is code the database automatically calls on a specified event. On Ask TOM, Tom Kyte received a question about enforcing at most one primary currency per country with a trigger. Using two sessions, he showed the weakness of “change it, then count.” One session designated the dollar as primary, while another designated a different currency for the same country. Each saw only one when it checked. Once both committed there were two. One solution he offered stores primary currencies in a separate table keyed by country so each country naturally has one slot.26

When writing globals directly, what do transactions and locks each do?

How do transactions work? Consider a transfer. Suppose two demonstration balances start at 100 and 20 and only one process operates on them. Transfer 30 from A to B, deliberately roll back and observe both balances. The first line initializes balances before the transaction begins.

    s ^DemoBalance("A")=100,^DemoBalance("B")=20
    tstart
    s ^DemoBalance("A")=^DemoBalance("A")-30  // A 从 100 变成 70
    s ^DemoBalance("B")=^DemoBalance("B")+30  // B 从 20 变成 50
    trollback
    w ^DemoBalance("A")," ",^DemoBalance("B") // 输出 100 20

Replace trollback with tcommit, rerun from the first line, and the final output is 70 50. Underneath is the transaction journal. TSTART marks the beginning and both SET commands change nodes as they execute. On commit Caché marks successful completion in the journal. On rollback it uses the journal to undo the changes. Even if a problem arises after only the debit, TROLLBACK can restore A to 100.27

Why also use locks? If program A has lowered account A to 70 but not yet credited B, program B reading both globals directly could see 70 20. A subsequent rollback restores both balances, but the reader may already have calculated an incorrect total. To see only before- or after-transfer balances, readers and writers must follow the same locking convention.27

Consider two processes concurrently deducting 80 from a balance of 100. If both read 100, pass their checks and write back 20, only one deduction appears in the balance. Writers should acquire the same account lock before reading, checking and updating. When transferring between two accounts, all paths should acquire locks in the same account order so processes do not each hold one lock while waiting for the other.

Legacy locking code can also be read line by line. Suppose the following occur in a method that returns 0 on failure:

    l +^DemoAccountLock(id):3
    q:'$t 0  // if not acquired: return 0

The first line’s l means LOCK. The :3 after the lock name means wait up to three seconds. Only the colon touching q on the second line is a postconditional. After a timed lock, $t ($TEST) indicates acquisition. Release it after the protected operation with l -^DemoAccountLock(id). The Caché manual says “Locks work by convention”. A nightly batch that skips this same lock can still change balances directly.2827

The rollback example deliberately used ordinary SET. If $INCREMENT allocates a transaction number from a global counter, Caché retains that increment, so a rolled-back transaction may leave a gap in numbering.29

With applications and data on separate machines, how many network calls does a global read require?

In a 2015 article on Caché development for healthcare, 疯狂的拖鞋 wrote “一个命名空间可以访问多个数据库里的数据” (“a namespace can access data in multiple databases”). This explains something invisible in code. In ^DemoPatient(42,"Name") the subscripts select the patient and field, while namespace mapping selects the database, which may be on another machine.3031

Caché already had Enterprise Cache Protocol (ECP). Suppose several outpatient workstations connect to one application server and successively open the same patient. If the needed data is absent locally, the first read fetches it from the data server. Later local cache hits avoid remote reads. If another application server changes data, the data server coordinates cache consistency and locks. Adding application servers distributes the work of more simultaneous users.3132

IRIS sharding solves a different problem. To count five years of hospital laboratory tests, distribute rows in the test table across data nodes by shard key. The app submits one SQL query. Each node counts its portion concurrently and the results are combined. This distributes one large table’s data and computation. IRIS permits sharding alongside ECP, so more doctors opening charts and one report scanning more rows can be considered separately.3233

Does moving debits to a service layer make locking easier?

For “deduct 80 only if the balance covers it,” a service with account ID as primary key can let the database check and debit in one update:

UPDATE account SET balance = balance - 80
WHERE id = :id AND balance >= 80

The service checks the affected row count. One means success. Zero means the account is missing or funds are insufficient. If both online and nightly jobs send this update, both delegate the balance check to the database. Wrapping a read-then-write in Python’s threading.Lock alone gives each deployed process its own lock, so two requests can still read the old balance. Caché also offers SQL, and a conditional update can place the same rule with the data. If another account must be credited, both updates still belong in one transaction.727

Outlook: running Go or Python business logic inside the database

Running business logic close to data remains an active approach. Since 2022.1, InterSystems IRIS has supported embedded Python that can directly read and write globals in the database process. The PostgreSQL community also has plgo, which compiles Go functions into database extensions and lets them run SQL internally. For our transfer, a service previously sending separate debit and credit requests could call one database function, with both updates completing inside the same transaction.3435

Footnotes

  1. InterSystems. (2016, July 22). On data interoperability: Interview with Julie Lockner. InterSystems, Lockner on Epic’s Caché use in the US. See also Enlyft. (n.d.). Companies using InterSystems IRIS and its marketshare. Enlyft, Industries of IRIS users identified from public data. Enlyft covers a sample of IRIS users. For historical Caché use see the preceding source. ↩

  2. InterSystems. (n.d.). QUIT (ObjectScript). ObjectScript Reference, Command syntax and return value. ↩

  3. InterSystems. (n.d.). Syntax rules. Using Caché ObjectScript, see Postconditional Expressions and Case Sensitivity in the same chapter. ↩ ↩2

  4. InterSystems. (n.d.). ObjectScript syntax basics. Using ObjectScript, General syntax and case rules (rolling version), also see Postconditionals in IRIS 2025.1. ↩

  5. InterSystems. (n.d.). Abbreviations used in ObjectScript. ObjectScript Reference, Command abbreviation table. ↩

  6. InterSystems. (n.d.). Introducing ObjectScript. Using Caché ObjectScript, see Variables and Relationship with ISO Standard M. ↩

  7. InterSystems. (n.d.). Introduction to Caché programming. Caché Programming Orientation Guide, Direct Global Access. See also Concepts, Logical Storage. ↩ ↩2 ↩3

  8. InterSystems. (n.d.). SET. Caché ObjectScript Reference, Assignment targets and postconditionals. ↩

  9. InterSystems. (n.d.). $GET. Caché ObjectScript Reference, Retrieving values and defaults. ↩

  10. InterSystems. (n.d.). InterSystems Caché technology guide. Chapter 2, Caché’s Multidimensional Data Server. Quotation from the opening paragraph of Multidimensional Data Model. The Caché Advantage in the same chapter introduces the three interfaces. Original guide PDF, ODBMS.org archive. ↩

  11. InterSystems. (n.d.). InterSystems Caché technology. InterSystems, Technical notes on tables, objects and multidimensional arrays. ↩

  12. InterSystems. (n.d.). Working with persistent objects. Using Caché Objects, see Saving and opening objects and checking status. ↩ ↩2

  13. InterSystems. (n.d.). WRITE. Caché ObjectScript Reference, see WRITE with Arguments and formatting controls. ↩

  14. InterSystems. (n.d.). Creating REST services. Creating REST Services in Caché, URLMap with Route Elements. ↩

  15. InterSystems. (n.d.). Introduction to persistent objects. Using Caché Objects, see Introduction to the Default SQL Projection, paragraph 2. ↩

  16. MSPOLAP12. (2019, November 22). Comment on Intersystems Cache Database. Alteryx Community. Quotation in reply paragraph 1, stored procedures in paragraph 2. ↩

  17. Oracle. (n.d.). Introduction to Oracle Database. Oracle Database Concepts 19c, Oracle7 in Brief History of Oracle Database. IBM. (n.d.). SQL procedural language (SQL PL). Db2 for z/OS, Procedural SQL and control flow. ↩

  18. SAP. (n.d.). CREATE PROCEDURE. SAP ASE Reference Manual, Transact-SQL stored procedures. SAP. (n.d.). What is SQLScript?. SAP HANA SQLScript Reference, Executing data-intensive logic in the database. ↩

  19. YottaDB. (n.d.). Multi-language programmer’s guide. YottaDB Documentation, Notation for local variables and persistent globals. ↩

  20. Mathew, A. (2017, June 13). Comment on Is Caché SQL essential to Caché Objects? InterSystems Developer Community, Recollection of 2013 report read/write tests. ↩

  21. Kovacevic, A. (2020, April 26). Search within Globals (without class definitions). InterSystems Developer Community. See SQL call in the %Library.Global.Find section and the node list after its ObjectScript example. Visited July 3, 2025, followed by a search for Library.Global.Find. ↩ ↩2

  22. Millette, J. (2019, August 22). A case for thawing frozen query plans after upgrade. InterSystems Developer Community, Production investigation and data volume in comments. ↩

  23. Cornelius, A. (2024, May 3). SQL enters the Epic chat. Acorn Talks, Customer reporting needs and query compilation. ↩

  24. Canzano, S. (2025, September 5). Comment on Impact of SQL-mapped class indexes on legacy programs with direct global access. InterSystems Developer Community, Reply on legacy writes and read-only mappings. Example added during editing. ↩

  25. InterSystems. (n.d.). Lookup3.cls. Samples-ObjectScript, GitHub, see DOB method and birth-date index. ↩

  26. Kyte, T. (2008, September 1). The trouble with triggers. Oracle Connect, Two-session execution order and primary-key solution. ↩

  27. InterSystems. (n.d.). Using multidimensional storage (globals). Using Caché Globals, quotation in opening paragraph of Locks and Transactions; also see Managing Transactions in the same chapter. ↩ ↩2 ↩3 ↩4

  28. InterSystems. (n.d.). LOCK. Caché ObjectScript Reference, Incremental locks, timed waits and $TEST. ↩

  29. InterSystems. (n.d.). TROLLBACK. Caché ObjectScript Reference, What Is and Isn’t Rolled Back. ↩

  30. 疯狂的拖鞋. (2015, September 12). Development Notes on the Caché Healthcare Database. CNBlogs, quotation in “Mapping Between Namespaces and Databases”. ↩

  31. InterSystems. (n.d.). ECP. Caché Distributed Data Management Guide, Namespace mappings and application/data server responsibilities. ↩ ↩2

  32. InterSystems. (n.d.). Vertical & horizontal scalability with InterSystems IRIS. InterSystems, ECP and data sharding on the Database Management page. ↩ ↩2

  33. InterSystems. (n.d.). Horizontally scaling for data volume with sharding. InterSystems IRIS Scalability Guide, Shard keys and queries suitable for parallel processing. ↩

  34. InterSystems. (n.d.). New in InterSystems IRIS 2022.1. InterSystems IRIS Release Notes, Embedded Python and global access. ↩

  35. Magyar, V. (n.d.). plgo. GitLab, Go extensions executing SQL through PostgreSQL’s internal interface. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-04-15). Reading Caché ObjectScript: From q:condition to Saving and Querying Patient Objects. https://caiborui.com/blog/2025-04-15-zh-cache-objectscript-postconditionals-and-persistence-entrans

@misc{borui2025-78318dbd,
  author = {borui},
  title = {{Reading Caché ObjectScript: From q:condition to Saving and Querying Patient Objects}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-04-15-zh-cache-objectscript-postconditionals-and-persistence-entrans}
}