Add custom database mapping hooks

This commit is contained in:
jdb
2026-09-02 12:21:23 -05:00
parent 170359d840
commit 06b568e071
6 changed files with 197 additions and 43 deletions
+25
View File
@@ -293,6 +293,31 @@ Distinct types backed by a supported type are parsed through their backing
type and then converted to the distinct type. This also applies when the
distinct type is nested in an `Option`_ or `seq`.
Custom Database Mappings
------------------------
A model module can customize conversion from the database's string
representation by exporting a ``fromDbHook`` overload:
.. code-block:: Nim
import std/strutils
type Money* = object
cents*: int64
proc fromDbHook*(_: typedesc[Money], value: string): Money =
Money(cents: value.parseBiggestInt)
The overload must take ``typedesc[TargetType]`` and ``string``, and return
``TargetType``. It must be visible where Fiber ORM's generated query code is
declared, so export it when the type lives in another module.
Fiber ORM uses a custom mapping before its built-in conversion for a value.
``Option`` and ``seq`` remain structural: an absent optional value does not
call the hook, while present optional values and individual sequence values
do. Exceptions raised by the hook propagate to the caller.
.. [#f1] Note that this implies that all `NULL`-able fields should be typed
as optional using `Option[fieldType]`. Conversely, any fields with
non-optional types should also be constrained to be `NOT NULL` in