SlintORM
Docsnpm

Context Propagation & Prepared Statements

Context Propagation

SlintORM provides a per-request/scope context store accessible throughout your data layer. Use orm.withContext(ctx) to attach metadata and orm.getContext() to retrieve it.

API Reference

MethodDescription
orm.withContext(ctx)Set the context object for the current request/scope.
orm.getContext()Retrieve the current context object.
orm.clearContext()Clear the current context — call in finally blocks.

Common use cases include request IDs for tracing, authenticated user IDs, tenant isolation in multi-tenant apps, and correlation IDs for distributed logging.

Setting context per request

handler.ts
// Set context for the current request/scope
import { orm } from './db';

async function handleRequest(req: Request) {
  // Attach request metadata
  orm.withContext({
    requestId: crypto.randomUUID(),
    userId: req.headers.get('x-user-id'),
    tenant: req.headers.get('x-tenant-id'),
  });

  try {
    const users = await orm.db.User.findAll();
    return Response.json(users);
  } finally {
    // Always clear to prevent leaking across requests
    orm.clearContext();
  }
}

Using context in hooks

models/user.ts
// Access context anywhere in your query pipeline
import { orm } from './db';

const User = orm.defineModel<User>('users', 'User', {
  onCreateBefore(data) {
    const ctx = orm.getContext();
    if (ctx?.userId) {
      return { ...data, createdBy: ctx.userId };
    }
    return data;
  },
});

Prepared Statement Mode

SQLite supports prepared statements — compiled SQL that can be reused with different parameters. SlintORM wraps this with an LRU cache (max 200 statements) to avoid re-parsing repeated queries.

API Reference

MethodDescription
orm.preparedMode(boolean)Toggle prepared statement caching on/off.
orm.isPreparedMode()Return whether prepared mode is active.

Enabling prepared mode

db.ts
// Toggle prepared statement caching
import ORMManager from 'slintorm';

const orm = new ORMManager({
  driver: 'sqlite',
  databaseUrl: './dev.db',
});

// Enable prepared mode
orm.preparedMode(true);
console.log('Prepared mode:', orm.isPreparedMode()); // true

// Queries are now cached as prepared statements
const users = await orm.db.User.findAll({ age: { gt: 18 } });

// Disable when done
orm.preparedMode(false);

Cache behavior & performance

The cache holds up to 200 prepared statements with LRU eviction. This is most effective for hot paths — loops, batch operations, or frequently re-executed queries where only parameters change between invocations.

loop-example.ts
// Internal LRU cache behavior
// Max 200 prepared statements cached
// Eviction: LRU (least recently used)

// This is especially beneficial for repeated queries:
for (const id of userIds) {
  // With prepared mode on, the SQL is compiled once
  // and only the parameter changes on each iteration
  const user = await orm.db.User.findById(id);
}
PreviousPluginsNextDatabase Resolver