How can I design a dynamic class schema generator in ObjectScript based on runtime JSON input?
Given a JSON schema at runtime, I want to programmatically create persistent classes with corresponding properties and indices. Is there a way to dynamically compile and load such classes?
Discussion (4)0
Comments
Hi Jack
IRIS does not provide built-in functionality to generate classes directly from a JSON Schema, unlike the support available for XML Schema (XSD). However, you can programmatically create and compile classes at runtime using the %Dictionary.ClassDefinition API.
Here is the sample code to generate a class.
ClassMethod CreateClass()
{
Set clsObj = ##class(%Dictionary.ClassDefinition).%New()
Set clsObj.Name="Test.NewClass"
Set clsObj.Super="%RegisteredObject,%JSON.Adaptor"
Set clsObj.Description="Class created via code"
Set clsObj.DdlAllowed = 1
Set clsObj.Inheritance="left"
Set propObj = ##class(%Dictionary.PropertyDefinition).%New()
Set propObj.Name="Name"
Set propObj.Type="%String"
Set propObj.SqlColumnNumber=2
Do propObj.Parameters.SetAt(70,"MAXLEN")
Set indexObj = ##class(%Dictionary.IndexDefinition).%New()
Set indexObj.Name="NameIdx"
Set indexObj.Properties="Name"
Do clsObj.Properties.Insert(propObj)
Do clsObj.Indices.Insert( indexObj)
Set st= clsObj.%Save()
D $SYSTEM.OBJ.Compile("Test.NewClass","ckb")
If $$$ISERR(st) w $SYSTEM.OBJ.DisplayError(st)
}Hi Ashok, this is really interesting but is it possibile in any way to add specific code to the generated class?
Hi @Lucrezia Puntorieri
Yes you can create a method and classmethod programmatically.
Set clsmethodObj = ##class(%Dictionary.MethodDefinition).%New()
Set clsmethodObj.Name="TestClsMethod"
Set clsmethodObj.ClassMethod=1
Do clsmethodObj.Implementation.WriteLine($C(9)_"Set ^test=""Test"" ")
Do clsmethodObj.Implementation.WriteLine($C(9)_"Quit ^test ")
Set methodObj = ##class(%Dictionary.MethodDefinition).%New()
Set methodObj.Name="TestMethod"
Set methodObj.ClassMethod=0
Do methodObj.Implementation.WriteLine($C(9)_"For I=1:1:10 { S ^test(i)=i} ")
Do methodObj.Implementation.WriteLine($C(9)_"Quit ^test ")
Do clsObj.Methods.Insert(clsmethodObj)
Do clsObj.Methods.Insert(methodObj)Thank you Ashok! This is really useful