Less Boilerplate, Auto-Conversion in ThingsDB v1.11.2
Working with strongly typed data stores is great, until you have to ingest a JSON or MessagePack payload from the outside world. JSON only knows a handful of primitives: strings, numbers, booleans, arrays, and objects.
Meanwhile, your database schema might use rich types like datetime, uuid, regex, set, enum, error, or references to existing typed instances. Previously, bridging that gap in ThingsDB meant writing repetitive mapping code every time data crossed the boundary.
Starting in ThingsDB v1.11.2, auto-conversion removes that boilerplate while keeping ThingsDB's strict type system intact where it matters most.
The Problem: Manual Mapping Boilerplate
Suppose you have a schema for tracking background jobs, users, and tasks:
set_enum('Status', { Pending: 0, Complete: 1, });
set_type('User', { id: '#', name: 'str', email: 'email', });
set_type('Task', { id: '#', name: 'str', status: 'Status', due: 'datetime?', err: 'error?', });
set_type('Job', { id: '#', title: 'str', user: '&User', tasks: '&{Task}', });
.users = [ User{name: 'Iris', email: '*Emails are not allowed*'}, ];
.jobs = [];
When an external client sends a Job payload over JSON or MessagePack, tasks arrives as an array (not a set), status arrives as an int or str (not a Status enum), due arrives as an ISO string (not a datetime), and user might just be a numeric ID.
Previously, your ingestion procedure had to manually cast and map every nested field:
new_procedure('add_job', |payload| {
job = Job{
title: payload.title,
user: User(payload.user),
tasks: set(payload.tasks.map(|t| Task{
name: t.name,
status: Status(t.status),
due: is_nil(t.due) ? nil : datetime(t.due),
err: is_nil(t.err) ? nil : err(t.err),
})),
};
.jobs.push(job);
job.wrap();
});
It works, it's safe and it gets tedious fast as your schemas grow.
The Solution: Auto-Conversion in Type(thing) and .assign()
With ThingsDB v1.11.2, you can pass the raw payload straight to the type constructor or .assign():
new_procedure('add_job', |payload| {
job = Job(payload);
.jobs.push(job);
job.wrap();
});
ThingsDB inspects the target type definition recursively and converts compatible values automatically:
// Incoming JSON/MessagePack payload
payload = {
title: 'Release v2.0',
user: 2, // Resolves to existing User with ID #2
tasks: [
{name: 'Run tests', status: 1, due: '2026-11-20T22:32:28Z'},
{name: 'Deploy', status: 'Pending'},
],
};
job = Job(payload);
Under the hood, that single Job(payload) call:
- Resolves
user: 2to the existing User instance with ID #2. - Converts the
tasksarray into a typed set (&{Task}). - Converts each task's
statusinto a Status enum (matching by member name first if it's astr, or by member value otherwise). - Parses the ISO 8601
duestring into a nativedatetime.
Updating an existing instance works the exact same way via .assign():
task.assign({ status: 'Complete', err: 'Deployment timed out', // Converted to err(-100, 'Deployment timed out') });
Strict Where You Write Code, Flexible Where You Ingest Data
A key design goal was making sure auto-conversion doesn't weaken ThingsDB's type safety inside regular code. Auto-conversion only triggers in two places:
- Initializing an instance from an existing thing:
Type(thing) - Updating an instance via
.assign():instance.assign(thing)
Direct literal instantiation (Type{...}) and standard property assignments (instance.prop = val) remain strictly typed:
// Auto-conversion applies here:
task = Task({name: 'Build', status: 0});
task.assign({status: 1});
// Strict typing still applies here:
Task{name: 'Build', status: 0}; // type_err(): mismatch in type `Task`
task.status = 0; // type_err(): mismatch in type `Task`
And even during auto-conversion, ThingsDB refuses lossy conversions. For example, JavaScript numbers don't distinguish between integers and floats, so 3.0 is accepted for an int property, while 3.1 raises a value_err() instead of silently truncating the fractional part:
set_type('Counter', {count: 'int'});
Counter({count: 3.0}); // OK -> 3
Counter({count: 3.1}); // value_err(): cannot convert float with fractional part to integer
What Gets Converted?
Here is a quick overview of supported conversions in v1.11.2:
- Numbers: Exact whole-number float ➜
int(including constrained variants likeuint,pint,nint, andint<min:max>), andint➜float. - Dates & Timestamps: ISO 8601
str➜datetime, andint/floatUNIX timestamps ➜timeval. - UUIDs: Standard UUID
stror 16-bytebytes(great for MessagePack binary UUIDs) ➜uuid. - Code & Patterns:
"/pattern/flags"str➜regex, and"|args| body"str➜closure. - Enums & Errors: Member name (
str) or member value ➜enum(all enum types supported), and messagestr➜error(with default code -100). - Collections & Nested Types:
array➜set, recursive conversion forarrayandthing<T>, andthingor instance ID (int/float) ➜ custom type instance.
Upgrade & Try It Out
Auto-conversion is available starting in ThingsDB v1.11.2. Check out the Auto-conversion documentation for the full conversion table and examples. If you're already using ThingsDB with JSON or MessagePack clients, give Type(payload) a try and let us know what you think!
Comments
No comments yet. Start the discussion.