[Go to site: main page, start]

0% found this document useful (0 votes)
97 views4 pages

ObjectScript Basics and Functions Guide

The document provides a reference for common ObjectScript commands and functions for working with objects, properties, lists, and more. It includes examples of how to call methods, create and open objects, set properties, save and delete objects, work with dates/times, strings, and lists, and more.

Uploaded by

Rodolfo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views4 pages

ObjectScript Basics and Functions Guide

The document provides a reference for common ObjectScript commands and functions for working with objects, properties, lists, and more. It includes examples of how to call methods, create and open objects, set properties, save and delete objects, work with dates/times, strings, and lists, and more.

Uploaded by

Rodolfo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ObjectScript Reference

Note: words in italics in the examples below are placeholders for actual values.

Object/SQL Basics
• Call a class method do ##class([Link]).method(arguments)
set variable = ##class([Link]).method(arguments)
Note: place a . before each pass-by-reference argument
• Call an instance method do [Link](arguments)
set variable = [Link](arguments)
Note: place a . before each pass-by-reference argument
• Create a new object set object = ##class([Link]).%New()
• Open an existing object by ID set object = ##class([Link]).%OpenId(id, concurrency, .status)
• Open an existing object by unique index value set object = ##class([Link]).IndexNameOpen(value, concurrency,
.status)
• Close an object (remove from process) set object = ""
• Write or set a property write [Link] set [Link] = value
• Write a class parameter write ..#PARAMETER write ##class([Link]).#PARAMETER
• Set a serial (embedded) property set [Link] = value
• Link two objects set [Link] = object2
• Save an object set status = object.%Save()
• Retrieve the ID of a saved object set id = object.%Id()
• Validate an object without saving set status = object.%ValidateObject()
• Validate a property without saving set status = ##class([Link]).PropertyIsValid([Link])
• Print status after error do $[Link](status)
write $[Link](status)
• Convert status into exception set ex = ##class(%[Link]).CreateFromStatus(status)
• Reload stored properties of object do object.%Reload()
• Retrieve stored property value of object directly ##class([Link]).PropertyGetStored(id)
• Delete an existing object by ID set status = ##class([Link]).%DeleteId(id)
• Delete an existing object by unique index value set status = ##class([Link]).IndexNameDelete(value)
• Delete all saved objects of a class do ##class([Link]).%DeleteExtent()
do ##class([Link]).%KillExtent()
• Clone an object set clonedObject = object.%ConstructClone()
• Determine if value exists in index set exists = ##class([Link]).IndexNameExists(value, .id)
• Populate a class do ##class([Link]).Populate(count, verbose)
• List all objects in process do $[Link]()
• Display all properties of an object do $[Link](object)
zwrite object
• Determine if variable is an object reference $isobject(variable) Note: returns 1 (true), 0 (false)
• Find classname of an object $classname(oref)
• Retrieve the OID of a saved object set oid = object.%Oid()
• Determine if object was modified in memory set variable = object.%IsModified()
• Declare a variable's type for IDE code completion #dim object as [Link]
• Start the SQL shell do $[Link]()
• Check SQL privileges $[Link]()

ObjectScript Commands
• Continue Stop current loop iteration, continue looping.
• Do Execute method, procedure, or routine.
• For {}, While {}, Do {} While Execute block of code repeatedly.
• Halt Stop process and close Terminal.
• If {} ElseIf {} Else {} Evaluate conditions and branch.
• Kill Destroy variable(s). Remove all objects in process.
• Quit, Return Terminate method, procedure, or routine. Optionally return value to calling
method. Terminate loops.
• Set Set value of variable.
• Try {} Catch {}, Throw Handle errors.
• Write Display text strings, value of variable or expression.
• ZWrite Display array, list string, bit string, JSON object/array (v2019.1+)

1
ObjectScript Reference

Note: words in italics in the examples below are placeholders for actual values.

ObjectScript Date/Time Functions and Special Variables


• Date conversion (internal à external) $zdate(internalDate, format)
• Date conversion (external à internal) $zdateh(“mm/dd/yyyy”)
• Time conversion (internal à external) $ztime(internalTime, format)
• Time conversion (external à internal) $ztimeh(“hh:mm:ss”)
• Current local date/time string $horolog
• Current UTC date/time string $ztimestamp

ObjectScript Branching Functions


• Return result for value of expression $case(expression, value1:result1, value2:result2, …, :result)
• Return result for first true condition $select(condition1:result1, condition2:result2, …, 1:resultN)

