Tuesday, August 1, 2017

mORMot on FHIR - Part 2 - ORM

In this blog, I want to try out some ORM feature of mORMot first.

Fist step, we save the Echo project from previous part to ORM project, and make a copy of SampleData.pas from mORMot's sample 01 to ORM's project folder, add this unit to the project:

Open SampleData.pas, we can see a class TSQLSampleRecord is defined, we can then add this class to the model when a TSQLModel is created so that the model now has one table/class:

Run the application and it has no problem. But we don't see where the table is created as the data server is a memory server, no persistence to any media, it is better to change the server to one of real database server, for convenience, we will use the default Sqlite database server.

The default Sqlite server class is TSQLRestServerDB, so we change the class TECHOServer to inherit from TSQLRestServerDB:

TECHOServer = class (TSQLRestServerDB)
  published
    procedure Echo(Ctxt: TSQLRestServerURIContext);
  end;
And the parameters for creating such a server is different from TSQLRestServerFullMemory, we just need to tell the server where the database file is:
aServer := TECHOServer.Create(aModel,
    ChangeFileExt(ExeVersion.ProgramFileName,'.db3'));
We can then ask the server to create the schema for us:
TSQLRestServerDB(aServer).CreateMissingTables;
That is it! (of cause, you need to add use units as we have changed the class)

After running the application, we can check the database file and there is the table created:


As you can see, without doing any explicit mapping configuration, the database schema is created automatically.