Transactions, Live Queries & Frameworks
Because @ahmadmoussawi/webdb/orm binds explicitly to a WebDB instance (or transaction lease), ACID transactions, nested savepoints, cross-tab reactive queries, and full-text search all compose cleanly in the same app.
1. ACID Transactions & Savepoints (orm.transaction)
Calling orm.transaction(async (tx) => ...) acquires a WebDB transaction lease, binds every repository on tx to the transactional database handle, and automatically commits or rolls back if an error is thrown:
const createdUser = await orm.transaction(async (tx) => {
const user = await tx.users.create({
name: "Alice",
email: "[email protected]",
passwordHash: "hash_123",
});
await tx.posts.create({
authorId: user.id,
title: "Inside an Atomic Transaction",
published: true,
});
// Nested savepoints roll back independently without aborting the outer transaction
await tx
.transaction(async (sp) => {
await sp.roles.create({ name: "temp_role" });
throw new Error("Revert inner savepoint only");
})
.catch(() => {});
return user;
});
// Automatic post-commit rebinding:
// Instances returned from `orm.transaction()` are safely rebound to the outer `db`
// so calling `save()` or `refresh()` later never fails with an expired transaction error!
createdUser.name = "Alice Post-Commit";
await createdUser.save();If an error escapes the outer orm.transaction(...) callback, every write across IndexedDB / OPFS rolls back atomically.
2. Reactive Live Queries (.live() & .liveFirst())
Any ModelQueryBuilder supports .live() and .liveFirst(), returning a standard LiveQueryController that automatically tracks:
- The model's primary table
- Every related target table in
.with(...)and.withCount(...) - Every
belongsToManypivot table involved in eager loads - Nested relation tables referenced inside
.whereHas(...)/.whereDoesntHave(...)
Whenever any tracked table changes—in the current tab, in an orm.transaction(), in a background Web Worker, or in another open browser tab via BroadcastChannel—the live query re-executes and delivers fresh, hydrated model instances:
// Watch a list query with eager-loaded posts
const controller = orm.users
.query()
.where("isActive", "=", true)
.with({
posts: {
where: (q) => q.where("published", "=", true),
},
})
.withCount({ posts: true })
.live((users, state) => {
console.log("Updated active users:", users.length);
console.log("Last updated:", state.lastUpdated);
});
// Watch a single model instance
const profileLive = orm.users
.where("id", "=", userId)
.with({ profile: true })
.liveFirst((user) => {
renderProfile(user);
});
// Async iteration is built into LiveQueryController:
for await (const users of controller) {
updateView(users);
if (done) break;
}
// Force refresh or clean up when done:
await controller.refresh();
controller.destroy();
profileLive.destroy();3. Using the ORM with React, Vue 3 & Angular
Because ORM query methods (orm.users.query().with(...).get()) execute WebDB queries underneath, WebDB's ActiveReadTracker automatically detects reads during useLiveQuery / liveQuerySignal. For clarity (and to watch nested relations or empty results consistently), pass { db: orm.db, tables: [...] } when combining with framework adapters:
React (@ahmadmoussawi/webdb/react)
import { useLiveQuery } from "@ahmadmoussawi/webdb/react";
import { orm } from "./db";
export function AuthorFeed() {
const { data: authors, isLoading } = useLiveQuery(
() =>
orm.users
.query()
.where("isActive", "=", true)
.with({ posts: { where: (q) => q.where("published", "=", true) } })
.get(),
[],
{ db: orm.db, tables: ["users", "posts"] },
);
if (isLoading || !authors) return <p>Loading...</p>;
return (
<ul>
{authors.map((user) => (
<li key={user.id}>
{user.name} ({user.relations.posts.length} posts)
</li>
))}
</ul>
);
}Vue 3 (@ahmadmoussawi/webdb/vue)
<script setup lang="ts">
import { useLiveQuery } from "@ahmadmoussawi/webdb/vue";
import { orm } from "./db";
const { data: authors } = useLiveQuery(
() => orm.users.query().with({ posts: true }).get(),
{ db: orm.db, tables: ["users", "posts"] },
);
</script>
<template>
<ul v-if="authors">
<li v-for="user in authors" :key="user.id">
{{ user.name }} ({{ user.relations.posts.length }} posts)
</li>
</ul>
</template>Angular (@ahmadmoussawi/webdb/angular)
import { Component } from "@angular/core";
import { liveQuerySignal } from "@ahmadmoussawi/webdb/angular";
import { orm } from "./db";
@Component({
selector: "app-authors",
template: `
@for (user of authors.data() ?? []; track user.id) {
<div>{{ user.name }} ({{ user.relations.posts.length }})</div>
}
`,
})
export class AuthorsComponent {
authors = liveQuerySignal(
() => orm.users.query().with({ posts: true }).get(),
{ db: orm.db, tables: ["users", "posts"] },
);
}See Live Queries (React, Vue, Angular, JS) for full adapter options (debounceMs, onError, initialData).
4. Full-Text Search & Raw Query Interop
orm.db exposes the underlying WebDB handle directly, so you can combine ORM models with @ahmadmoussawi/webdb/search, custom JavaScript UDFs, or binary snapshots:
import { createSearchIndex } from "@ahmadmoussawi/webdb/search";
const postSearch = createSearchIndex(orm.db, {
table: "posts",
fields: [{ name: "title", weight: 10, highlight: true }],
});
const result = await postSearch.search("local frist", {
fuzzy: true,
limit: 10,
});
// Re-hydrate search hits back into full ORM Post instances with relations:
const postIds = result.hits.map((h) => h.row.id as string);
const hydratedPosts = await orm.posts
.query()
.whereIn("id", postIds)
.with({ author: true })
.get();