Archive for September, 2019

Doubling Down - Fixing Min/Max() for Doubles

Tuesday, September 17th, 2019

Today I discovered that the built-in overload for Min() and Max() double in the Math unit do not always work as expected when you don’t care about a great deal of precision.  If you search on how to compare floating point types there are many StackOverflow answers, none of which have been adopted over the years by the built-in library.  I have come across this issue of the comparison of floating type values more than once, but keep forgetting not to use built-in functions.  I discovered that the code I was using to determine the range of values was failing on

MyX := Max(MinDouble,0);

MyX was not 0 as I expected because the value is used for a measure of distance for which I only cared about 3 decimal places, so I created a new Math unit with functions that return the expected result.  Hopefully this helps someone else or prevents me from falling into the same hole again.  Naturally these methods should also have overloads for the other floating point types.

unit unMath;



function Max(const Value1, Value2 :double) :double;
function Min(const Value1, Value2 :double) :double;


function Max(const Value1, Value2 :double) :double;
  relationship :TValueRelationShip;
  relationship := CompareValue(Value1,Value2);
  if (relationship = GreaterThanValue) then
    Result := Value1
    Result := Value2;

function Min(const Value1, Value2 :double) :double;
  relationship :TValueRelationShip;
  relationship := CompareValue(Value1,Value2);
  if (relationship = LessThanValue) then
    Result := Value1
    Result := Value2;


Adding a New Attribute to hcOPF

Friday, September 13th, 2019

In order to support a client using SQL Server with replication I needed to add GUID support to hcOPF.  This post is a chronicle of my efforts.

If you’re unfamiliar with ThcAttribute you can breathe a sigh of relief.  It’s analagous to a barebones TField implementation which contains two native Delphi scalar fields used to store the original value of the attribute as read from the object store, and the current value as manipulated by the user.  It also contains two booleans to track whether the value of either field is actually NULL.  Using native Delphi fields of the corresponding type to the database field type minimizes the amount of memory required (a variant is 16 bytes), and still provides functionality similar to the Nullable types found in .NET.  If you’re talking to a database,  NULL <> ” or 0 so you need to provide full support for database NULLs.

First I created a new unit, hcGUIDAttribute and created a corresponding class descending from ThcAttribute.  Since a GUID doesn’t have many valid forms (you can’t convert it to a boolean, integer, or float for example) the number of methods that needed to be overridden is quite small.  Perhaps this is not the best example for what needs to be done when implementing a new attribute type, but it may provide some insight into the framework since ThcAttribute is a fundamental building block.

Since a GUID can really only be represented by a string, variant, or a TGUID we only have to override SetAsString, SetVarValue and their symmetric equivalents GetAsString, and GetAsVariant.

There are three abstract virtual methods on ThcAttribute.  All of these methods are declared as abstract because they must access the native Delphi fields used for the storage of values.  Since only descendants of ThcAttribute declare the private storage fields, these methods must be implemented in descendants, and the code is always the same:

SetOrigAsVariant():  This method sets the original value of the attribute as it was loaded from the database (assuming it ever was).  This method is used by the OriginalValue property to populate the native field FOriginalValue.  Since the framework populates the objects from the database, you may wonder why we need an OriginalValue property in the first place.  The answer is, so we can load single objects we know exist, from the datastore by populating it’s values and calling ThcObject.Read().  The framework also needs to be able to set an object’s OriginalValue as it propagates Primary Keys to child objects without knowing the native datatypes involved.

There are also two virtual methods that must be overriden in all descendants, but are not declared as abstract; ResetModified and UndoChanges.  These methods reset change tracking after the database has been updated, or reset the values back to those read from the database respectively,

Then I added code to ThcAbstractFactory.GetParameterValue for GUIDs and ThcAbstractFactory.PopulateAttributes method to populate the attribute from a database TField.  With a few miscellaneous support methods in the hcGUIDUtils unit  to generate new GUIDs and strip/add brackets to GUID strings it was ready.

Unlike most ORM/OPFs hcOPF supports complex PK/FK constaints and of types other than INT.  The SQL Server system I wrote that required GUID support has been running now for 10 years with minimal issues.

FireDAC TFDScript component - Bug or Feature?

Sunday, September 8th, 2019

When switching a project from using the Spring4D ORM to hcOPF I was forced to change the implementation of the CreateDatabase functionality that was so easy to implement using Spring4D.  Now I am using a TFDScript component with multiple scripts which naturally have to match the MetaData definitions used by hcOPF, but cannot be easily derived from that MetaData.

I dropped a FireDAC TFDScript component in my datamodule and added 3 named scripts:

TFDScript with 3 SQL Scripts

TFDScript with 3 SQL Scripts

Then in my CreateDatabase method I added code to execute each script like the following:

  Script := FDScript.SQLScripts.FindScript('CreateDatabaseContent');

Much to my surprise only the first script was executed followed by an AV, so I started tracing into the code only to find that the very first line of code in the ExecuteScript() method calls SQLScripts.Clear!  This means you cannot use the SQLScripts collection for any more than a single SQLScript at a time if you make this method call.  So why then would it be a public method?  Why would it even exist?  Why isn’t there an FDScript.ExecuteScriptByName(’CreateDatabaseContent’) method?

procedure TFDScript.ExecuteScript(const AScript: TStrings);
  SQLScripts.Add.SQL := AScript;
  SQLScriptFileName := '';
  if Status = ssFinishSuccess then

