Quantcast
Viewing all articles
Browse latest Browse all 53708

Out-of-transaction database writes

Ancient wisdom goes that you cannot have more than one write transaction going on at the same time in a single session in NAV.

This is absolutely true, in and out.

Some features, like Activity Log, will leave you wanting to be able to write to the database outside of the normally running transaction.

Wouldn’t it just be beautiful if you could:

  • Write to the database, and then persist the change to the database even if an error happens during the transaction? (without cough! TryFunction, cough! cough!);
  • Not cause any locks to remain at the target table for any longer than it takes to do the write itself, without having to call COMMIT on your “regular” transaction; and
  • Not use temporary tables, because a system error (however unlikely) could cause the data to not be persisted if crash happens before temporary table is flushed to the physical one.

Well, in fact, you can do this.

Conceptually, you do this: encapsulate your write operation into a codeunit, then run this codeunit in a background session through STARTSESSION function. Whatever is done in a background session is done in a separate transaction, and if this session only does this write, then the lock will be immediately released.

To show this in practice, I’ll use the Activity Log table. It’s a perfect example, because this table can get pretty busy, and could cause locks if being written to from regular transaction, but won’t cause any locking issues whatsoever to those transactions that do nothing else but write to this table.

Writes to Activity Log are done by this function inside the Activity Log table itself:

Image may be NSFW.
Clik here to view.
image

The first thing I’ll do with this function is cut it from this table. Then, I’ll create a new codeunit, paste it into it, and then make these changes:

Image may be NSFW.
Clik here to view.
image

And that’s it. To test it, I wrote this:

Image may be NSFW.
Clik here to view.
image

On my slow laptop running in battery mode (meaning with processor clock rate reduced), I got this:

Image may be NSFW.
Clik here to view.
image

31 milliseconds per log entry may seam a lot, but it’s nothing when you think that all this is happening on a separate transaction that does not keep any locks for much longer. Actually, actual locking time is much shorter, because majority of these 31 ms per write actually goes onto session starting and ending overhead.

Cool, isn’t it? What do you think?


Read this post at its original location at http://vjeko.com/out-of-transaction-database-writes, or visit the original blog at http://vjeko.com. 5e33c5f6cb90c441bd1f23d5b9eeca34

The post Out-of-transaction database writes appeared first on Vjeko.com.

Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 53708

Trending Articles