Default TimeStamp Gotcha with ColdFusion ORM

Let’s say for example you have a simple forum on your site. When ever a new post is added, you want to associate a date/time with the post.

Using SQL and ColdFusion there are three ways to do this:

INSERT INTO
    Forum(body, dateTimeInserted)
VALUES(
    <cfqueryparam value="#form.body#" cfsqltype="cf_sql_longvarchar">,
    <cfqueryparam value="#now()#" cfsqltype="date">
)

OR

INSERT INTO
    Forum(body, dateTimeInserted)
VALUES(
    <cfqueryparam value="#form.body#" cfsqltype="cf_sql_longvarchar">,
    GETDATE()
)

OR

Set your default column value to ‘GETDATE()’ (in MSSQL)

INSERT INTO
    Forum(body)
VALUES(
    <cfqueryparam value="#form.body#" cfsqltype="cf_sql_longvarchar">
)

The third has always been the most recommended method. The reason being less network traffic and the SQL Server is the common denominator between the SQL Server and your application servers.

Now introduce ColdFusion ORM into the mix. The default value method still works when you set the property attribute of “insert” to false in your bean.

component persistent="true" table="Forum" {
    property name="ID" fieldType="id" generator="native";
    property name="body";
    property name="dateTimeInserted" insert="false";
}

However the case where it doesn’t work as needed is when you save the entity and load all the entities within the same ORM Session (ColdFusion request).

So let’s say our controller method looks like this in FW/1:

void function forum( required struct RC ) {
    if( structKeyExists( RC, "body" ) ) {
        getForumService().add( body = RC.body );
    }
    RC.forumEntities = getForumService().get();
}

Because the entity we just saved is still in the same ORM session, it doesn’t look at the database again for it. But because we rely upon SQL to add the timestamp, ORM doesn’t know about it yet. Thus it returns an empty string instead of the date and time it was added.

So we get something like this record set:

1|’Body 1’|’1/25/2014′
2|’Body 2’|’1/26/2014′
3|’Body 3’|”

This is of no use to me. I suppose I could loop through the array and if one has an empty date/time added value, then reload that entity, but that seems like overkill for my application.

So in the end, unless precise date/time stamps are needed, I’m going to use the application server’s date/time (now()) instead of SQL’s GETDATE() default.

void function add( required string body, required date dateTimeInserted ) {
    var forumEntity = entityNew('forum');
    forumEntity.setBody(arguments.body);
    forumEntity.setDateTimeInserted(arguments.dateTimeInserted);
    entitySave(forumEntity);
    ormFlush();
};
Advertisements

#coldfusion-2, #orm