ObjectScript String Functions


• Extract characters from string $extract(string, start, end)
• Right-justify string within width characters $justify(string, width)
• Retrieve length of string $length(string)
• Retrieve number of delimited pieces in string $length(string, delimiter)
• Build a list string set listString = $listbuild(substrings separated by comma)
• Retrieve substring from list string $list(listString, position)
• Put substring into list string set $list(listString, position) = substring
• Retrieve number of substrings in list string $listlength(listString)
• Retrieve piece from delimited string $piece(string, delimiter, pieceNumber)
• Set piece into delimited string set $piece(string, delimiter, pieceNumber) = piece
• Replace/remove substring in string $replace(string, searchString, replaceString)
• Reverse a string $reverse(string)
• Replace/remove characters in string $translate(string, searchChars, replaceChars)

ObjectScript Existence Functions


• Determine if variable exists $data(variable)
• Return value of existing variable, or default $get(variable, default)
• Return next valid subscript in sparse array $order(array(subscript))

Additional ObjectScript Functions


• Increment ^global by 1 (or increment) $increment(^global, increment)
$sequence(^global)
• Match a regular expression $match(string, regularexpression)
• Generate random number $random(count) + start Note: start through (start+count-1)

ObjectScript Special Variables


• Process ID $job
• Current namespace $namespace
• Security roles $roles
• Security username $username

Utilities
• Change namespace set $namespace = “namespace”
do ^%CD
znspace "namespace"
• Display a global do ^%G
zwrite global

2
ObjectScript Reference

Note: words in italics in the examples below are placeholders for actual values.

List Collections
• Create a new standalone list set listObject=##class(%ListOfDataTypes).%New()
• Work with a list property Use methods below on a list collection property
• Insert an element at the end of a list do [Link](value)
do [Link](value)
• Insert an element into a list do [Link](value, position)
do [Link](value, position)
• Remove an element from a list do [Link](position)
do [Link](position)
• Retrieve an element of a list set variable = [Link](position)
set variable = [Link](position)
• Retrieve the size of a list set variable = [Link]()
set variable = [Link]()
• Clear all the elements of a list do [Link]()
do [Link]()

Array Collections
• Create a new standalone array set arrayObject=##class(%ArrayOfDataTypes).%New()
• Work with an array property Use methods below on an array collection property
• Insert an element into an array do [Link](value, key)
do [Link](value, key)
• Remove an element from an array do [Link](key)
do [Link](key)
• Retrieve an element of an array set variable = [Link](key)
set variable = [Link](key)
• Retrieve next key and its element set variable = [Link](.key)
set variable = [Link](.key)
Note: place a . before the pass-by-reference key argument
• Retrieve the size of an array set variable = [Link]()
set variable = [Link]()
• Clear all elements of an array do [Link]()
do [Link]()

Relationships
• Parent-to-children object linking do [Link](childObject)
set [Link] = parentObject
• One-to-many object linking do [Link](manyObject)
set [Link] = oneObject
• Retrieve a property of a child object set variable = [Link](position).property
• Retrieve a property of a many object set variable = [Link](position).property
• Retrieve next key set key = [Link](key)
set key = [Link](key)
• Retrieve the count of child/many objects set variable = [Link]()
set variable = [Link]()
• Open a many/child object directly set object = ##class([Link]).IDKEYOpen(parentID, childsub)
• Retrieve the id of a child object set status = ##class([Link]).IDKEYExists(parentID, childsub,
.childID)
• Clear the child/many objects do [Link]()
do [Link]()

3
ObjectScript Reference

Note: words in italics in the examples below are placeholders for actual values.

Streams
• Create a new stream set streamObject=##class(%[Link]).%New()
set streamObject=##class(%[Link]).%New()
or use methods below on a stream property
• Add text to a stream do [Link](text)
do [Link](text)
• Add a line of text to a stream do [Link](text)
do [Link](text)
• Read len characters of text from a stream write [Link](len)
write [Link](len)
• Read a line of text from a stream write [Link](len)
write [Link](len)
• Go to the beginning of a stream do [Link]()
do [Link]()
• Go to the end of a stream, for appending do [Link]()
do [Link]()
• Clear a stream do [Link]()
do [Link]()
• Display the length of a stream write [Link]
write [Link]

Unit Testing Macros