According to my interpretation of the documentation ExecuteAll should execute all scripts in the SQLScripts collection in the order in which they are defined. Using the FireDACMonitor and tracing through the code showed it only executed the first script (index 0).  As a result, my ugly hack to make the component work they way it should (correct me if I am wrong here) is:

  for I := FDScript.SQLScripts.Count -1 downto 0 do

Either I am missing something fundamental, or the TFDScript component is badly broken and/or documented. I have created RSP-26131 in case I haven’t lost my mind, so please vote for it.

hcOPF now supports FireDAC

Saturday, September 7th, 2019

In my last post I talked about how unfortunately Spring4D does not provide change notifications so that developers can easily determine if an object graph has been modified and needs to be persisted.  It was primarily for this reason I decided to change the persistence layer in my latest project to hcOPF.  Obviously, I’m more familiar with this ORM, and I know it’s viable because systems I have authored 10 years ago are still being used without issue.  Even though I am using Delphi Rio 10.3.2, with lots of new language features, I don’t have time to thoroughly investigate and learn other alternatives. Change notifications will allow me to implement data auditing, and the validation & binding framework functionality will ensure any data editing is easily crafted.

Unfortunately, IBX no longer works well with Firebird 3.04 even if you can actually find a version for the latest Delphi editions.  I already ran into issues with UIB supporting larger varchar columns so that was not an option.  Instead, I decided to implement support for FireDAC, in part because it had been requested and because my Spring4D implementation with FireDAC proved to be performant.  The implementation was basically a copy/paste/modify of another DAL layer.  It currently does not support StoredProcs, but queries work. More testing and additional unit tests are needed, but it should allow developers to get started using FireDAC.

I also added support for quoted column names which is a Firebird requirement if you use mixed case names.  I’ve been dogfooding it for about a week now, and ironing out a few issues encountered.  I’m pleased with the performance, as hcOPF seems to be faster than my Spring4D ORM implementation.  If I get time I will try to put together some benchmark comparisons.  My only explanation for this would be Spring’s use of RTTI.

FireDAC was added for Rio and then Tokyo. Projects should be easy to back port to other recent Delphi versions. There is one demo specific to FireDAC in the Demos folder with projects for Rio. That should show you how to get started, and it’s essentially the same for all DALs;  create a datamodule, drop a connection and all the hcOPF components on it, link them, and configure your database connection.

FireDAC DataModule Components

FireDAC DataModule Components for a Firebird Database

Spring4D ORM Change Tracking

Sunday, September 1st, 2019

Spring4D’s ORM uses an instance of an IEntityMap to perform change tracking. The default implementation is essentially a threadsafe wrapper around a Dictionary that uses an entitykey of the classname + ‘$’ + the object Id and the Value portion is an array of member values. If an object instance is present in the EntityMap, IsMapped() returns True.

As objects are mapped from ResultSets, they are added to the the EntityMap capturing their values as read from the database. If you want to see what changes were made to the objects you must call GetChangedMembers() which returns a list of attributes for columns that have changed. In effect Spring4D keeps two copies of the data for a given object: the data in the object instance itself and the EntityMap, which is a reasonably compact version of the data as it was originally read from the database result set.

hcOPF takes a different approach, in that each object instance essentially has 2 identical field variables for each attribute and a boolean field to track Nulls. The advantage of this approach is that you can easily test each attribute to see if it’s NULL or has been changed, in user code without testing all of them. Since the implementation does not use RTTI it is likely faster, and hcOPF Attributes surface change notifications. Of course the trade off is larger object instances.

Change Notifications are a very powerful mechanism for both the framework and developer code. They can be used to trigger attribute level validations, provide GUI feedback of modification status and provide for very granular efficient calculations on attributes. In fact these change notifications are the basis for hcOPF’s ability to save an object graph to the database by simply calling object.Save on the root object.  Some frameworks like mORMot have even implemented database auditing tracking.

Sadly, Change Notifications are something missing from the Spring4D ORM. If you want to know if a an object has been Modified you can of course add a FModified boolean field and set it in each property setter after checking if the value being set differs from the current value. It’s a roll your own state tracking that you would expect the ORM to do for you, and it doesn’t take into account situations where the user modifies an object property and then changes it back either by Undoing the change, or changing it back to the original value.

In developer code, change notifications can dramatically simplify logic to save data when the application allows users to modify numerous root objects with the ability to undo changes. It can become quite difficult to determine what method calls are required to save all changes with Spring4D when you don’t know what has been changed in the first place.

Visual Studio’s Rebuild vs. Build

Sunday, September 1st, 2019

Build of course, like most tools, only compiles files that have changed since the last time a compilation was performed.

Rebuild of course, like most tools, re-compiles all source files regardless of whether they have changed since the last successful compile or not.

Simple right?  Not exactly….there are some subtle undocumented differences.  If a configuration file such as an appsettings.json file exists in your project, it is normally meant to be copied to your output folder for use by the application when you run it.  If you update this file, and Build or run the project VS.NET does not update the file in the output folder.  This has bewildered me on more than one occasion.  Only when you perform a Rebuild on that project (or solution) does the newer file get copied to the output folder.

Some intellisense errors in the IDE code editor involving code from other assemblies are also only resolvable by performing a rebuild.  I don’t recall the specific circumstances, but suffice to say, when in doubt perform a Rebuild.