Learn How To Replicate A TFDMemTable Into An IBLite Table With FireDAC In Delphi 10.2 Tokyo

by Aug 24, 2018

The Field Service Template client app has offline capabilities which allows you to record changes offline without an internet connection. Later updates can be sent back up to the RAD Server once an internet connect is detected. One of the pieces of code in the Field Service Template client app that makes this possible is a function which will take the FireDAC JSON that is received from the RAD Server and store it as a table in IBLite.

As you will see in the source code below the procedure takes a table name, an TFDMemTable, a TFDTable, and a Recreate boolean parameter. In this instance TFDTable is connected to the IBLite database and TFDMemTable contains the FireDAC JSON from the server. The procedure first sets the Table name on the TFDTable. If Recreate is True it will overwrite the existing table if it exists. Next the FieldDefs in the TFDTable get cleared and then copied from the TFDMemTable into the TFDTable. Finally, the data from the TFDMemTable is copied (using CopyDataSet) into the TFDTable.


procedure TMainDM.SaveMemTableToIB(TableName: String; MemTable: TFDMemTable; FDTable: TFDTable; Recreate: Boolean);
     FDTable.TableName := TableName;
     if Recreate=True then
         FDTable.CopyDataSet(MemTable, [coStructure, coRestart, coAppend]);

And that is all there is to it. The data from the server table has now been replicated from the server into the IBLite database on the client. When the server data changes the client data just gets overwritten by the replication. One reason to use IBLite or SQLite this way is that any changes you do make to the data are automatically saved to disk (vs. a TFDMemTable which you would have to manually save). You might also want to use IBLite or SQLite if your data was quite large instead of holding it in a TFDMemTable in memory. Another reason is that if the schema changes on the server it will automatically get updated on the client.

The code to send changes back up to the server is separate. In this instance there is no data syncing going on here because the changes that are made on the client side and sent back to the server are mostly separate from the replicated dataFor syncing data between a client and RAD Server using FireDAC check out this sample.

Check out more information about the Field Service Template in the Deep Dive article about it.