• Assert equality do $$$AssertEquals(value1, value2, message)
• Assert inequality do $$$AssertNotEquals(value1, value2, message)
• Assert status is OK do $$$AssertStatusOK(status, message)
• Assert status isn't OK do $$$AssertStatusNotOK(status, message)
• Assert condition is true do $$$AssertTrue(condition, message)
• Assert condition isn't true do $$$AssertNotTrue(condition, message)
• Log that assertion was skipped do $$$AssertSkipped(message)
• Log message do $$$LogMessage(message)

Other Macros
• Return a good status return $$$OK
• Return an error status return $$$ERROR($$$GeneralError, message)
• Check if status is good if $$$ISOK(status)
• Check if status is an error if $$$ISERR(status)
• Throw an exception if status is an error $$$ThrowOnError(status)
• Return a null object reference return $$$NULLOREF
• Place a new line within a string write string1_$$$NL_string2

Common questions

Powered by AI

To validate an object property in ObjectScript, use the method `##class(package.class).PropertyIsValid(object.Property)`, which returns a status indicating the validity of the property. To handle errors, utilize the `Try {} Catch {}, Throw` framework: within a `try` block, you can execute the validation and use the `catch` block to handle any exceptions, potentially using `$system.Status.DisplayError(status)` to display error details .

You would use the `$select` function over `$case` when you need to evaluate multiple conditions and return the result of the first true condition. The key difference is that `$select` evaluates conditions in order, whereas `$case` matches expression values to results. `$select` is more flexible and dynamic, allowing for complex decision-making pathways, while `$case` is straightforward for mapping discrete expression values .

To manage linking in a parent-to-children relationship in ObjectScript, first link the child object to the parent using `do parentObject.childRefProperty.Insert(childObject)`. To retrieve properties of child objects, use `set variable = parentObject.childRefProperty.GetAt(position).property` to access specific child properties. This approach facilitates structured hierarchical data management, allowing for robust handling of related data models .

You implement a stream in ObjectScript by creating a new stream object, e.g., `set streamObject=##class(%Stream.GlobalCharacter).%New()`. To add text, use `do streamObject.Write(text)` or `do streamObject.WriteLine(text)`. This method is advantageous because it allows efficient, sequential access and manipulation of large text data without loading entire files into memory, which is particularly useful for processing logs or large user-generated content .

In ObjectScript, to retrieve the stored value of a property directly from storage, you can use the method `##class(package.class).PropertyGetStored(id)`. This retrieves the value without needing to open the entire object, thus providing an efficient means to access specific data .

To convert an error status into an exception in ObjectScript, you utilize the class `%Exception.StatusException`. Use `set ex = ##class(%Exception.StatusException).CreateFromStatus(status)` to create an exception object from a status code. This is useful for handling specific types of errors where a catch block can capture exceptions thrown, providing a structured way to manage error scenarios and perform necessary cleanup or alternative actions .

In ObjectScript, lists are managed using methods like `Insert`, `SetAt`, and `GetAt`, e.g., `do listObject.Insert(value)`. Arrays, on the other hand, use methods that involve key-value operations like `SetAt(value, key)` and `GetAt(key)`. Lists are sequence-based collections optimized for ordered data, whereas arrays are key-based, optimized for associative arrays. Lists offer simpler, ordered access, while arrays provide indexed, direct access, which can lead to performance differences based on use case requirements .

ObjectScript supports unit testing via macros like `$$$AssertEquals`, `$$$AssertStatusOK`, and `$$$LogMessage`, which simplify writing tests by providing pre-defined assertions and logging. For example, `do $$$AssertEquals(value1, value2, message)` checks if two values are equal and logs the message if not. This macro-based approach reduces boilerplate code and focuses on test logic, making test writing efficient and improving code reliability by facilitating early error detection .

To determine if an object was modified in memory, you use the method `set variable = object.%IsModified()`, which returns a boolean indicating whether changes have been made to the object since it was last saved or opened. This is significant in ObjectScript because knowing an object's modification state is crucial for deciding whether to save changes back to the database or rollback, thus ensuring data consistency and integrity .

Within an ObjectScript application, performing a validity check on an SQL privilege using `$system.SQL.Security.CheckPrivilege()` is crucial for enforcing access control. This function returns a boolean indication of the user's privileges, which helps in preventing unauthorized access to sensitive SQL operations. This check allows applications to dynamically adapt their behavior based on user permissions, enhancing security and compliance .

You might also like